about summary refs log tree commit diff
path: root/src/engine
diff options
context:
space:
mode:
authorMagnus Auvinen <magnus.auvinen@gmail.com>2007-08-22 07:52:33 +0000
committerMagnus Auvinen <magnus.auvinen@gmail.com>2007-08-22 07:52:33 +0000
commit8b3c16e6152a527f9aec1a88a9eed74119de7000 (patch)
treef0bde5cea15e696e42cade06a3b12ff6b13acc57 /src/engine
parent9899666a7ce6679a3b9667ab09f615f4d0769c16 (diff)
downloadzcatch-8b3c16e6152a527f9aec1a88a9eed74119de7000.tar.gz
zcatch-8b3c16e6152a527f9aec1a88a9eed74119de7000.zip
major engine cleanup. dependency on baselib removed. engine is now C code (not ansi tho). some other cruft removed aswell
Diffstat (limited to 'src/engine')
-rw-r--r--src/engine/client/client.c (renamed from src/engine/client/client.cpp)288
-rw-r--r--src/engine/client/gfx.c (renamed from src/engine/client/gfx.cpp)322
-rw-r--r--src/engine/client/inp.c95
-rw-r--r--src/engine/client/snd.c (renamed from src/engine/client/snd.cpp)446
-rw-r--r--src/engine/client/ui.c (renamed from src/engine/client/ui.cpp)11
-rw-r--r--src/engine/client/ui.h16
-rw-r--r--src/engine/compression.c (renamed from src/engine/compression.cpp)58
-rw-r--r--src/engine/compression.h6
-rw-r--r--src/engine/config.c (renamed from src/engine/config.cpp)117
-rw-r--r--src/engine/config.h14
-rw-r--r--src/engine/datafile.c (renamed from src/engine/datafile.cpp)251
-rw-r--r--src/engine/datafile.h34
-rw-r--r--src/engine/detect.h114
-rw-r--r--src/engine/external/glfw/include/GL/glfw.h486
-rw-r--r--src/engine/external/glfw/lib/enable.c295
-rw-r--r--src/engine/external/glfw/lib/fullscreen.c95
-rw-r--r--src/engine/external/glfw/lib/glext.c201
-rw-r--r--src/engine/external/glfw/lib/image.c629
-rw-r--r--src/engine/external/glfw/lib/init.c108
-rw-r--r--src/engine/external/glfw/lib/input.c280
-rw-r--r--src/engine/external/glfw/lib/internal.h210
-rw-r--r--src/engine/external/glfw/lib/joystick.c101
-rw-r--r--src/engine/external/glfw/lib/macosx/macosx_enable.c42
-rw-r--r--src/engine/external/glfw/lib/macosx/macosx_fullscreen.c126
-rw-r--r--src/engine/external/glfw/lib/macosx/macosx_glext.c52
-rw-r--r--src/engine/external/glfw/lib/macosx/macosx_init.c194
-rw-r--r--src/engine/external/glfw/lib/macosx/macosx_joystick.c50
-rw-r--r--src/engine/external/glfw/lib/macosx/macosx_thread.c414
-rw-r--r--src/engine/external/glfw/lib/macosx/macosx_time.c112
-rw-r--r--src/engine/external/glfw/lib/macosx/macosx_window.c1279
-rw-r--r--src/engine/external/glfw/lib/macosx/platform.h349
-rw-r--r--src/engine/external/glfw/lib/stream.c194
-rw-r--r--src/engine/external/glfw/lib/tga.c405
-rw-r--r--src/engine/external/glfw/lib/thread.c340
-rw-r--r--src/engine/external/glfw/lib/time.c83
-rw-r--r--src/engine/external/glfw/lib/win32/glfwdll.def67
-rw-r--r--src/engine/external/glfw/lib/win32/glfwdll_mgw1.def67
-rw-r--r--src/engine/external/glfw/lib/win32/glfwdll_mgw2.def67
-rw-r--r--src/engine/external/glfw/lib/win32/glfwdll_pellesc.def65
-rw-r--r--src/engine/external/glfw/lib/win32/platform.h468
-rw-r--r--src/engine/external/glfw/lib/win32/win32_dllmain.c60
-rw-r--r--src/engine/external/glfw/lib/win32/win32_enable.c155
-rw-r--r--src/engine/external/glfw/lib/win32/win32_fullscreen.c317
-rw-r--r--src/engine/external/glfw/lib/win32/win32_glext.c101
-rw-r--r--src/engine/external/glfw/lib/win32/win32_init.c356
-rw-r--r--src/engine/external/glfw/lib/win32/win32_joystick.c234
-rw-r--r--src/engine/external/glfw/lib/win32/win32_thread.c511
-rw-r--r--src/engine/external/glfw/lib/win32/win32_time.c146
-rw-r--r--src/engine/external/glfw/lib/win32/win32_window.c1697
-rw-r--r--src/engine/external/glfw/lib/window.c727
-rw-r--r--src/engine/external/glfw/lib/x11/platform.h415
-rw-r--r--src/engine/external/glfw/lib/x11/x11_enable.c51
-rw-r--r--src/engine/external/glfw/lib/x11/x11_fullscreen.c524
-rw-r--r--src/engine/external/glfw/lib/x11/x11_glext.c69
-rw-r--r--src/engine/external/glfw/lib/x11/x11_init.c275
-rw-r--r--src/engine/external/glfw/lib/x11/x11_joystick.c371
-rw-r--r--src/engine/external/glfw/lib/x11/x11_keysym2unicode.c902
-rw-r--r--src/engine/external/glfw/lib/x11/x11_thread.c507
-rw-r--r--src/engine/external/glfw/lib/x11/x11_time.c154
-rw-r--r--src/engine/external/glfw/lib/x11/x11_window.c1746
-rw-r--r--src/engine/external/important.txt5
-rw-r--r--src/engine/external/pa.c40
-rw-r--r--src/engine/external/pnglite/pnglite.c (renamed from src/engine/client/pnglite/pnglite.c)0
-rw-r--r--src/engine/external/pnglite/pnglite.h (renamed from src/engine/client/pnglite/pnglite.h)0
-rw-r--r--src/engine/external/portaudio/changes.txt3
-rw-r--r--src/engine/external/portaudio/pa_allocation.c243
-rw-r--r--src/engine/external/portaudio/pa_allocation.h104
-rw-r--r--src/engine/external/portaudio/pa_converters.c1935
-rw-r--r--src/engine/external/portaudio/pa_converters.h263
-rw-r--r--src/engine/external/portaudio/pa_cpuload.c105
-rw-r--r--src/engine/external/portaudio/pa_cpuload.h72
-rw-r--r--src/engine/external/portaudio/pa_debugprint.c107
-rw-r--r--src/engine/external/portaudio/pa_debugprint.h148
-rw-r--r--src/engine/external/portaudio/pa_dither.c213
-rw-r--r--src/engine/external/portaudio/pa_dither.h100
-rw-r--r--src/engine/external/portaudio/pa_endianness.h141
-rw-r--r--src/engine/external/portaudio/pa_front.c1760
-rw-r--r--src/engine/external/portaudio/pa_hostapi.h253
-rw-r--r--src/engine/external/portaudio/pa_linux_alsa.c3323
-rw-r--r--src/engine/external/portaudio/pa_linux_alsa.h70
-rw-r--r--src/engine/external/portaudio/pa_mac_core.c2238
-rw-r--r--src/engine/external/portaudio/pa_mac_core.h171
-rw-r--r--src/engine/external/portaudio/pa_mac_core_blocking.c564
-rw-r--r--src/engine/external/portaudio/pa_mac_core_blocking.h133
-rw-r--r--src/engine/external/portaudio/pa_mac_core_internal.h162
-rw-r--r--src/engine/external/portaudio/pa_mac_core_utilities.c611
-rw-r--r--src/engine/external/portaudio/pa_mac_core_utilities.h205
-rw-r--r--src/engine/external/portaudio/pa_mac_hostapis.c87
-rw-r--r--src/engine/external/portaudio/pa_process.c1772
-rw-r--r--src/engine/external/portaudio/pa_process.h750
-rw-r--r--src/engine/external/portaudio/pa_ringbuffer.c285
-rw-r--r--src/engine/external/portaudio/pa_ringbuffer.h198
-rw-r--r--src/engine/external/portaudio/pa_skeleton.c816
-rw-r--r--src/engine/external/portaudio/pa_stream.c150
-rw-r--r--src/engine/external/portaudio/pa_stream.h205
-rw-r--r--src/engine/external/portaudio/pa_trace.c97
-rw-r--r--src/engine/external/portaudio/pa_trace.h79
-rw-r--r--src/engine/external/portaudio/pa_types.h107
-rw-r--r--src/engine/external/portaudio/pa_unix_hostapis.c78
-rw-r--r--src/engine/external/portaudio/pa_unix_oss.c1946
-rw-r--r--src/engine/external/portaudio/pa_unix_util.c666
-rw-r--r--src/engine/external/portaudio/pa_unix_util.h224
-rw-r--r--src/engine/external/portaudio/pa_util.h159
-rw-r--r--src/engine/external/portaudio/pa_win_ds.c2197
-rw-r--r--src/engine/external/portaudio/pa_win_ds_dynlink.c166
-rw-r--r--src/engine/external/portaudio/pa_win_ds_dynlink.h94
-rw-r--r--src/engine/external/portaudio/pa_win_hostapis.c100
-rw-r--r--src/engine/external/portaudio/pa_win_util.c147
-rw-r--r--src/engine/external/portaudio/pablio.c314
-rw-r--r--src/engine/external/portaudio/pablio.h116
-rw-r--r--src/engine/external/portaudio/portaudio.h1134
-rw-r--r--src/engine/external/wavpack/arm.S461
-rw-r--r--src/engine/external/wavpack/arml.S491
-rw-r--r--src/engine/external/wavpack/bits.c140
-rw-r--r--src/engine/external/wavpack/coldfire.S525
-rw-r--r--src/engine/external/wavpack/float.c50
-rw-r--r--src/engine/external/wavpack/license.txt25
-rw-r--r--src/engine/external/wavpack/metadata.c105
-rw-r--r--src/engine/external/wavpack/readme.txt68
-rw-r--r--src/engine/external/wavpack/unpack.c785
-rw-r--r--src/engine/external/wavpack/wavpack.h384
-rw-r--r--src/engine/external/wavpack/words.c560
-rw-r--r--src/engine/external/wavpack/wputils.c351
-rw-r--r--src/engine/external/wavpack/wvfilter.c.no_compile200
-rw-r--r--src/engine/external/zlib/VERSION1
-rw-r--r--src/engine/external/zlib/adler32.c149
-rw-r--r--src/engine/external/zlib/compress.c79
-rw-r--r--src/engine/external/zlib/crc32.c423
-rw-r--r--src/engine/external/zlib/crc32.h441
-rw-r--r--src/engine/external/zlib/deflate.c1736
-rw-r--r--src/engine/external/zlib/deflate.h331
-rw-r--r--src/engine/external/zlib/gzio.c1026
-rw-r--r--src/engine/external/zlib/infback.c623
-rw-r--r--src/engine/external/zlib/inffast.c318
-rw-r--r--src/engine/external/zlib/inffast.h11
-rw-r--r--src/engine/external/zlib/inffixed.h94
-rw-r--r--src/engine/external/zlib/inflate.c1368
-rw-r--r--src/engine/external/zlib/inflate.h115
-rw-r--r--src/engine/external/zlib/inftrees.c329
-rw-r--r--src/engine/external/zlib/inftrees.h55
-rw-r--r--src/engine/external/zlib/trees.c1219
-rw-r--r--src/engine/external/zlib/trees.h128
-rw-r--r--src/engine/external/zlib/uncompr.c61
-rw-r--r--src/engine/external/zlib/zconf.h332
-rw-r--r--src/engine/external/zlib/zconf.in.h332
-rw-r--r--src/engine/external/zlib/zlib.h1357
-rw-r--r--src/engine/external/zlib/zutil.c318
-rw-r--r--src/engine/external/zlib/zutil.h269
-rw-r--r--src/engine/interface.h168
-rw-r--r--src/engine/keynames.c523
-rw-r--r--src/engine/keys.h85
-rw-r--r--src/engine/map.c (renamed from src/engine/map.cpp)5
-rw-r--r--src/engine/msg.c53
-rw-r--r--src/engine/msg.cpp54
-rw-r--r--src/engine/network.c (renamed from src/engine/network.cpp)349
-rw-r--r--src/engine/network.h104
-rw-r--r--src/engine/packer.c89
-rw-r--r--src/engine/packer.h34
-rw-r--r--src/engine/packet.h315
-rw-r--r--src/engine/protocol.h34
-rw-r--r--src/engine/ringbuffer.h84
-rw-r--r--src/engine/server/server.c659
-rw-r--r--src/engine/server/server.cpp702
-rw-r--r--src/engine/snapshot.c441
-rw-r--r--src/engine/snapshot.cpp263
-rw-r--r--src/engine/snapshot.h119
-rw-r--r--src/engine/system.c560
-rw-r--r--src/engine/system.h522
168 files changed, 60624 insertions, 2524 deletions
diff --git a/src/engine/client/client.cpp b/src/engine/client/client.c
index a4cb4509..ab4b7109 100644
--- a/src/engine/client/client.cpp
+++ b/src/engine/client/client.c
@@ -1,29 +1,25 @@
-#include <baselib/system.h>
-#include <baselib/config.h>
-#include <baselib/input.h>
-#include <baselib/audio.h>
-#include <baselib/stream/file.h>
 
 #include <string.h>
 #include <stdarg.h>
 #include <stdlib.h>
 #include <stdio.h>
 #include <math.h>
-#include <engine/interface.h>
 
-#include <engine/packet.h>
-#include <engine/snapshot.h>
+#include <engine/system.h>
+#include <engine/interface.h>
 #include "ui.h"
 
+#include <engine/versions.h>
+
+#include <engine/protocol.h>
+#include <engine/snapshot.h>
 #include <engine/compression.h>
 #include <engine/network.h>
-#include <engine/versions.h>
 #include <engine/config.h>
+#include <engine/packer.h>
 
 #include <mastersrv/mastersrv.h>
 
-using namespace baselib;
-
 static int info_request_begin;
 static int info_request_end;
 static int snapshot_part;
@@ -33,42 +29,15 @@ static float latency = 0;
 static int extra_polating = 0;
 static int debug_font;
 static float frametime = 0.0001f;
-static net_client net;
-static netaddr4 master_server;
-static netaddr4 server_address;
+static NETCLIENT *net;
+static NETADDR4 master_server;
+static NETADDR4 server_address;
 static int window_must_refocus = 0;
 static int snaploss = 0;
 
 static int current_tick = 0;
 static float intratick = 0;
 
-
-// --- input wrappers ---
-static int keyboard_state[2][input::last];
-static int keyboard_current = 0;
-static int keyboard_first = 1;
-
-void inp_mouse_relative(int *x, int *y) { input::mouse_position(x, y); }
-int inp_mouse_scroll() { return input::mouse_scroll(); }
-int inp_key_pressed(int key) { return keyboard_state[keyboard_current][key]; }
-int inp_key_was_pressed(int key) { return keyboard_state[keyboard_current^1][key]; }
-int inp_key_down(int key) { return inp_key_pressed(key)&&!inp_key_was_pressed(key); }
-int inp_button_pressed(int button) { return input::pressed(button); }
-
-void inp_update()
-{
-	if(keyboard_first)
-	{
-		// make sure to reset
-		keyboard_first = 0;
-		inp_update();
-	}
-	
-	keyboard_current = keyboard_current^1;
-	for(int i = 0; i < input::last; i++)
-		keyboard_state[keyboard_current][i] = input::pressed(i);
-}
-
 // --- input snapping ---
 static int input_data[MAX_INPUT_SIZE] = {0};
 static int input_data_size;
@@ -87,94 +56,31 @@ enum
 	NUM_SNAPSHOT_TYPES=2,
 };
 
-struct snapshot_info
-{
-	snapshot_info *prev;
-	snapshot_info *next;
-	
-	int tick;
-	int64 recvtime;
-	snapshot *snap;
-};
-
-static snapshot_info *first_snapshot = 0;
-static snapshot_info *last_snapshot = 0;
-
-static snapshot_info *client_snapshot_add(int tick, int64 time, void *data, int data_size)
-{
-	snapshot_info *holder = (snapshot_info*)mem_alloc(sizeof(snapshot_info) + data_size, 1);
-	holder->tick = tick;
-	holder->recvtime = time;
-	holder->snap = (snapshot *)(holder+1);
-	mem_copy(holder->snap, data, data_size);
-	
-	holder->next =0x0;
-	holder->prev = last_snapshot;
-	if(last_snapshot)
-		last_snapshot->next = holder;
-	else
-		first_snapshot = holder;
-	last_snapshot = holder;
-	
-	return holder;
-}
-
-static snapshot_info *client_snapshot_find(int tick)
-{
-	snapshot_info *current = first_snapshot;
-	while(current)
-	{
-		if(current->tick == tick)
-			return current;
-		current = current->next;
-	}
-	
-	return 0;
-}
-
-static void client_snapshot_purge_until(int tick)
-{
-	snapshot_info *current = first_snapshot;
-	while(current)
-	{
-		snapshot_info *next = current->next;
-		if(current->tick < tick)
-			mem_free(current);
-		else
-			break;
-		
-		current = next;
-		current->prev = 0;
-		first_snapshot = current;
-	}
-	
-	if(!first_snapshot)
-		last_snapshot = 0;
-}
-
-static snapshot_info *snapshots[NUM_SNAPSHOT_TYPES];
+SNAPSTORAGE snapshot_storage;
+static SNAPSTORAGE_HOLDER *snapshots[NUM_SNAPSHOT_TYPES];
 static int recived_snapshots;
 static char snapshot_incomming_data[MAX_SNAPSHOT_SIZE];
 
 // ---
 
-const void *snap_get_item(int snapid, int index, snap_item *item)
+const void *snap_get_item(int snapid, int index, SNAP_ITEM *item)
 {
 	dbg_assert(snapid >= 0 && snapid < NUM_SNAPSHOT_TYPES, "invalid snapid");
-	snapshot::item *i = snapshots[snapid]->snap->get_item(index);
-	item->type = i->type();
-	item->id = i->id();
-	return (void *)i->data();
+	SNAPSHOT_ITEM *i = snapshot_get_item(snapshots[snapid]->snap, index);
+	item->type = snapitem_type(i);
+	item->id = snapitem_id(i);
+	return (void *)snapitem_data(i);
 }
 
 const void *snap_find_item(int snapid, int type, int id)
 {
 	// TODO: linear search. should be fixed.
-	for(int i = 0; i < snapshots[snapid]->snap->num_items; i++)
+	int i;
+	for(i = 0; i < snapshots[snapid]->snap->num_items; i++)
 	{
-		snapshot::item *itm = snapshots[snapid]->snap->get_item(i);
-		if(itm->type() == type && itm->id() == id)
-			return (void *)itm->data();
+		SNAPSHOT_ITEM *itm = snapshot_get_item(snapshots[snapid]->snap, i);
+		if(snapitem_type(itm) == type && snapitem_id(itm) == id)
+			return (void *)snapitem_data(itm);
 	}
 	return 0x0;
 }
@@ -225,7 +131,7 @@ int menu_loop(); // TODO: what is this?
 // ----- send functions -----
 int client_send_msg()
 {
-	const msg_info *info = msg_get_info();
+	const MSG_INFO *info = msg_get_info();
 	NETPACKET packet;
 	mem_zero(&packet, sizeof(NETPACKET));
 	
@@ -236,7 +142,7 @@ int client_send_msg()
 	if(info->flags&MSGFLAG_VITAL)	
 		packet.flags = PACKETFLAG_VITAL;
 	
-	net.send(&packet);
+	netclient_send(net, &packet);
 	return 0;
 }
 
@@ -265,9 +171,6 @@ static void client_send_entergame()
 static void client_send_error(const char *error)
 {
 	/*
-		pack(NETMSG_CLIENT_ERROR, "s", error);
-	*/
-	/*
 	packet p(NETMSG_CLIENT_ERROR);
 	p.write_str(error);
 	send_packet(&p);
@@ -280,7 +183,8 @@ static void client_send_input()
 {
 	msg_pack_start_system(NETMSG_INPUT, 0);
 	msg_pack_int(input_data_size);
-	for(int i = 0; i < input_data_size/4; i++)
+	int i;
+	for(i = 0; i < input_data_size/4; i++)
 		msg_pack_int(input_data[i]);
 	msg_pack_end();
 	client_send_msg();
@@ -290,14 +194,15 @@ static void client_send_input()
 // ------ server browse ----
 static struct 
 {
-	server_info infos[MAX_SERVERS];
+	SERVER_INFO infos[MAX_SERVERS];
 	int64 request_times[MAX_SERVERS];
-	netaddr4 addresses[MAX_SERVERS];
+	NETADDR4 addresses[MAX_SERVERS];
 	int num;
 } servers;
+
 static int serverlist_lan = 1;
 
-int client_serverbrowse_getlist(server_info **serverlist)
+int client_serverbrowse_getlist(SERVER_INFO **serverlist)
 {
 	*serverlist = servers.infos;
 	return servers.num;
@@ -327,7 +232,7 @@ void client_serverbrowse_refresh(int lan)
 		packet.flags = PACKETFLAG_CONNLESS;
 		packet.data_size = sizeof(SERVERBROWSE_GETINFO);
 		packet.data = SERVERBROWSE_GETINFO;
-		net.send(&packet);	
+		netclient_send(net, &packet);	
 		
 		// reset the list
 		servers.num = 0;		
@@ -343,7 +248,7 @@ void client_serverbrowse_refresh(int lan)
 		packet.flags = PACKETFLAG_CONNLESS;
 		packet.data_size = sizeof(SERVERBROWSE_GETLIST);
 		packet.data = SERVERBROWSE_GETLIST;
-		net.send(&packet);	
+		netclient_send(net, &packet);	
 		
 		// reset the list
 		servers.num = 0;
@@ -365,7 +270,7 @@ static void client_serverbrowse_request(int id)
 	packet.flags = PACKETFLAG_CONNLESS;
 	packet.data_size = sizeof(SERVERBROWSE_GETINFO);
 	packet.data = SERVERBROWSE_GETINFO;
-	net.send(&packet);
+	netclient_send(net, &packet);
 	servers.request_times[id] = time_get();
 }
 
@@ -413,7 +318,8 @@ void client_connect(const char *server_address_str)
 	strncpy(buf, server_address_str, 512);
 	
 	const char *port_str = 0;
-	for(int k = 0; buf[k]; k++)
+	int k;
+	for(k = 0; buf[k]; k++)
 	{
 		if(buf[k] == ':')
 		{
@@ -430,7 +336,7 @@ void client_connect(const char *server_address_str)
 	if(net_host_lookup(buf, port, &server_address) != 0)
 		dbg_msg("client", "could not find the address of %s, connecting to localhost", buf);
 	
-	net.connect(&server_address);
+	netclient_connect(net, &server_address);
 	client_set_state(CLIENTSTATE_CONNECTING);	
 	current_tick = 0;
 }
@@ -438,15 +344,15 @@ void client_connect(const char *server_address_str)
 void client_disconnect()
 {
 	client_send_error("disconnected");
-	net.disconnect("disconnected");
+	netclient_disconnect(net, "disconnected");
 	client_set_state(CLIENTSTATE_OFFLINE);
 	map_unload();
 }
 
-static bool client_load_data()
+static int client_load_data()
 {
 	debug_font = gfx_load_texture("data/debug_font.png");
-	return true;
+	return 1;
 }
 
 static void client_debug_render()
@@ -464,7 +370,7 @@ static void client_debug_render()
 	{
 		last_snap = time_get();
 		prev = current;
-		net.stats(&current);
+		netclient_stats(net, &current);
 	}
 	
 	static float frametime_avg = 0;
@@ -488,7 +394,7 @@ void client_quit()
 
 const char *client_error_string()
 {
-	return net.error_string();
+	return netclient_error_string(net);
 }
 
 static void client_render()
@@ -521,7 +427,8 @@ static void client_process_packet(NETPACKET *packet)
 			info_request_begin = 0;
 			info_request_end = 0;
 
-			for(int i = 0; i < servers.num; i++)
+			int i;
+			for(i = 0; i < servers.num; i++)
 			{
 				servers.infos[i].num_players = 0;
 				servers.infos[i].max_players = 0;
@@ -543,18 +450,18 @@ static void client_process_packet(NETPACKET *packet)
 			memcmp(packet->data, SERVERBROWSE_INFO, sizeof(SERVERBROWSE_INFO)) == 0)
 		{
 			// we got ze info
-			data_unpacker unpacker;
-			unpacker.reset((unsigned char*)packet->data+sizeof(SERVERBROWSE_INFO), packet->data_size-sizeof(SERVERBROWSE_INFO));
+			UNPACKER up;
+			unpacker_reset(&up, (unsigned char*)packet->data+sizeof(SERVERBROWSE_INFO), packet->data_size-sizeof(SERVERBROWSE_INFO));
 			
 			if(serverlist_lan)
 			{
 				if(servers.num != MAX_SERVERS)
 				{
 					int i = servers.num;
-					strncpy(servers.infos[i].name, unpacker.get_string(), 128);
-					strncpy(servers.infos[i].map, unpacker.get_string(), 128);
-					servers.infos[i].max_players = unpacker.get_int();
-					servers.infos[i].num_players = unpacker.get_int();
+					strncpy(servers.infos[i].name, unpacker_get_string(&up), 128);
+					strncpy(servers.infos[i].map, unpacker_get_string(&up), 128);
+					servers.infos[i].max_players = unpacker_get_int(&up);
+					servers.infos[i].num_players = unpacker_get_int(&up);
 					servers.infos[i].latency = 0;
 					
 					sprintf(servers.infos[i].address, "%d.%d.%d.%d:%d",
@@ -569,14 +476,15 @@ static void client_process_packet(NETPACKET *packet)
 			}
 			else
 			{
-				for(int i = 0; i < servers.num; i++)
+				int i;
+				for(i = 0; i < servers.num; i++)
 				{
 					if(net_addr4_cmp(&servers.addresses[i], &packet->address) == 0)
 					{
-						strncpy(servers.infos[i].name, unpacker.get_string(), 128);
-						strncpy(servers.infos[i].map, unpacker.get_string(), 128);
-						servers.infos[i].max_players = unpacker.get_int();
-						servers.infos[i].num_players = unpacker.get_int();
+						strncpy(servers.infos[i].name, unpacker_get_string(&up), 128);
+						strncpy(servers.infos[i].map, unpacker_get_string(&up), 128);
+						servers.infos[i].max_players = unpacker_get_int(&up);
+						servers.infos[i].num_players = unpacker_get_int(&up);
 						servers.infos[i].latency = ((time_get() - servers.request_times[i])*1000)/time_freq();
 						if(config.debug)
 							dbg_msg("client", "got server info");
@@ -637,21 +545,20 @@ static void client_process_packet(NETPACKET *packet)
 						snapshot_part = 0;
 						
 						// find snapshot that we should use as delta 
-						static snapshot emptysnap;
+						static SNAPSHOT emptysnap;
 						emptysnap.data_size = 0;
 						emptysnap.num_items = 0;
 						
-						snapshot *deltashot = &emptysnap;
+						SNAPSHOT *deltashot = &emptysnap;
 						
 						// find delta
 						if(delta_tick >= 0)
 						{
 							//void *delta_data;
-							snapshot_info *delta_info = client_snapshot_find(delta_tick);
-							//deltashot_size = snapshots_new.get(delta_tick, 0, &delta_data);
-							if(delta_info)
-								deltashot = delta_info->snap;
-							else
+							
+							int deltashot_size = snapstorage_get(&snapshot_storage, delta_tick, 0, &deltashot);
+							
+							if(deltashot_size < 0)
 							{
 								// couldn't find the delta snapshots that the server used
 								// to compress this snapshot. force the server to resync
@@ -684,7 +591,7 @@ static void client_process_packet(NETPACKET *packet)
 						//dbg_msg("UNPACK", "%d unpacked with %d", game_tick, delta_tick);
 						
 						unsigned char tmpbuffer3[MAX_SNAPSHOT_SIZE];
-						int snapsize = snapshot_unpack_delta(deltashot, (snapshot*)tmpbuffer3, deltadata, deltasize);
+						int snapsize = snapshot_unpack_delta(deltashot, (SNAPSHOT*)tmpbuffer3, deltadata, deltasize);
 
 						// purge old snapshots				
 						int purgetick = delta_tick;
@@ -692,11 +599,12 @@ static void client_process_packet(NETPACKET *packet)
 							purgetick = snapshots[SNAP_PREV]->tick;
 						if(snapshots[SNAP_CURRENT] && snapshots[SNAP_CURRENT]->tick < purgetick)
 							purgetick = snapshots[SNAP_PREV]->tick;
-						client_snapshot_purge_until(purgetick);
+						snapstorage_purge_until(&snapshot_storage, purgetick);
 						//client_snapshot_purge_until(game_tick-50);
 						
 						// add new
-						snapshot_info *snap = client_snapshot_add(game_tick, time_get(), tmpbuffer3, snapsize);
+						snapstorage_add(&snapshot_storage, game_tick, time_get(), snapsize, (SNAPSHOT*)tmpbuffer3);
+						//SNAPSTORAGE_HOLDER *snap = client_snapshot_add(game_tick, time_get(), tmpbuffer3, snapsize);
 						
 						//int ncrc = snapshot_crc((snapshot*)tmpbuffer3);
 						//if(crc != ncrc)
@@ -708,22 +616,17 @@ static void client_process_packet(NETPACKET *packet)
 
 						if(current_tick > 0)
 							snaploss += game_tick-current_tick-1;
-						
 						current_tick = game_tick;
 						
 						// we got two snapshots until we see us self as connected
-						if(recived_snapshots <= 2)
-						{
-							snapshots[SNAP_PREV] = snapshots[SNAP_CURRENT];
-							snapshots[SNAP_CURRENT] = snap;
-						}
-						
 						if(recived_snapshots == 2)
 						{
+							snapshots[SNAP_PREV] = snapshot_storage.first;
+							snapshots[SNAP_CURRENT] = snapshot_storage.last;
 							local_start_time = time_get();
 							client_set_state(CLIENTSTATE_ONLINE);
 						}
-						
+
 						int64 now = time_get();
 						int64 t = now - game_tick*time_freq()/50;
 						if(game_start_time == -1 || t < game_start_time)
@@ -762,18 +665,18 @@ static void client_process_packet(NETPACKET *packet)
 
 static void client_pump_network()
 {
-	net.update();
+	netclient_update(net);
 
 	// check for errors		
-	if(client_state() != CLIENTSTATE_OFFLINE && net.state() == NETSTATE_OFFLINE)
+	if(client_state() != CLIENTSTATE_OFFLINE && netclient_state(net) == NETSTATE_OFFLINE)
 	{
 		// TODO: add message to the user there
 		client_set_state(CLIENTSTATE_OFFLINE);
-		dbg_msg("client", "offline error='%s'", net.error_string());
+		dbg_msg("client", "offline error='%s'", netclient_error_string(net));
 	}
 
 	//
-	if(client_state() == CLIENTSTATE_CONNECTING && net.state() == NETSTATE_ONLINE)
+	if(client_state() == CLIENTSTATE_CONNECTING && netclient_state(net) == NETSTATE_ONLINE)
 	{
 		// we switched to online
 		dbg_msg("client", "connected, sending info");
@@ -783,7 +686,7 @@ static void client_pump_network()
 	
 	// process packets
 	NETPACKET packet;
-	while(net.recv(&packet))
+	while(netclient_recv(net, &packet))
 		client_process_packet(&packet);
 }
 
@@ -818,7 +721,7 @@ static void client_run(const char *direct_connect_server)
 	// open socket
 	NETADDR4 bindaddr;
 	mem_zero(&bindaddr, sizeof(bindaddr));
-	net.open(bindaddr, 0);
+	net = netclient_open(bindaddr, 0);
 	
 	//
 	net_host_lookup(config.masterserver, MASTERSERVER_PORT, &master_server);
@@ -827,8 +730,6 @@ static void client_run(const char *direct_connect_server)
 	if(direct_connect_server)
 		client_connect(direct_connect_server);
 		
-	//int64 inputs_per_second = 50;
-	//int64 time_per_input = time_freq()/inputs_per_second;
 	int64 game_starttime = time_get();
 	int64 last_input = game_starttime;
 	
@@ -836,7 +737,7 @@ static void client_run(const char *direct_connect_server)
 	int64 reportinterval = time_freq()*1;
 	int frames = 0;
 	
-	input::set_mouse_mode(input::mode_relative);
+	inp_mouse_mode_relative();
 	
 	while (1)
 	{	
@@ -849,7 +750,7 @@ static void client_run(const char *direct_connect_server)
 			int64 now = time_get();
 			while(1)
 			{
-				snapshot_info *cur = snapshots[SNAP_CURRENT];
+				SNAPSTORAGE_HOLDER *cur = snapshots[SNAP_CURRENT];
 				int64 tickstart = game_start_time + (cur->tick+1)*time_freq()/50;
 				int64 t = tickstart;
 				if(latency > 0)
@@ -857,7 +758,7 @@ static void client_run(const char *direct_connect_server)
 
 				if(t < now)
 				{
-					snapshot_info *next = snapshots[SNAP_CURRENT]->next;
+					SNAPSTORAGE_HOLDER *next = snapshots[SNAP_CURRENT]->next;
 					if(next)
 					{
 						snapshots[SNAP_PREV] = snapshots[SNAP_CURRENT];
@@ -913,12 +814,12 @@ static void client_run(const char *direct_connect_server)
 		inp_update();
 		
 		// refocus
+		// TODO: fixme
+		
 		if(!gfx_window_active())
 		{
 			if(window_must_refocus == 0)
-			{
-				input::set_mouse_mode(input::mode_absolute);
-			}
+				inp_mouse_mode_absolute();
 			window_must_refocus = 1;
 		}
 
@@ -926,13 +827,13 @@ static void client_run(const char *direct_connect_server)
 		{
 			if(window_must_refocus < 3)
 			{
-				input::set_mouse_mode(input::mode_absolute);
+				inp_mouse_mode_absolute();
 				window_must_refocus++;
 			}
 
-			if(inp_button_pressed(input::mouse_1))
+			if(inp_key_pressed(KEY_MOUSE_1))
 			{
-				input::set_mouse_mode(input::mode_relative);
+				inp_mouse_mode_relative();
 				window_must_refocus = 0;
 			}
 		}
@@ -944,15 +845,15 @@ static void client_run(const char *direct_connect_server)
 		// panic button
 		if(config.debug)
 		{
-			if(input::pressed(input::f1))
-				input::set_mouse_mode(input::mode_absolute);
-			if(input::pressed(input::f2))
-				input::set_mouse_mode(input::mode_relative);
+			if(inp_key_pressed(KEY_F1))
+				inp_mouse_mode_absolute();
+			if(inp_key_pressed(KEY_F2))
+				inp_mouse_mode_relative();
 
-			if(input::pressed(input::lctrl) && input::pressed('Q'))
+			if(inp_key_pressed(KEY_LCTRL) && inp_key_pressed('Q'))
 				break;
 		
-			if(input::pressed(input::f5))
+			if(inp_key_pressed(KEY_F5))
 			{
 				// ack snapshot
 				msg_pack_start_system(NETMSG_SNAPACK, 0);
@@ -996,7 +897,7 @@ static void client_run(const char *direct_connect_server)
 			if(config.debug)
 			{
 				dbg_msg("client/report", "fps=%.02f netstate=%d",
-					frames/(float)(reportinterval/time_freq()), net.state());
+					frames/(float)(reportinterval/time_freq()), netclient_state(net));
 			}
 			frames = 0;
 			reporttime += reportinterval;
@@ -1032,7 +933,8 @@ int main(int argc, char **argv)
 	const char *config_filename = "default.cfg";
 #endif
 
-	for(int i = 1; i < argc; i++)
+	int i;
+	for(i = 1; i < argc; i++)
 	{
 		if(argv[i][0] == '-' && argv[i][1] == 'f' && argv[i][2] == 0 && argc - i > 1)
 		{
@@ -1045,13 +947,13 @@ int main(int argc, char **argv)
 
 	const char *direct_connect_server = 0x0;
 	snd_set_master_volume(config.volume / 255.0f);
-	bool editor = false;
+	int editor = 0;
 
 	// init network, need to be done first so we can do lookups
 	net_init();
 
 	// parse arguments
-	for(int i = 1; i < argc; i++)
+	for(i = 1; i < argc; i++)
 	{
 		if(argv[i][0] == '-' && argv[i][1] == 'c' && argv[i][2] == 0 && argc - i > 1)
 		{
@@ -1061,7 +963,7 @@ int main(int argc, char **argv)
 		}
 		else if(argv[i][0] == '-' && argv[i][1] == 'e' && argv[i][2] == 0)
 		{
-			editor = true;
+			editor = 1;
 		}
 		else
 			config_set(argv[i]);
diff --git a/src/engine/client/gfx.cpp b/src/engine/client/gfx.c
index 6a096139..b48740b6 100644
--- a/src/engine/client/gfx.cpp
+++ b/src/engine/client/gfx.c
@@ -1,38 +1,41 @@
-#include <baselib/opengl.h>
-#include <baselib/math.h>
-#include <baselib/vmath.h>
-#include <baselib/stream/file.h>
 
-#include <engine/interface.h>
+#include <engine/external/glfw/include/GL/glfw.h>
+#include <engine/external/pnglite/pnglite.h>
 
-#include "pnglite/pnglite.h"
+#include <engine/system.h>
+#include <engine/interface.h>
+#include <engine/config.h>
+#include <engine/keys.h>
 
 #include <string.h>
 #include <stdio.h>
+#include <math.h>
 
-#include <engine/config.h>
-
+// compressed textures
+#define GL_COMPRESSED_RGB_ARB 0x84ED
+#define GL_COMPRESSED_RGBA_ARB 0x84EE
 
-using namespace baselib;
+//
+typedef struct { float x, y, z; } VEC3;
+typedef struct { float u, v; } TEXCOORD;
+typedef struct { float r, g, b, a; } COLOR;
 
-static opengl::context context;
-
-struct custom_vertex
+typedef struct
 {
-	vec3 pos;
-	vec2 tex;
-	vec4 color;
-};
+	VEC3 pos;
+	TEXCOORD tex;
+	COLOR color;
+} VERTEX;
 
 const int vertex_buffer_size = 32*1024;
-static custom_vertex *vertices = 0;
+static VERTEX *vertices = 0;
 static int num_vertices = 0;
-static vec4 color[4];
-static vec2 texture[4];
+
+static COLOR color[4];
+static TEXCOORD texture[4];
 
 static int do_screenshot = 0;
 
-static opengl::vertex_buffer vertex_buffer;
 static int screen_width = -1;
 static int screen_height = -1;
 static float rotation = 0;
@@ -43,17 +46,21 @@ static float screen_y0 = 0;
 static float screen_x1 = 0;
 static float screen_y1 = 0;
 
-struct texture_holder
+typedef struct
 {
-	opengl::texture tex;
+	GLuint tex;
 	int memsize;
 	int flags;
 	int next;
-};
+} TEXTURE;
 
-static const int MAX_TEXTURES = 128;
 
-static texture_holder textures[MAX_TEXTURES];
+enum
+{
+	MAX_TEXTURES = 128
+};
+
+static TEXTURE textures[MAX_TEXTURES];
 static int first_free_texture;
 static int memory_usage = 0;
 
@@ -64,7 +71,7 @@ static const unsigned char null_texture_data[] = {
 	0x00,0x00,0xff,0xff, 0x00,0x00,0xff,0xff, 0xff,0xff,0x00,0xff, 0xff,0xff,0x00,0xff, 
 };
 
-static void draw_quad(bool _bflush = false)
+static void draw_quad(int _bflush)
 {
 	if (!_bflush && ((num_vertices + 4) < vertex_buffer_size))
 	{
@@ -80,33 +87,15 @@ static void draw_quad(bool _bflush = false)
 		//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
 		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
 
-		/*
-		if(GLEW_ARB_vertex_buffer_object)
-		{
-			// set the data
-			vertex_buffer.data(vertices, num_vertices * sizeof(custom_vertex), GL_DYNAMIC_DRAW);
-			opengl::stream_vertex(&vertex_buffer, 3, GL_FLOAT, sizeof(custom_vertex), 0);
-			opengl::stream_texcoord(&vertex_buffer, 0, 2, GL_FLOAT,
-					sizeof(custom_vertex),
-					sizeof(vec3));
-			opengl::stream_color(&vertex_buffer, 4, GL_FLOAT,
-					sizeof(custom_vertex),
-					sizeof(vec3)+sizeof(vec2));		
-					
-			//glDrawElements(GL_TRIANGLES, num_vertices, GL_UNSIGNED_SHORT, indecies);
-			opengl::draw_arrays(GL_QUADS, 0, num_vertices);
-		}
-		else
-		{*/
 		glVertexPointer(3, GL_FLOAT,
-				sizeof(custom_vertex),
+				sizeof(VERTEX),
 				(char*)vertices);
 		glTexCoordPointer(2, GL_FLOAT,
-				sizeof(custom_vertex),
-				(char*)vertices + sizeof(vec3));
+				sizeof(VERTEX),
+				(char*)vertices + sizeof(float)*3);
 		glColorPointer(4, GL_FLOAT,
-				sizeof(custom_vertex),
-				(char*)vertices + sizeof(vec3) + sizeof(vec2));
+				sizeof(VERTEX),
+				(char*)vertices + sizeof(float)*5);
 		glEnableClientState(GL_VERTEX_ARRAY);
 		glEnableClientState(GL_TEXTURE_COORD_ARRAY);
 		glEnableClientState(GL_COLOR_ARRAY);
@@ -117,11 +106,13 @@ static void draw_quad(bool _bflush = false)
 	}
 }
 
-bool gfx_init()
+int gfx_init()
 {
 	screen_width = config.gfx_screen_width;
 	screen_height = config.gfx_screen_height;
 
+	glfwInit();
+
 	if(config.stress)
 	{
 		screen_width = 320;
@@ -130,31 +121,33 @@ bool gfx_init()
 	
 	if(config.gfx_fullscreen)
 	{
-		if(!context.create(screen_width, screen_height, 24, 0, 0, 0, opengl::context::FLAG_FULLSCREEN))
+		int result = glfwOpenWindow(screen_width, screen_height, 8, 8, 8, 0, 0, 0, GLFW_FULLSCREEN);
+		if(result != GL_TRUE)
 		{
 			dbg_msg("game", "failed to create gl context");
-			return false;
+			return 0;
 		}
 	}
 	else
 	{
-		if(!context.create(screen_width, screen_height, 0, 0, 0, 0, 0))
+		int result = glfwOpenWindow(screen_width, screen_height, 0, 0, 0, 0, 0, 0, GLFW_WINDOW);
+		if(result != GL_TRUE)
 		{
 			dbg_msg("game", "failed to create gl context");
-			return false;
+			return 0;
 		}
 	}
 	
-	context.set_title("Teewars");
+	glfwSetWindowTitle("Teewars");
 	
 	// We don't want to see the window when we run the stress testing
 	if(config.stress)
-		context.iconify();
+		glfwIconifyWindow();
 	
 	// Init vertices
 	if (vertices)
 		mem_free(vertices);
-	vertices = (custom_vertex*)mem_alloc(sizeof(custom_vertex) * vertex_buffer_size, 1);
+	vertices = (VERTEX*)mem_alloc(sizeof(VERTEX) * vertex_buffer_size, 1);
 	num_vertices = 0;
 
 
@@ -169,49 +162,26 @@ bool gfx_init()
 	glEnable(GL_BLEND);
 	
 	// model
-	mat4 mat = mat4::identity;
-	opengl::matrix_modelview(&mat);
+	glMatrixMode(GL_MODELVIEW);
+	glLoadIdentity();
 	
 	// Set all z to -5.0f
-	for (int i = 0; i < vertex_buffer_size; i++)
+	int i;
+	for (i = 0; i < vertex_buffer_size; i++)
 		vertices[i].pos.z = -5.0f;
 
-/*
-	if(GLEW_ARB_vertex_buffer_object)
-	{
-		// set the streams
-		vertex_buffer.data(vertices, sizeof(vertex_buffer_size), GL_DYNAMIC_DRAW);
-		opengl::stream_vertex(&vertex_buffer, 3, GL_FLOAT, sizeof(custom_vertex), 0);
-		opengl::stream_texcoord(&vertex_buffer, 0, 2, GL_FLOAT,
-				sizeof(custom_vertex),
-				sizeof(vec3));
-		opengl::stream_color(&vertex_buffer, 4, GL_FLOAT,
-				sizeof(custom_vertex),
-				sizeof(vec3)+sizeof(vec2));		
-	}*/
-
 	// init textures
 	first_free_texture = 0;
-	for(int i = 0; i < MAX_TEXTURES; i++)
+	for(i = 0; i < MAX_TEXTURES; i++)
 		textures[i].next = i+1;
 	textures[MAX_TEXTURES-1].next = -1;
 	
-	// init indecies
-	/*
-	for(int i = 0; i < vertex_buffer_size; i++)
-	{
-		indecies[i*6 + 0] = i+0;
-		indecies[i*6 + 1] = i+1;
-		indecies[i*6 + 2] = i+2;
-		
-		indecies[i*6 + 3] = i+1;
-		indecies[i*6 + 4] = i+3;
-		indecies[i*6 + 5] = i+2;
-	}*/
-	
 	//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
 	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
 	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+
+	// init input
+	inp_init();
 	
 	// create null texture, will get id=0
 	gfx_load_texture_raw(4,4,IMG_RGBA,null_texture_data);
@@ -219,17 +189,17 @@ bool gfx_init()
 	// set vsync as needed
 	gfx_set_vsync(config.gfx_vsync);
 
-	return true;
+	return 1;
 }
 
 
 int gfx_window_active()
 {
-	return context.active()?1:0;
+	return glfwGetWindowParam(GLFW_ACTIVE) == GL_TRUE ? 1 : 0;
 }
 
 
-video_mode fakemodes[] = {
+VIDEO_MODE fakemodes[] = {
 	{320,240,8,8,8}, {400,300,8,8,8}, {640,480,8,8,8},
 	{720,400,8,8,8}, {768,576,8,8,8}, {800,600,8,8,8},
 	{1024,600,8,8,8}, {1024,768,8,8,8}, {1152,864,8,8,8},
@@ -253,25 +223,28 @@ video_mode fakemodes[] = {
 	{2048,1536,5,6,5}
 };
 
-int gfx_get_video_modes(video_mode *list, int maxcount)
+int gfx_get_video_modes(VIDEO_MODE *list, int maxcount)
 {
 	if(config.gfx_display_all_modes)
 	{
 		mem_copy(list, fakemodes, sizeof(fakemodes));
-		return min((int)(sizeof(fakemodes)/sizeof(video_mode)), maxcount);
+		int count = sizeof(fakemodes)/sizeof(VIDEO_MODE);
+		if(maxcount < count)
+			count = maxcount;
+		return count;
 	}
 	
-	return context.getvideomodes((opengl::videomode *)list, maxcount);
+	return glfwGetVideoModes((GLFWvidmode *)list, maxcount);
 }
 
 void gfx_set_vsync(int val)
 {
-	context.set_vsync(val);
+	glfwSwapInterval(val);
 }
 
 int gfx_unload_texture(int index)
 {
-	textures[index].tex.clear();
+	glDeleteTextures(1, &textures[index].tex);
 	textures[index].next = first_free_texture;
 	memory_usage -= textures[index].memsize;
 	first_free_texture = index;
@@ -302,7 +275,7 @@ static unsigned char sample(int w, int h, const unsigned char *data, int u, int
 
 int gfx_load_texture_raw(int w, int h, int format, const void *data)
 {
-	bool mipmap = true;
+	int mipmap = 1;
 	
 	// grab texture
 	int tex = first_free_texture;
@@ -320,8 +293,9 @@ int gfx_load_texture_raw(int w, int h, int format, const void *data)
 			h/=2;
 			unsigned char *tmpdata = (unsigned char *)mem_alloc(w*h*4, 1);
 			int c = 0;
-			for(int y = 0; y < h; y++)
-				for(int x = 0; x < w; x++, c++)
+			int x, y;
+			for(y = 0; y < h; y++)
+				for(x = 0; x < w; x++, c++)
 				{
 					tmpdata[c*4] = sample(w*2, h*2, texdata, x*2,y*2, 0);
 					tmpdata[c*4+1] = sample(w*2, h*2, texdata, x*2,y*2, 1);
@@ -335,22 +309,28 @@ int gfx_load_texture_raw(int w, int h, int format, const void *data)
 	if(config.debug)
 		dbg_msg("gfx", "%d = %dx%d", tex, w, h);
 	
-	// set data and return
-	if(config.gfx_texture_compression && GLEW_ARB_texture_compression)
+	// upload texture
+	int oglformat = 0;
+	if(config.gfx_texture_compression)
 	{
+		oglformat = GL_COMPRESSED_RGBA_ARB;
 		if(format == IMG_RGB)
-			textures[tex].tex.data2d(w, h, GL_COMPRESSED_RGB_ARB, GL_RGB, GL_UNSIGNED_BYTE, texdata);
-		else if(format == IMG_RGBA)
-			textures[tex].tex.data2d(w, h, GL_COMPRESSED_RGBA_ARB, GL_RGBA, GL_UNSIGNED_BYTE, texdata);
+			oglformat = GL_COMPRESSED_RGB_ARB;
 	}
 	else
 	{
+		oglformat = GL_RGBA;
 		if(format == IMG_RGB)
-			textures[tex].tex.data2d(w, h, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, texdata);
-		else if(format == IMG_RGBA)
-			textures[tex].tex.data2d(w, h, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, texdata);
+			oglformat = GL_RGB;
 	}
+		
+	glGenTextures(1, &textures[tex].tex);
+	glBindTexture(GL_TEXTURE_2D, textures[tex].tex);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
+	gluBuild2DMipmaps(GL_TEXTURE_2D, oglformat, w, h, oglformat, GL_UNSIGNED_BYTE, texdata);
 	
+	// calculate memory usage
 	textures[tex].memsize = w*h*4;
 	if(mipmap)
 	{
@@ -363,9 +343,7 @@ int gfx_load_texture_raw(int w, int h, int format, const void *data)
 	}
 	
 	memory_usage += textures[tex].memsize;
-	
 	mem_free(tmpdata);
-	
 	return tex;
 }
 /*
@@ -403,7 +381,7 @@ int gfx_load_texture(const char *filename)
 	int l = strlen(filename);
 	if(l < 3)
 		return 0;
-	image_info img;
+	IMAGE_INFO img;
 	if(gfx_load_png(&img, filename))
 	{
 		int id = gfx_load_texture_raw(img.width, img.height, img.format, img.data);
@@ -414,7 +392,7 @@ int gfx_load_texture(const char *filename)
 	return 0;
 }
 
-int gfx_load_png(image_info *img, const char *filename)
+int gfx_load_png(IMAGE_INFO *img, const char *filename)
 {
 	// open file for reading
 	png_init(0,0);
@@ -450,7 +428,8 @@ void gfx_shutdown()
 {
 	if (vertices)
 		mem_free(vertices);
-	context.destroy();
+	glfwCloseWindow();
+	glfwTerminate();
 }
 
 void gfx_screenshot()
@@ -470,7 +449,8 @@ void gfx_swap()
 		glReadPixels(0,0, w, h, GL_RGB, GL_UNSIGNED_BYTE, pixel_data);
 		
 		// flip the pixel because opengl works from bottom left corner
-		for(int y = 0; y < h/2; y++)
+		int y;
+		for(y = 0; y < h/2; y++)
 		{
 			mem_copy(temp_row, pixel_data+y*w*3, w*3);
 			mem_copy(pixel_data+y*w*3, pixel_data+(h-y-1)*w*3, w*3);
@@ -503,7 +483,8 @@ void gfx_swap()
 		do_screenshot = 0;
 	}
 	
-	context.swap();
+	glfwSwapBuffers();
+	glfwPollEvents();
 }
 
 int gfx_screenwidth()
@@ -520,15 +501,18 @@ void gfx_texture_set(int slot)
 {
 	dbg_assert(quads_drawing == 0, "called gfx_texture_set within quads_begin");
 	if(slot == -1)
-		opengl::texture_disable(0);
+		glDisable(GL_TEXTURE_2D);
 	else
-		opengl::texture_2d(0, &textures[slot].tex);
+	{
+		glEnable(GL_TEXTURE_2D);
+		glBindTexture(GL_TEXTURE_2D, textures[slot].tex);
+	}
 }
 
 void gfx_clear(float r, float g, float b)
 {
 	glClearColor(r,g,b,1.0f);
-	opengl::clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
 }
 
 void gfx_mapscreen(float tl_x, float tl_y, float br_x, float br_y)
@@ -537,9 +521,9 @@ void gfx_mapscreen(float tl_x, float tl_y, float br_x, float br_y)
 	screen_y0 = tl_y;
 	screen_x1 = br_x;
 	screen_y1 = br_y;
-	mat4 mat;
-	mat.ortho(tl_x, br_x, br_y, tl_y, 1.0f, 10.f);
-	opengl::matrix_projection(&mat);
+	glMatrixMode(GL_PROJECTION);
+	glLoadIdentity();
+	glOrtho(tl_x, br_x, br_y, tl_y, 1.0f, 10.f);
 }
 
 void gfx_getscreen(float *tl_x, float *tl_y, float *br_x, float *br_y)
@@ -552,20 +536,19 @@ void gfx_getscreen(float *tl_x, float *tl_y, float *br_x, float *br_y)
 
 void gfx_setoffset(float x, float y)
 {
-	//const float scale = 0.75f;
-	const float scale = 1.0f;
-	mat4 mat = mat4::identity;
-	mat.m[0] = scale;
-	mat.m[5] = scale;
-	mat.m[10] = scale;
-	mat.m[12] = x*scale;
-	mat.m[13] = y*scale;
-	opengl::matrix_modelview(&mat);
+	//const float scale = 1.0f;
+	//mat4 mat = mat4::identity;
+	//mat.m[0] = scale;
+	//mat.m[5] = scale;
+	//mat.m[10] = scale;
+	//mat.m[12] = x*scale;
+	//mat.m[13] = y*scale;
+	glMatrixMode(GL_MODELVIEW);
+	glLoadIdentity();
+	glTranslatef(x, y, 0);
 }
 
 
-
-
 void gfx_quads_begin()
 {
 	dbg_assert(quads_drawing == 0, "called quads_begin twice");
@@ -579,7 +562,7 @@ void gfx_quads_begin()
 void gfx_quads_end()
 {
 	dbg_assert(quads_drawing == 1, "called quads_end without quads_begin");
-	draw_quad(true);
+	draw_quad(1);
 	quads_drawing--;
 }
 
@@ -602,42 +585,43 @@ void gfx_quads_setcolorvertex(int i, float r, float g, float b, float a)
 void gfx_quads_setcolor(float r, float g, float b, float a)
 {
 	dbg_assert(quads_drawing == 1, "called gfx_quads_setcolor without quads_begin");
-	color[0] = vec4(r,g,b,a);
-	color[1] = vec4(r,g,b,a);
-	color[2] = vec4(r,g,b,a);
-	color[3] = vec4(r,g,b,a);
+	gfx_quads_setcolorvertex(0, r, g, b, a);
+	gfx_quads_setcolorvertex(1, r, g, b, a);
+	gfx_quads_setcolorvertex(2, r, g, b, a);
+	gfx_quads_setcolorvertex(3, r, g, b, a);
 }
 
 void gfx_quads_setsubset(float tl_u, float tl_v, float br_u, float br_v)
 {
 	dbg_assert(quads_drawing == 1, "called gfx_quads_setsubset without quads_begin");
 
-	texture[0].x = tl_u;
-	texture[0].y = tl_v;
+	texture[0].u = tl_u;
+	texture[0].v = tl_v;
 	//g_pVertices[g_iVertexEnd].tex.u = tl_u;
 	//g_pVertices[g_iVertexEnd].tex.v = tl_v;
 
-	texture[1].x = br_u;
-	texture[1].y = tl_v;
+	texture[1].u = br_u;
+	texture[1].v = tl_v;
 	//g_pVertices[g_iVertexEnd + 2].tex.u = br_u;
 	//g_pVertices[g_iVertexEnd + 2].tex.v = tl_v;
 
-	texture[2].x = br_u;
-	texture[2].y = br_v;
+	texture[2].u = br_u;
+	texture[2].v = br_v;
 	//g_pVertices[g_iVertexEnd + 1].tex.u = tl_u;
 	//g_pVertices[g_iVertexEnd + 1].tex.v = br_v;
 
-	texture[3].x = tl_u;
-	texture[3].y = br_v;
+	texture[3].u = tl_u;
+	texture[3].v = br_v;
 	//g_pVertices[g_iVertexEnd + 3].tex.u = br_u;
 	//g_pVertices[g_iVertexEnd + 3].tex.v = br_v;
 }
 
-static void rotate(vec3 &center, vec3 &point)
+static void rotate(VEC3 *center, VEC3 *point)
 {
-	vec3 p = point-center;
-	point.x = p.x * cosf(rotation) - p.y * sinf(rotation) + center.x;
-	point.y = p.x * sinf(rotation) + p.y * cosf(rotation) + center.y;
+	float x = point->x - center->x;
+	float y = point->y - center->y;
+	point->x = x * cosf(rotation) - y * sinf(rotation) + center->x;
+	point->y = x * sinf(rotation) + y * cosf(rotation) + center->y;
 }
 
 void gfx_quads_draw(float x, float y, float w, float h)
@@ -649,40 +633,36 @@ void gfx_quads_drawTL(float x, float y, float width, float height)
 {
 	dbg_assert(quads_drawing == 1, "called quads_draw without quads_begin");
 	
-	vec3 center;
+	VEC3 center;
 	center.x = x + width/2;
 	center.y = y + height/2;
 	center.z = 0;
 	
 	vertices[num_vertices].pos.x = x;
 	vertices[num_vertices].pos.y = y;
-	vertices[num_vertices].tex.u = texture[0].x;
-	vertices[num_vertices].tex.v = texture[0].y;
+	vertices[num_vertices].tex = texture[0];
 	vertices[num_vertices].color = color[0];
-	rotate(center, vertices[num_vertices].pos);
+	rotate(&center, &vertices[num_vertices].pos);
 
 	vertices[num_vertices + 1].pos.x = x+width;
 	vertices[num_vertices + 1].pos.y = y;
-	vertices[num_vertices + 1].tex.u = texture[1].x;
-	vertices[num_vertices + 1].tex.v = texture[1].y;
+	vertices[num_vertices + 1].tex = texture[1];
 	vertices[num_vertices + 1].color = color[1];
-	rotate(center, vertices[num_vertices + 1].pos);
+	rotate(&center, &vertices[num_vertices + 1].pos);
 
 	vertices[num_vertices + 2].pos.x = x + width;
 	vertices[num_vertices + 2].pos.y = y+height;
-	vertices[num_vertices + 2].tex.u = texture[2].x;
-	vertices[num_vertices + 2].tex.v = texture[2].y;
+	vertices[num_vertices + 2].tex = texture[2];
 	vertices[num_vertices + 2].color = color[2];
-	rotate(center, vertices[num_vertices + 2].pos);
+	rotate(&center, &vertices[num_vertices + 2].pos);
 
 	vertices[num_vertices + 3].pos.x = x;
 	vertices[num_vertices + 3].pos.y = y+height;
-	vertices[num_vertices + 3].tex.u = texture[3].x;
-	vertices[num_vertices + 3].tex.v = texture[3].y;
+	vertices[num_vertices + 3].tex = texture[3];
 	vertices[num_vertices + 3].color = color[3];
-	rotate(center, vertices[num_vertices + 3].pos);
+	rotate(&center, &vertices[num_vertices + 3].pos);
 	
-	draw_quad();
+	draw_quad(0);
 }
 
 void gfx_quads_draw_freeform(
@@ -695,29 +675,25 @@ void gfx_quads_draw_freeform(
 	
 	vertices[num_vertices].pos.x = x0;
 	vertices[num_vertices].pos.y = y0;
-	vertices[num_vertices].tex.u = texture[0].x;
-	vertices[num_vertices].tex.v = texture[0].y;
+	vertices[num_vertices].tex = texture[0];
 	vertices[num_vertices].color = color[0];
 
 	vertices[num_vertices + 1].pos.x = x1;
 	vertices[num_vertices + 1].pos.y = y1;
-	vertices[num_vertices + 1].tex.u = texture[1].x;
-	vertices[num_vertices + 1].tex.v = texture[1].y;
+	vertices[num_vertices + 1].tex = texture[1];
 	vertices[num_vertices + 1].color = color[1];
 
 	vertices[num_vertices + 2].pos.x = x3;
 	vertices[num_vertices + 2].pos.y = y3;
-	vertices[num_vertices + 2].tex.u = texture[2].x;
-	vertices[num_vertices + 2].tex.v = texture[2].y;
+	vertices[num_vertices + 2].tex = texture[2];
 	vertices[num_vertices + 2].color = color[2];
 
 	vertices[num_vertices + 3].pos.x = x2;
 	vertices[num_vertices + 3].pos.y = y2;
-	vertices[num_vertices + 3].tex.u = texture[3].x;
-	vertices[num_vertices + 3].tex.v = texture[3].y;
+	vertices[num_vertices + 3].tex = texture[3];
 	vertices[num_vertices + 3].color = color[3];
 	
-	draw_quad();
+	draw_quad(0);
 }
 
 void gfx_quads_text(float x, float y, float size, const char *text)
@@ -750,12 +726,12 @@ void gfx_quads_text(float x, float y, float size, const char *text)
 	gfx_quads_end();
 }
 
-struct pretty_font
+typedef struct
 {
 	float m_CharStartTable[256];
 	float m_CharEndTable[256];
 	int font_texture;
-};
+} pretty_font;
 
 pretty_font default_font = 
 {
diff --git a/src/engine/client/inp.c b/src/engine/client/inp.c
new file mode 100644
index 00000000..6583c53f
--- /dev/null
+++ b/src/engine/client/inp.c
@@ -0,0 +1,95 @@
+#include <engine/external/glfw/include/GL/glfw.h>
+
+#include <engine/system.h>
+#include <engine/interface.h>
+
+static int keyboard_state[2][1024]; // TODO: fix this!!
+static int keyboard_current = 0;
+static int keyboard_first = 1;
+
+void inp_mouse_relative(int *x, int *y)
+{
+	static int last_x = 0, last_y = 0;
+	int nx, ny;
+	glfwGetMousePos(&nx, &ny);
+	*x = nx-last_x;
+	*y = ny-last_y;
+	last_x = nx;
+	last_y = ny;
+}
+
+static char last_c = 0;
+static int last_k = 0;
+
+static void char_callback(int character, int action)
+{
+	if(action == GLFW_PRESS && character < 256)
+	last_c = (char)character;
+}
+
+static void key_callback(int key, int action)
+{
+    if(action == GLFW_PRESS)
+	    last_k = key;
+}
+
+void inp_init()
+{
+	glfwEnable(GLFW_KEY_REPEAT);
+	glfwSetCharCallback(char_callback);
+	glfwSetKeyCallback(key_callback);
+}
+
+char inp_last_char()
+{
+	return last_c;
+}
+
+int inp_last_key()
+{
+	return last_k;
+}
+
+void inp_clear()
+{
+	last_k = 0;
+	last_c = 0;
+}
+
+void inp_mouse_mode_absolute()
+{
+	glfwEnable(GLFW_MOUSE_CURSOR);
+}
+
+void inp_mouse_mode_relative()
+{
+	glfwDisable(GLFW_MOUSE_CURSOR);
+}
+
+//int inp_mouse_scroll() { return input::mouse_scroll(); }
+int inp_key_pressed(int key) { return keyboard_state[keyboard_current][key]; }
+int inp_key_was_pressed(int key) { return keyboard_state[keyboard_current^1][key]; }
+int inp_key_down(int key) { return inp_key_pressed(key)&&!inp_key_was_pressed(key); }
+int inp_button_pressed(int button) { return keyboard_state[keyboard_current][button]; }
+
+void inp_update()
+{
+    if(keyboard_first)
+    {
+        // make sure to reset
+        keyboard_first = 0;
+        inp_update();
+    }
+
+    keyboard_current = keyboard_current^1;
+    int i, v;
+    for(i = 0; i < KEY_LAST; i++)
+    {
+	    if (i >= KEY_MOUSE_FIRST)
+			v = glfwGetMouseButton(i-KEY_MOUSE_FIRST) == GLFW_PRESS ? 1 : 0;
+		else
+			v = glfwGetKey(i) == GLFW_PRESS ? 1 : 0;
+        keyboard_state[keyboard_current][i] = v;
+    }
+
+}
diff --git a/src/engine/client/snd.cpp b/src/engine/client/snd.c
index 2fefd6f2..6b490f72 100644
--- a/src/engine/client/snd.cpp
+++ b/src/engine/client/snd.c
@@ -1,19 +1,17 @@
-#include <baselib/system.h>
-#include <baselib/audio.h>
-#include <baselib/stream/file.h>
-
+#include <engine/system.h>
 #include <engine/interface.h>
 #include <engine/config.h>
 
-extern "C" {
-#include "../../wavpack/wavpack.h"
-}
+#include <engine/external/portaudio/portaudio.h>
+#include <engine/external/wavpack/wavpack.h>
 
-using namespace baselib;
+enum
+{
+	NUM_FRAMES_STOP = 512,
+	NUM_FRAMES_LERP = 512,
+};
 
-static const int NUM_FRAMES_STOP = 512;
 static const float NUM_FRAMES_STOP_INV = 1.0f/(float)NUM_FRAMES_STOP;
-static const int NUM_FRAMES_LERP = 512;
 static const float NUM_FRAMES_LERP_INV = 1.0f/(float)NUM_FRAMES_LERP;
 
 static const float GLOBAL_VOLUME_SCALE = 0.75f;
@@ -22,8 +20,9 @@ static float master_volume = 1.0f;
 static const float GLOBAL_SOUND_DELAY = 0.05f;
 
 // --- sound ---
-class sound_data
+typedef struct
 {
+	/*
 public:
 	sound_data() :
 		data(0x0),
@@ -33,7 +32,7 @@ public:
 		sustain_start(-1),
 		sustain_end(-1),
 		last_played(0)
-	{ }
+	{ }*/
 
 	short *data;
 	int num_samples;
@@ -42,8 +41,28 @@ public:
 	int sustain_start;
 	int sustain_end;
 	int64 last_played;
-};
+} SOUND_DATA;
+
+
+static float clampf(float val, float lower, float upper)
+{
+	if(val > upper)
+		return upper;
+	if(val < lower)
+		return lower;
+	return val;
+}
+
 
+static int clampi(int val, int lower, int upper)
+{
+	if(val > upper)
+		return upper;
+	if(val < lower)
+		return lower;
+	return val;
+}
+/*
 template<typename T>
 inline const T clamp(const T val, const T lower, const T upper)
 {
@@ -52,201 +71,264 @@ inline const T clamp(const T val, const T lower, const T upper)
 	if(val < lower)
 		return lower;
 	return val;
-}
+}*/
 
-static class mixer : public audio_stream
+
+typedef struct
 {
+/*
 public:
-	class channel
-	{
-	public:
-		channel()
-		{ data = 0; lerp = -1; stop = -1; }
-		
-		sound_data *data;
-		int tick;
-		int loop;
-		float pan;
-		float vol;
-		float old_vol;
-		float new_vol;
-		int lerp;
-		int stop;
-	};
+	channel()
+	{ data = 0; lerp = -1; stop = -1; }
+*/
 	
-	enum
-	{
-		MAX_CHANNELS=32,
-		MAX_FILL_FRAMES=256,
-	};
+	SOUND_DATA *data;
+	int tick;
+	int loop;
+	float pan;
+	float vol;
+	float old_vol;
+	float new_vol;
+	int lerp;
+	int stop;
+} MIXER_CHANNEL;
+
+enum
+{
+	MAX_CHANNELS=32,
+	MAX_FILL_FRAMES=256,
+};
 
-	channel channels[MAX_CHANNELS];
-	int buffer[MAX_FILL_FRAMES*2];
+static MIXER_CHANNEL channels[MAX_CHANNELS];
+static int buffer[MAX_FILL_FRAMES*2];
 
-	void fill_mono(int *out, unsigned long frames, channel *c, float dv = 0.0f)
-	{
-		float pl = clamp(1.0f - c->pan, 0.0f, 1.0f);
-		float pr = clamp(1.0f + c->pan, 0.0f, 1.0f);
+static void mixer_fill_mono(int *out, unsigned long frames, MIXER_CHANNEL *c, float dv)
+{
+	float pl = clampf(1.0f - c->pan, 0.0f, 1.0f);
+	float pr = clampf(1.0f + c->pan, 0.0f, 1.0f);
+	unsigned long i;
 
-		for(unsigned long i = 0; i < frames; i++)
-		{
-			float val = c->vol * master_volume * c->data->data[c->tick];
+	for(i = 0; i < frames; i++)
+	{
+		float val = c->vol * master_volume * c->data->data[c->tick];
 
-			out[i<<1] += (int)(pl*val);
-			out[(i<<1)+1] += (int)(pr*val);
-			c->tick++;
-			c->vol += dv;
-			if(c->vol < 0.0f) c->vol = 0.0f;
-		}
+		out[i<<1] += (int)(pl*val);
+		out[(i<<1)+1] += (int)(pr*val);
+		c->tick++;
+		c->vol += dv;
+		if(c->vol < 0.0f) c->vol = 0.0f;
 	}
+}
 
-	void fill_stereo(int *out, unsigned long frames, channel *c, float dv = 0.0f)
-	{
-		float pl = clamp(1.0f - c->pan, 0.0f, 1.0f);
-		float pr = clamp(1.0f + c->pan, 0.0f, 1.0f);
+static void mixer_fill_stereo(int *out, unsigned long frames, MIXER_CHANNEL *c, float dv)
+{
+	float pl = clampf(1.0f - c->pan, 0.0f, 1.0f);
+	float pr = clampf(1.0f + c->pan, 0.0f, 1.0f);
+	unsigned long i;
 
-		for(unsigned long i = 0; i < frames; i++)
-		{
-			int vl = (int)(pl*c->vol * master_volume * c->data->data[c->tick]);
-			int vr = (int)(pr*c->vol * master_volume * c->data->data[c->tick + 1]);
-			out[i<<1] += vl;
-			out[(i<<1)+1] += vr;
-			c->tick += 2;
-			c->vol += dv;
-			if(c->vol < 0.0f) c->vol = 0.0f;
-		}
+	for(i = 0; i < frames; i++)
+	{
+		int vl = (int)(pl*c->vol * master_volume * c->data->data[c->tick]);
+		int vr = (int)(pr*c->vol * master_volume * c->data->data[c->tick + 1]);
+		out[i<<1] += vl;
+		out[(i<<1)+1] += vr;
+		c->tick += 2;
+		c->vol += dv;
+		if(c->vol < 0.0f) c->vol = 0.0f;
 	}
+}
 
-	virtual void fill(void *output, unsigned long frames)
-	{
-		short *out = (short*)output;
+static void mixer_fill(void *output, unsigned long frames)
+{
+	short *out = (short*)output;
 
-		dbg_assert(frames <= MAX_FILL_FRAMES, "not enough fill frames in buffer");
+	dbg_assert(frames <= MAX_FILL_FRAMES, "not enough fill frames in buffer");
+	unsigned long i;
+	int c;
 
-		for(unsigned long i = 0; i < frames; i++)
-		{
-			buffer[i<<1] = 0;
-			buffer[(i<<1)+1] = 0;
-		}
+	for(i = 0; i < frames; i++)
+	{
+		buffer[i<<1] = 0;
+		buffer[(i<<1)+1] = 0;
+	}
 
-		for(int c = 0; c < MAX_CHANNELS; c++)
+	for(c = 0; c < MAX_CHANNELS; c++)
+	{
+		unsigned long filled = 0;
+		while(channels[c].data && filled < frames)
 		{
-			unsigned long filled = 0;
-			while(channels[c].data && filled < frames)
+			unsigned long frames_left = (channels[c].data->num_samples - channels[c].tick) >> (channels[c].data->channels-1);
+			unsigned long to_fill = frames>frames_left?frames_left:frames;
+			float dv = 0.0f;
+
+			if(channels[c].stop >= 0)
+				to_fill = (unsigned)channels[c].stop>frames_left?frames:channels[c].stop;
+			if(channels[c].loop >= 0 &&
+					channels[c].data->sustain_start >= 0)
 			{
-				unsigned long frames_left = (channels[c].data->num_samples - channels[c].tick) >> (channels[c].data->channels-1);
-				unsigned long to_fill = frames>frames_left?frames_left:frames;
-				float dv = 0.0f;
-
-				if(channels[c].stop >= 0)
-					to_fill = (unsigned)channels[c].stop>frames_left?frames:channels[c].stop;
-				if(channels[c].loop >= 0 &&
-						channels[c].data->sustain_start >= 0)
-				{
-					unsigned long tmp = channels[c].data->sustain_end - channels[c].tick;
-					to_fill = tmp>frames?frames:tmp;
-				}
-
-				if(channels[c].lerp >= 0)
-				{
-						dv = (channels[c].new_vol - channels[c].old_vol) * NUM_FRAMES_LERP_INV;
-				}
+				unsigned long tmp = channels[c].data->sustain_end - channels[c].tick;
+				to_fill = tmp>frames?frames:tmp;
+			}
 
-				if(channels[c].data->channels == 1)
-					fill_mono(buffer, to_fill, &channels[c], dv);
-				else
-					fill_stereo(buffer, to_fill, &channels[c], dv);
+			if(channels[c].lerp >= 0)
+			{
+					dv = (channels[c].new_vol - channels[c].old_vol) * NUM_FRAMES_LERP_INV;
+			}
 
-				if(channels[c].loop >= 0 &&
-						channels[c].data->sustain_start >= 0 &&
-						channels[c].tick >= channels[c].data->sustain_end)
-					channels[c].tick = channels[c].data->sustain_start;
+			if(channels[c].data->channels == 1)
+				mixer_fill_mono(buffer, to_fill, &channels[c], dv);
+			else
+				mixer_fill_stereo(buffer, to_fill, &channels[c], dv);
 
-				if(channels[c].stop >= 0)
-					channels[c].stop -=  to_fill;
-				if(channels[c].tick >= channels[c].data->num_samples ||
-						channels[c].stop == 0)
-					channels[c].data = 0;
+			if(channels[c].loop >= 0 &&
+					channels[c].data->sustain_start >= 0 &&
+					channels[c].tick >= channels[c].data->sustain_end)
+				channels[c].tick = channels[c].data->sustain_start;
 
-				channels[c].lerp -= to_fill;
-				if(channels[c].lerp < 0)
-					channels[c].lerp = -1;
+			if(channels[c].stop >= 0)
+				channels[c].stop -=  to_fill;
+			if(channels[c].tick >= channels[c].data->num_samples ||
+					channels[c].stop == 0)
+				channels[c].data = 0;
 
+			channels[c].lerp -= to_fill;
+			if(channels[c].lerp < 0)
+				channels[c].lerp = -1;
 
-				filled += to_fill;
-			}
-		}
 
-		for(unsigned long i = 0; i < frames; i++)
-		{
-			out[i<<1] = (short)clamp(buffer[i<<1], -0x7fff, 0x7fff);
-			out[(i<<1)+1] = (short)clamp(buffer[(i<<1)+1], -0x7fff, 0x7fff);
+			filled += to_fill;
 		}
 	}
-	
-	int play(sound_data *sound, unsigned loop, float vol, float pan)
-	{
-		if(time_get() - sound->last_played < (int64)(time_freq()*GLOBAL_SOUND_DELAY))
-			return -1;
 
-		for(int c = 0; c < MAX_CHANNELS; c++)
-		{
-			if(channels[c].data == 0)
-			{
-				channels[c].data = sound;
-				channels[c].tick = 0;
-				channels[c].loop = loop;
-				channels[c].vol = vol * GLOBAL_VOLUME_SCALE;
-				channels[c].pan = pan;
-				channels[c].stop = -1;
-				channels[c].lerp = -1;
-				sound->last_played = time_get();
-				return c;
-			}
-		}
+	for(i = 0; i < frames; i++)
+	{
+		out[i<<1] = (short)clampi(buffer[i<<1], -0x7fff, 0x7fff);
+		out[(i<<1)+1] = (short)clampi(buffer[(i<<1)+1], -0x7fff, 0x7fff);
+	}
+}
 
+int mixer_play(SOUND_DATA *sound, unsigned loop, float vol, float pan)
+{
+	if(time_get() - sound->last_played < (int64)(time_freq()*GLOBAL_SOUND_DELAY))
 		return -1;
-	}
 
-	void stop(int id)
+	int c;
+	for(c = 0; c < MAX_CHANNELS; c++)
 	{
-		dbg_assert(id >= 0 && id < MAX_CHANNELS, "id out of bounds");
-		channels[id].old_vol = channels[id].vol;
-		channels[id].stop = NUM_FRAMES_STOP;
+		if(channels[c].data == 0)
+		{
+			channels[c].data = sound;
+			channels[c].tick = 0;
+			channels[c].loop = loop;
+			channels[c].vol = vol * GLOBAL_VOLUME_SCALE;
+			channels[c].pan = pan;
+			channels[c].stop = -1;
+			channels[c].lerp = -1;
+			sound->last_played = time_get();
+			return c;
+		}
 	}
 
-	void set_vol(int id, float vol)
-	{
-		dbg_assert(id >= 0 && id < MAX_CHANNELS, "id out of bounds");
-		channels[id].new_vol = vol * GLOBAL_VOLUME_SCALE;
-		channels[id].old_vol = channels[id].vol;
-		channels[id].lerp = NUM_FRAMES_LERP;
-	}
-} mixer;
+	return -1;
+}
+
+static void mixer_stop(int id)
+{
+	dbg_assert(id >= 0 && id < MAX_CHANNELS, "id out of bounds");
+	channels[id].old_vol = channels[id].vol;
+	channels[id].stop = NUM_FRAMES_STOP;
+}
+
+static void mixer_set_vol(int id, float vol)
+{
+	dbg_assert(id >= 0 && id < MAX_CHANNELS, "id out of bounds");
+	channels[id].new_vol = vol * GLOBAL_VOLUME_SCALE;
+	channels[id].old_vol = channels[id].vol;
+	channels[id].lerp = NUM_FRAMES_LERP;
+}
 
-struct sound_holder
+typedef struct
 {
-	sound_data sound;
+	SOUND_DATA sound;
 	int next;
+} SOUND;
+
+enum
+{
+	MAX_SOUNDS = 1024,
 };
 
-static const int MAX_SOUNDS = 1024;
-static sound_holder sounds[MAX_SOUNDS];
+static SOUND sounds[MAX_SOUNDS];
 static int first_free_sound;
 
-bool snd_init()
+static PaStream *stream = 0;
+
+static int pacallback(const void *in, void *out, unsigned long frames, const PaStreamCallbackTimeInfo* time, PaStreamCallbackFlags status, void *user)
+{
+	mixer_fill(out, frames);
+	return 0;
+}
+
+int snd_init()
 {
+	int i;
 	first_free_sound = 0;
-	for(int i = 0; i < MAX_SOUNDS; i++)
+	for(i = 0; i < MAX_SOUNDS; i++)
 		sounds[i].next = i+1;
 	sounds[MAX_SOUNDS-1].next = -1;
-	return mixer.create();
+	
+	// init PA
+	PaStreamParameters params;
+	PaError err = Pa_Initialize();
+	if(err != paNoError)
+	{
+		dbg_msg("audio_stream", "portaudio error: %s", Pa_GetErrorText(err));
+		return 0;
+	}
+
+	params.device = Pa_GetDefaultOutputDevice();
+	if(params.device == -1)
+	{
+		dbg_msg("audio_stream", "no default output device");
+		return 0;
+	}
+	params.channelCount = 2;
+	params.sampleFormat = paInt16;
+	params.suggestedLatency = Pa_GetDeviceInfo(params.device)->defaultLowOutputLatency;
+	params.hostApiSpecificStreamInfo = 0x0;
+
+	err = Pa_OpenStream(
+		&stream,        /* passes back stream pointer */
+		0,              /* no input channels */
+		&params,		/* pointer to parameters */
+		44100,          /* sample rate */
+		128,            /* frames per buffer */
+		paClipOff,		/* no clamping */
+		pacallback,		/* specify our custom callback */
+		0); /* pass our data through to callback */	
+
+	if(err != paNoError)
+	{
+		dbg_msg("audio_stream", "portaudio error: %s", Pa_GetErrorText(err));
+		return 0;
+	}
+	
+	err = Pa_StartStream(stream);
+	if(err != paNoError)
+	{
+		dbg_msg("audio_stream", "portaudio error: %s", Pa_GetErrorText(err));
+		return 0;
+	}
+	
+	return 1;	
 }
 
-bool snd_shutdown()
+int snd_shutdown()
 {
-	mixer.destroy();
-	return true;
+	Pa_StopStream(stream);
+	stream = NULL;
+	Pa_Terminate();	
+	return 1;
 }
 
 float snd_get_master_volume()
@@ -283,12 +365,12 @@ static int read_data(void *buffer, int size)
 
 int snd_load_wv(const char *filename)
 {
-	sound_data snd;
+	SOUND_DATA snd;
 	int id = -1;
 
 	char error[100];
 
-	file = fopen(filename, "rb");
+	file = fopen(filename, "rb"); // TODO: use system.h stuff for this
 
 	WavpackContext *context = WavpackOpenFileInput(read_data, error);
 	if (context)
@@ -326,7 +408,8 @@ int snd_load_wv(const char *filename)
 		snd.data = (short *)mem_alloc(2*samples*channels, 1);
 		short *dst = snd.data;
 
-		for (int i = 0; i < samples*channels; i++)
+		int i;
+		for (i = 0; i < samples*channels; i++)
 			*dst++ = (short)*src++;
 
 		mem_free(data);
@@ -361,11 +444,12 @@ int snd_load_wv(const char *filename)
 
 int snd_load_wav(const char *filename)
 {
-	sound_data snd;
+	SOUND_DATA snd;
 	
 	// open file for reading
-	file_stream file;
-	if(!file.open_r(filename))
+	IOHANDLE file;
+	file = io_open(filename, IOFLAG_READ);
+	if(!file)
 	{
 		dbg_msg("sound/wav", "failed to open file. filename='%s'", filename);
 		return -1;
@@ -377,7 +461,7 @@ int snd_load_wav(const char *filename)
 	{
 		// read chunk header
 		unsigned char head[8];
-		if(file.read(head, sizeof(head)) != 8)
+		if(io_read(file, head, sizeof(head)) != 8)
 		{
 			break;
 		}
@@ -395,7 +479,7 @@ int snd_load_wav(const char *filename)
 			}
 			
 			unsigned char type[4];
-			file.read(type, 4);
+			io_read(file, type, 4);
 
 			if(type[0] != 'W' || type[1] != 'A' || type[2] != 'V' || type[3] != 'E')
 			{
@@ -411,7 +495,7 @@ int snd_load_wav(const char *filename)
 			if(head[0] == 'f' && head[1] == 'm' && head[2] == 't' && head[3] == ' ')
 			{
 				unsigned char fmt[16];
-				if(file.read(fmt, sizeof(fmt)) !=  sizeof(fmt))
+				if(io_read(file, fmt, sizeof(fmt)) !=  sizeof(fmt))
 				{
 					dbg_msg("sound/wav", "failed to read format. filename='%s'", filename);
 					return -1;
@@ -451,7 +535,7 @@ int snd_load_wav(const char *filename)
 				state++;
 			}
 			else
-				file.skip(chunk_size);
+				io_skip(file, chunk_size);
 		}
 		else if(state == 2)
 		{
@@ -459,7 +543,7 @@ int snd_load_wav(const char *filename)
 			if(head[0] == 'd' && head[1] == 'a' && head[2] == 't' && head[3] == 'a')
 			{
 				snd.data = (short*)mem_alloc(chunk_size, 1);
-				file.read(snd.data, chunk_size);
+				io_read(file, snd.data, chunk_size);
 				snd.num_samples = chunk_size/(2);
 #if defined(CONF_ARCH_ENDIAN_BIG)
 				for(unsigned i = 0; i < (unsigned)snd.num_samples; i++)
@@ -476,7 +560,7 @@ int snd_load_wav(const char *filename)
 				state++;
 			}
 			else
-				file.skip(chunk_size);
+				io_skip(file, chunk_size);
 		}
 		else if(state == 3)
 		{
@@ -487,13 +571,13 @@ int snd_load_wav(const char *filename)
 				if(config.debug)
 					dbg_msg("sound/wav", "got sustain");
 
-				file.read(smpl, sizeof(smpl));
+				io_read(file, smpl, sizeof(smpl));
 				unsigned num_loops = (smpl[28] | (smpl[29]<<8) | (smpl[30]<<16) | (smpl[31]<<24));
 				unsigned skip = (smpl[32] | (smpl[33]<<8) | (smpl[34]<<16) | (smpl[35]<<24));
 
 				if(num_loops > 0)
 				{
-					file.read(loop, sizeof(loop));
+					io_read(file, loop, sizeof(loop));
 					unsigned start = (loop[8] | (loop[9]<<8) | (loop[10]<<16) | (loop[11]<<24));
 					unsigned end = (loop[12] | (loop[13]<<8) | (loop[14]<<16) | (loop[15]<<24));
 					sounds[id].sound.sustain_start = start * sounds[id].sound.channels;
@@ -501,16 +585,16 @@ int snd_load_wav(const char *filename)
 				}
 
 				if(num_loops > 1)
-					file.skip((num_loops-1) * sizeof(loop));
+					io_skip(file, (num_loops-1) * sizeof(loop));
 
-				file.skip(skip);
+				io_skip(file, skip);
 				state++;
 			}
 			else
-				file.skip(chunk_size);
+				io_skip(file, chunk_size);
 		}
 		else
-			file.skip(chunk_size);
+			io_skip(file, chunk_size);
 	}
 
 	if(id >= 0)
@@ -534,17 +618,17 @@ int snd_play(int id, int loop, float vol, float pan)
 
 	dbg_assert(sounds[id].sound.data != 0, "null sound");
 	dbg_assert(sounds[id].next == -1, "sound isn't allocated");
-	return mixer.play(&sounds[id].sound, loop, vol, pan);
+	return mixer_play(&sounds[id].sound, loop, vol, pan);
 }
 
 void snd_stop(int id)
 {
 	if(id >= 0)
-		mixer.stop(id);
+		mixer_stop(id);
 }
 
 void snd_set_vol(int id, float vol)
 {
 	if(id >= 0)
-		mixer.set_vol(id, vol);
+		mixer_set_vol(id, vol);
 }
diff --git a/src/engine/client/ui.cpp b/src/engine/client/ui.c
index 7b309539..c67b1b13 100644
--- a/src/engine/client/ui.cpp
+++ b/src/engine/client/ui.c
@@ -1,4 +1,4 @@
-#include <baselib/system.h>
+#include <engine/system.h>
 #include <engine/interface.h>
 #include "ui.h"
 
@@ -14,7 +14,7 @@ struct pretty_font
 	int font_texture;
 };
 
-extern pretty_font *current_font;
+extern struct pretty_font *current_font;
 
 static void *hot_item = 0;
 static void *active_item = 0;
@@ -84,7 +84,7 @@ void ui_do_label(float x, float y, const char *text, float size)
 {
     gfx_blend_normal();
     gfx_texture_set(current_font->font_texture);
-    gfx_pretty_text(x, y, size, text);
+    gfx_pretty_text(x, y, size, text, -1);
 }
 
 int ui_do_button(void *id, const char *text, int checked, float x, float y, float w, float h, draw_button_callback draw_func, void *extra)
@@ -115,8 +115,3 @@ int ui_do_button(void *id, const char *text, int checked, float x, float y, floa
     return r;
 }
 
-int ui_do_button(void *id, const char *text, int checked, float x, float y, float w, float h, draw_button_callback draw_func)
-{
-	return ui_do_button(id, text, checked, x, y, w, h, draw_func, 0x0);
-}
-
diff --git a/src/engine/client/ui.h b/src/engine/client/ui.h
index fb9208c1..31757b3b 100644
--- a/src/engine/client/ui.h
+++ b/src/engine/client/ui.h
@@ -1,12 +1,9 @@
 #ifndef _UI_H
 #define _UI_H
-/*
-extern void *hot_item;
-extern void *active_item;
-extern void *becomming_hot_item;
-extern float mouse_x, mouse_y; // in gui space
-extern float mouse_wx, mouse_wy; // in world space
-extern unsigned mouse_buttons;*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
 
 int ui_update(float mx, float my, float mwx, float mwy, int buttons);
 
@@ -30,6 +27,9 @@ typedef void (*draw_button_callback)(void *id, const char *text, int checked, fl
 void ui_do_image(int texture, float x, float y, float w, float h);
 void ui_do_label(float x, float y, const char *text, float size);
 int ui_do_button(void *id, const char *text, int checked, float x, float y, float w, float h, draw_button_callback draw_func, void *extra);
-int ui_do_button(void *id, const char *text, int checked, float x, float y, float w, float h, draw_button_callback draw_func);
+
+#ifdef __cplusplus
+}
+#endif
 
 #endif
diff --git a/src/engine/compression.cpp b/src/engine/compression.c
index 427eceb5..2f3e37ca 100644
--- a/src/engine/compression.cpp
+++ b/src/engine/compression.c
@@ -1,59 +1,59 @@
-#include <baselib/system.h>
+#include "system.h"
 #include <string.h>
 
 // Format: ESDDDDDD EDDDDDDD EDD...  Extended, Data, Sign
 unsigned char *vint_pack(unsigned char *dst, int i) 
 { 
-        *dst = (i>>25)&0x40; // set sign bit if i<0
+	*dst = (i>>25)&0x40; // set sign bit if i<0
 	i = i^(i>>31); // if(i<0) i = ~i
- 
-        *dst |= i&0x3F; // pack 6bit into dst
-        i >>= 6; // discard 6 bits
-        if(i)
+
+	*dst |= i&0x3F; // pack 6bit into dst
+	i >>= 6; // discard 6 bits
+	if(i)
 	{
-                *dst |= 0x80; // set extend bit
+		*dst |= 0x80; // set extend bit
 		while(1)
 		{
 			dst++;
-	                *dst = i&(0x7F); // pack 7bit
-        	        i >>= 7; // discard 7 bits
+			*dst = i&(0x7F); // pack 7bit
+			i >>= 7; // discard 7 bits
 			*dst |= (i!=0)<<7; // set extend bit (may branch)
-                	if(!i)
+			if(!i)
 				break;
 		}
 	}
 
 	dst++;
-        return dst; 
+	return dst; 
 } 
  
 const unsigned char *vint_unpack(const unsigned char *src, int *i)
 { 
-        int sign = (*src>>6)&1; 
-        *i = *src&0x3F; 
+	int sign = (*src>>6)&1; 
+	*i = *src&0x3F; 
 
 	do
 	{ 
-	        if(!(*src&0x80)) break;
+		if(!(*src&0x80)) break;
 		src++;
-                *i |= (*src&(0x7F))<<(6);
+		*i |= (*src&(0x7F))<<(6);
 
-	        if(!(*src&0x80)) break;
+		if(!(*src&0x80)) break;
 		src++;
-                *i |= (*src&(0x7F))<<(6+7);
+		*i |= (*src&(0x7F))<<(6+7);
 
-	        if(!(*src&0x80)) break;
+		if(!(*src&0x80)) break;
 		src++;
-                *i |= (*src&(0x7F))<<(6+7+7);
+		*i |= (*src&(0x7F))<<(6+7+7);
 
-	        if(!(*src&0x80)) break;
+		if(!(*src&0x80)) break;
 		src++;
-                *i |= (*src&(0x7F))<<(6+7+7+7);
+		*i |= (*src&(0x7F))<<(6+7+7+7);
 	} while(0);
 
 	src++;
 	*i ^= -sign; // if(sign) *i = ~(*i)
-        return src; 
+	return src; 
 } 
 
 
@@ -85,21 +85,22 @@ long intpack_compress(const void *src_, int size, void *dst_)
 }
 
 
+//
 long zerobit_compress(const void *src_, int size, void *dst_)
 {
 	unsigned char *src = (unsigned char *)src_;
 	unsigned char *dst = (unsigned char *)dst_;
 	
-	//int zerocount = 0 ;
 	while(size)
 	{
 		unsigned char bit = 0x80;
 		unsigned char mask = 0;
 		int dst_move = 1;
 		int chunk = size < 8 ? size : 8;
+		int b;
 		size -= chunk;
 		
-		for(int b = 0; b < chunk; b++, bit>>=1)
+		for(b = 0; b < chunk; b++, bit>>=1)
 		{
 			if(*src)
 			{
@@ -115,9 +116,7 @@ long zerobit_compress(const void *src_, int size, void *dst_)
 		dst += dst_move;
 	}
 	
-	long l = (long)(dst-(unsigned char *)dst_);
-	//dbg_msg("zerobit", "%d", (int)l);
-	return l;
+	return (long)(dst-(unsigned char *)dst_);
 }
 
 long zerobit_decompress(const void *src_, int size, void *dst_)
@@ -126,13 +125,13 @@ long zerobit_decompress(const void *src_, int size, void *dst_)
 	unsigned char *dst = (unsigned char *)dst_;
 	unsigned char *end = src + size;
 	
-	//int zerocount = 0 ;
 	while(src != end)
 	{
 		unsigned char bit = 0x80;
 		unsigned char mask = *src++;
+		int b;
 		
-		for(int b = 0; b < 8; b++, bit>>=1)
+		for(b = 0; b < 8; b++, bit>>=1)
 		{
 			if(mask&bit)
 				*dst++ = *src++;
@@ -142,7 +141,6 @@ long zerobit_decompress(const void *src_, int size, void *dst_)
 	}
 	
 	long l = (long)(dst-(unsigned char *)dst_);
-	//dbg_msg("zerobit", "%d", (int)l);
 	return l;
 }
 
diff --git a/src/engine/compression.h b/src/engine/compression.h
index 607b826e..9f6cedc5 100644
--- a/src/engine/compression.h
+++ b/src/engine/compression.h
@@ -1,12 +1,10 @@
-// lzw is no longer in use
-//long lzw_compress(const void *src, int size, void *dst);
-//long lzw_decompress(const void *src, void *dst);
 
+/* variable int packing */
 unsigned char *vint_pack(unsigned char *dst, int i);
 const unsigned char *vint_unpack(const unsigned char *src, int *inout);
-
 long intpack_compress(const void *src, int size, void *dst);
 long intpack_decompress(const void *src, int size, void *dst);
 
+/* zerobit packing */
 long zerobit_compress(const void *src, int size, void *dst);
 long zerobit_decompress(const void *src, int size, void *dst);
diff --git a/src/engine/config.cpp b/src/engine/config.c
index 508f6368..59c07f3e 100644
--- a/src/engine/config.cpp
+++ b/src/engine/config.c
@@ -1,16 +1,82 @@
-#include <baselib/system.h>
-#include <baselib/stream/file.h>
-#include <baselib/stream/line.h>
 
-#include <cstring>
-#include <cstdio>
-#include <cstdlib>
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
 
+#include "system.h"
 #include "config.h"
 
-configuration config;
 
-using namespace baselib;
+// buffered stream for reading lines, should perhaps be something smaller
+typedef struct
+{
+	char buffer[4*1024];
+	unsigned buffer_pos;
+	unsigned buffer_size;
+	unsigned buffer_max_size;
+	IOHANDLE io;
+} LINEREADER;
+
+void linereader_init(LINEREADER *lr, IOHANDLE io)
+{
+	lr->buffer_max_size = 4*1024;
+	lr->buffer_size = 0;
+	lr->buffer_pos = 0;
+	lr->io = io;
+}
+
+char *linereader_get(LINEREADER *lr)
+{
+	unsigned line_start = lr->buffer_pos;
+
+	while(1)
+	{
+		if(lr->buffer_pos >= lr->buffer_size)
+		{
+			// fetch more
+
+			// move the remaining part to the front
+			unsigned left = lr->buffer_size - line_start;
+			if(line_start > lr->buffer_size)
+				left = 0;
+			if(left)
+				mem_move(lr->buffer, &lr->buffer[line_start], left);
+			lr->buffer_pos = left;
+
+			// fill the buffer
+			unsigned read = io_read(lr->io, &lr->buffer[lr->buffer_pos], lr->buffer_max_size-lr->buffer_pos);
+			lr->buffer_size = left + read;
+			line_start = 0;
+
+			if(!read)
+			{
+				if(left)
+				{
+					lr->buffer[left] = 0; // return the last line
+					lr->buffer_pos = left;
+					lr->buffer_size = left;
+					return lr->buffer;
+				}
+				else
+					return 0x0; // we are done!
+			}
+		}
+		else
+		{
+			if(lr->buffer[lr->buffer_pos] == '\n' || lr->buffer[lr->buffer_pos] == '\r')
+			{
+				// line found
+				lr->buffer[lr->buffer_pos] = 0;
+				lr->buffer_pos++;
+				return &lr->buffer[line_start];
+			}
+			else
+				lr->buffer_pos++;
+		}
+	}
+}
+
+CONFIGURATION config;
 
 void config_reset()
 {
@@ -25,7 +91,7 @@ void config_reset()
 
 void strip_spaces(char **p)
 {
-	char *&s = *p;
+	char *s = *p;
 	
 	while (*s == ' ')
 		++s;
@@ -77,20 +143,20 @@ void config_load(const char *filename)
 		}
 	}
 
-
 	dbg_msg("config/load", "loading %s", filename);
 
-	file_stream file;
-
-	if (file.open_r(filename))
+	IOHANDLE file = io_open(filename, IOFLAG_READ);
+	
+	if(file)
 	{
 		char *line;
-		line_stream lstream(&file);
+		LINEREADER lr;
+		linereader_init(&lr, file);
 
-		while ((line = lstream.get_line()))
+		while ((line = linereader_get(&lr)))
 			config_set(line);
 
-		file.close();
+		io_close(file);
 	}
 }
 
@@ -110,9 +176,10 @@ void config_save(const char *filename)
 
 	dbg_msg("config/save", "saving config to %s", filename);
 
-	file_stream file;
+	//file_stream file;
+	IOHANDLE file = io_open(filename, IOFLAG_WRITE);
 
-	if (file.open_w(filename))
+	if(file)
 	{
 #if defined(CONF_FAMILY_WINDOWS)
 		const char newline[] = "\r\n";
@@ -121,28 +188,28 @@ void config_save(const char *filename)
 #endif
 		const int newline_len = sizeof(newline)-1;
 		
-    	#define MACRO_CONFIG_INT(name,def,min,max) { char str[256]; sprintf(str, "%s=%i", #name, config.name); file.write(str, strlen(str)); file.write(newline, newline_len); }
-    	#define MACRO_CONFIG_STR(name,len,def) { file.write(#name, strlen(#name)); file.write("=", 1); file.write(config.name, strlen(config.name)); file.write(newline, newline_len); }
+    	#define MACRO_CONFIG_INT(name,def,min,max) { char str[256]; sprintf(str, "%s=%i%s", #name, config.name, newline); io_write(file, str, strlen(str)); }
+    	#define MACRO_CONFIG_STR(name,len,def) { io_write(file, #name, strlen(#name)); io_write(file, "=", 1); io_write(file, config.name, strlen(config.name)); io_write(file, newline, newline_len); }
  
     	#include "config_variables.h" 
  
     	#undef MACRO_CONFIG_INT 
     	#undef MACRO_CONFIG_STR 
 
-		file.close();
+		io_close(file);
 	}
 	else
 		dbg_msg("config/save", "couldn't open %s for writing. :(", filename);
 }
 
-#define MACRO_CONFIG_INT(name,def,min,max) int config_get_ ## name (configuration *c) { return c->name; }
-#define MACRO_CONFIG_STR(name,len,def) const char *config_get_ ## name (configuration *c) { return c->name; }
+#define MACRO_CONFIG_INT(name,def,min,max) int config_get_ ## name (CONFIGURATION *c) { return c->name; }
+#define MACRO_CONFIG_STR(name,len,def) const char *config_get_ ## name (CONFIGURATION *c) { return c->name; }
 #include "config_variables.h"
 #undef MACRO_CONFIG_INT
 #undef MACRO_CONFIG_STR
 
-#define MACRO_CONFIG_INT(name,def,min,max) void config_set_ ## name (configuration *c, int val) { if (val < min) val = min; if (max != 0 && val > max) val = max; c->name = val; }
-#define MACRO_CONFIG_STR(name,len,def) void config_set_ ## name (configuration *c, const char *str) { strncpy(c->name, str, len-1); c->name[sizeof(c->name)-1] = 0; }
+#define MACRO_CONFIG_INT(name,def,min,max) void config_set_ ## name (CONFIGURATION *c, int val) { if (val < min) val = min; if (max != 0 && val > max) val = max; c->name = val; }
+#define MACRO_CONFIG_STR(name,len,def) void config_set_ ## name (CONFIGURATION *c, const char *str) { strncpy(c->name, str, len-1); c->name[sizeof(c->name)-1] = 0; }
 #include "config_variables.h"
 #undef MACRO_CONFIG_INT
 #undef MACRO_CONFIG_STR
diff --git a/src/engine/config.h b/src/engine/config.h
index 09851d78..ce0a6567 100644
--- a/src/engine/config.h
+++ b/src/engine/config.h
@@ -1,30 +1,30 @@
 #ifndef _CONFIG_H
 #define _CONFIG_H
 
-struct configuration
+typedef struct
 { 
     #define MACRO_CONFIG_INT(name,def,min,max) int name;
     #define MACRO_CONFIG_STR(name,len,def) char name[len];
     #include "config_variables.h" 
     #undef MACRO_CONFIG_INT 
     #undef MACRO_CONFIG_STR 
-}; 
+} CONFIGURATION;
 
-extern configuration config;
+extern CONFIGURATION config;
 
 void config_set(const char *line);
 void config_reset();
 void config_load(const char *filename);
 void config_save(const char *filename);
 
-#define MACRO_CONFIG_INT(name,def,min,max) int config_get_ ## name (configuration *c);
-#define MACRO_CONFIG_STR(name,len,def) const char *config_get_ ## name (configuration *c);
+#define MACRO_CONFIG_INT(name,def,min,max) int config_get_ ## name (CONFIGURATION *c);
+#define MACRO_CONFIG_STR(name,len,def) const char *config_get_ ## name (CONFIGURATION *c);
 #include "config_variables.h"
 #undef MACRO_CONFIG_INT
 #undef MACRO_CONFIG_STR
 
-#define MACRO_CONFIG_INT(name,def,min,max) void config_set_ ## name (configuration *c, int val);
-#define MACRO_CONFIG_STR(name,len,def) void config_set_ ## name (configuration *c, const char *str);
+#define MACRO_CONFIG_INT(name,def,min,max) void config_set_ ## name (CONFIGURATION *c, int val);
+#define MACRO_CONFIG_STR(name,len,def) void config_set_ ## name (CONFIGURATION *c, const char *str);
 #include "config_variables.h"
 #undef MACRO_CONFIG_INT
 #undef MACRO_CONFIG_STR
diff --git a/src/engine/datafile.cpp b/src/engine/datafile.c
index b3a23589..1df5fee3 100644
--- a/src/engine/datafile.cpp
+++ b/src/engine/datafile.c
@@ -1,24 +1,23 @@
-#include <baselib/system.h>
-#include <baselib/stream/file.h>
 
+#include "system.h"
 #include "datafile.h"
 
 static const int DEBUG=0;
 
-struct item_type
+typedef struct 
 {
 	int type;
 	int start;
 	int num;
-};
+} DATAFILE_ITEM_TYPE;
 
-struct item
+typedef struct 
 {
 	int type_and_id;
 	int size;
-};
+} DATAFILE_ITEM;
 
-struct datafile_header
+typedef struct
 {
 	int id;
 	int version;
@@ -29,9 +28,9 @@ struct datafile_header
 	int num_raw_data;
 	int item_size;
 	int data_size;
-};
+} DATAFILE_HEADER;
 
-struct datafile_data
+typedef struct
 {
 	int num_item_types;
 	int num_items;
@@ -39,56 +38,71 @@ struct datafile_data
 	int item_size;
 	int data_size;
 	char start[4];
-};
+} DATAFILE_DATA;
 
-struct datafile_info
+typedef struct
 {
-	item_type *item_types;
+	DATAFILE_ITEM_TYPE *item_types;
 	int *item_offsets;
 	int *data_offsets;
 
 	char *item_start;
 	char *data_start;	
-};
+} DATAFILE_INFO;
 
-struct datafile
+struct DATAFILE_t
 {
-	datafile_info info;
-	datafile_data data;
+	DATAFILE_INFO info;
+	DATAFILE_DATA data;
 };
 
-datafile *datafile_load(const char *filename)
+DATAFILE *datafile_load(const char *filename)
 {
+	DATAFILE *df;
+	IOHANDLE file;
+	unsigned char header[16];
+	int version;
+	unsigned size, swapsize, readsize;
+	
+	unsigned *dst;
+	unsigned char *src;
+	unsigned j;
+	(void)dst;
+	(void)src;
+	(void)j;
+	
+	
 	dbg_msg("datafile", "datafile loading. filename='%s'", filename);
 
-	baselib::file_stream file;
-	if(!file.open_r(filename))
+	file = io_open(filename, IOFLAG_READ);
+	if(!file)
 		return 0;
 	
-	// TODO: change this header
-	unsigned char header[16];
-	file.read(header, sizeof(header));
+	/* TODO: change this header */
+	io_read(file, header, sizeof(header));
 	if(header[3] != 'D' || header[2] != 'A' || header[1] != 'T' || header[0] != 'A')
 	{
 		dbg_msg("datafile", "wrong signature. %x %x %x %x", header[0], header[1], header[2], header[3]);
 		return 0;
 	}
 	
-	int version = (unsigned)header[4] | (unsigned)header[5]<<8 | (unsigned)header[6]<<16 | (unsigned)header[7]<<24;
+	version = (unsigned)header[4] | (unsigned)header[5]<<8 | (unsigned)header[6]<<16 | (unsigned)header[7]<<24;
 	if(version != 3)
 	{
 		dbg_msg("datafile", "wrong version. version=%x", version);
 		return 0;
 	}
 	
-	unsigned size = (unsigned)header[8] | (unsigned)header[9]<<8 | (unsigned)header[10]<<16 | (unsigned)header[11]<<24;
-	unsigned swapsize = (unsigned)header[12] | (unsigned)header[13]<<8 | (unsigned)header[14]<<16 | (unsigned)header[15]<<24;
+	size = (unsigned)header[8] | (unsigned)header[9]<<8 | (unsigned)header[10]<<16 | (unsigned)header[11]<<24;
+	swapsize = (unsigned)header[12] | (unsigned)header[13]<<8 | (unsigned)header[14]<<16 | (unsigned)header[15]<<24;
+	
+	(void)swapsize;
 	
 	if(DEBUG)
 		dbg_msg("datafile", "loading. size=%d", size);
 	
-	datafile *df = (datafile*)mem_alloc(size+sizeof(datafile_info), 1);
-	unsigned readsize = file.read(&df->data, size);
+	df = (DATAFILE*)mem_alloc(size+sizeof(DATAFILE_INFO), 1);
+	readsize = io_read(file, &df->data, size);
 	if(readsize != size)
 	{
 		dbg_msg("datafile", "couldn't load the whole thing, wanted=%d got=%d", size, readsize);
@@ -108,7 +122,7 @@ datafile *datafile_load(const char *filename)
 	if(DEBUG)
 		dbg_msg("datafile", "item_size=%d", df->data.item_size);
 	
-	df->info.item_types = (item_type *)df->data.start;
+	df->info.item_types = (DATAFILE_ITEM_TYPE *)df->data.start;
 	df->info.item_offsets = (int *)&df->info.item_types[df->data.num_item_types];
 	df->info.data_offsets = (int *)&df->info.item_offsets[df->data.num_items];
 	
@@ -120,6 +134,7 @@ datafile *datafile_load(const char *filename)
 
 	if(DEBUG)
 	{
+		/*
 		for(int i = 0; i < df->data.num_raw_data; i++)
 		{
 			void *p = datafile_get_data(df, i);
@@ -150,29 +165,31 @@ datafile *datafile_load(const char *filename)
 					dbg_msg("map", "\tERROR");
 			}
 		}
+		*/
 	}
 		
 	return df;
 }
 
-void *datafile_get_data(datafile *df, int index)
+void *datafile_get_data(DATAFILE *df, int index)
 {
 	return df->info.data_start+df->info.data_offsets[index];
 }
 
-void *datafile_get_item(datafile *df, int index, int *type, int *id)
+void *datafile_get_item(DATAFILE *df, int index, int *type, int *id)
 {
-	item *i = (item *)(df->info.item_start+df->info.item_offsets[index]);
+	DATAFILE_ITEM *i = (DATAFILE_ITEM *)(df->info.item_start+df->info.item_offsets[index]);
 	if(type)
-		*type = (i->type_and_id>>16)&0xffff; // remove sign extention
+		*type = (i->type_and_id>>16)&0xffff; /* remove sign extention */
 	if(id)
 		*id = i->type_and_id&0xffff;
 	return (void *)(i+1);
 }
 
-void datafile_get_type(datafile *df, int type, int *start, int *num)
+void datafile_get_type(DATAFILE *df, int type, int *start, int *num)
 {
-	for(int i = 0; i < df->data.num_item_types; i++)
+	int i;
+	for(i = 0; i < df->data.num_item_types; i++)
 	{
 		if(df->info.item_types[i].type == type)
 		{
@@ -186,39 +203,42 @@ void datafile_get_type(datafile *df, int type, int *start, int *num)
 	*num = 0;
 }
 
-void *datafile_find_item(datafile *df, int type, int id)
+void *datafile_find_item(DATAFILE *df, int type, int id)
 {
-	int start, num;
+	int start, num,i ;
+	int item_id;
+	void *item;
+	
 	datafile_get_type(df, type, &start, &num);
-	for(int i = 0; i < num; i++)
+	for(i = 0; i < num; i++)
 	{
-		int item_id;
-		void *item = datafile_get_item(df, start+i,0, &item_id);
+		
+		item = datafile_get_item(df, start+i,0, &item_id);
 		if(id == item_id)
 			return item;
 	}
 	return 0;
 }
 
-int datafile_num_items(datafile *df)
+int datafile_num_items(DATAFILE *df)
 {
 	return df->data.num_items;
 }
 
-void datafile_unload(datafile *df)
+void datafile_unload(DATAFILE *df)
 {
 	if(df)
 		mem_free(df);
 }
 
-// DATAFILE output
-struct data_info
+/* DATAFILE output */
+typedef struct
 {
 	int size;
 	void *data;
-};
+} DATA_INFO;
 
-struct item_info
+typedef struct
 {
 	int type;
 	int id;
@@ -226,33 +246,35 @@ struct item_info
 	int next;
 	int prev;
 	void *data;
-};
+} ITEM_INFO;
 
-struct itemtype_info
+typedef struct
 {
 	int num;
 	int first;
 	int last;
-};
+} ITEMTYPE_INFO;
 
-//
-struct datafile_out
+/* */
+struct DATAFILE_OUT_t
 {
-	baselib::file_stream file;
+	IOHANDLE file;
 	int num_items;
 	int num_datas;
 	int num_item_types;
-	itemtype_info item_types[0xffff];
-	item_info items[1024];
-	data_info datas[1024];
+	ITEMTYPE_INFO item_types[0xffff];
+	ITEM_INFO items[1024];
+	DATA_INFO datas[1024];
 };
 
-datafile_out *datafile_create(const char *filename)
+DATAFILE_OUT *datafile_create(const char *filename)
 {
-	datafile_out *df = new datafile_out;
-	if(!df->file.open_w(filename))
+	int i;
+	DATAFILE_OUT *df = mem_alloc(sizeof(DATAFILE_OUT), 1);
+	df->file = io_open(filename, IOFLAG_WRITE);
+	if(!df->file)
 	{
-		delete df;
+		mem_free(df);
 		return 0;
 	}
 	
@@ -261,7 +283,7 @@ datafile_out *datafile_create(const char *filename)
 	df->num_item_types = 0;
 	mem_zero(&df->item_types, sizeof(df->item_types));
 
-	for(int i = 0; i < 0xffff; i++)
+	for(i = 0; i < 0xffff; i++)
 	{
 		df->item_types[i].first = -1;
 		df->item_types[i].last = -1;
@@ -270,20 +292,20 @@ datafile_out *datafile_create(const char *filename)
 	return df;
 }
 
-int datafile_add_item(datafile_out *df, int type, int id, int size, void *data)
+int datafile_add_item(DATAFILE_OUT *df, int type, int id, int size, void *data)
 {
 	df->items[df->num_items].type = type;
 	df->items[df->num_items].id = id;
 	df->items[df->num_items].size = size;
 	
-	// copy data
+	/* copy data */
 	df->items[df->num_items].data = mem_alloc(size, 1);
 	mem_copy(df->items[df->num_items].data, data, size);
 
-	if(!df->item_types[type].num) // count item types
+	if(!df->item_types[type].num) /* count item types */
 		df->num_item_types++;
 
-	// link
+	/* link */
 	df->items[df->num_items].prev = df->item_types[type].last;
 	df->items[df->num_items].next = -1;
 	
@@ -300,7 +322,7 @@ int datafile_add_item(datafile_out *df, int type, int id, int size, void *data)
 	return df->num_items-1;
 }
 
-int datafile_add_data(datafile_out *df, int size, void *data)
+int datafile_add_data(DATAFILE_OUT *df, int size, void *data)
 {
 	df->datas[df->num_items].size = size;
 	df->datas[df->num_datas].data = data;
@@ -308,37 +330,45 @@ int datafile_add_data(datafile_out *df, int size, void *data)
 	return df->num_datas-1;
 }
 
-int datafile_finish(datafile_out *df)
+int datafile_finish(DATAFILE_OUT *df)
 {
-	// we should now write this file!
+	/* we should now write this file! */
 	if(DEBUG)
 		dbg_msg("datafile", "writing");
 
-	// calculate sizes
 	int itemsize = 0;
-	for(int i = 0; i < df->num_items; i++)
+	int i, count, offset;
+	int typessize, headersize, offsetsize, filesize, swapsize;
+	int datasize = 0;
+	DATAFILE_ITEM_TYPE info;
+	DATAFILE_ITEM itm;
+	
+	/* calculate sizes */
+	for(i = 0; i < df->num_items; i++)
 	{
 		if(DEBUG)
-			dbg_msg("datafile", "item=%d size=%d (%d)", i, df->items[i].size, df->items[i].size+sizeof(item));
-		itemsize += df->items[i].size + sizeof(item);
+			dbg_msg("datafile", "item=%d size=%d (%d)", i, df->items[i].size, df->items[i].size+sizeof(DATAFILE_ITEM));
+		itemsize += df->items[i].size + sizeof(DATAFILE_ITEM);
 	}
 	
-	int datasize = 0;
-	for(int i = 0; i < df->num_datas; i++)
+	
+	for(i = 0; i < df->num_datas; i++)
 		datasize += df->datas[i].size;
 	
-	// calculate the complete size
-	int typessize = df->num_item_types*sizeof(item_type);
-	int headersize = sizeof(datafile_header);
-	int offsetsize = df->num_items*sizeof(int) + df->num_datas*sizeof(int);
-	int filesize = headersize + typessize + offsetsize + itemsize + datasize;
-	int swapsize = filesize - datasize;
+	/* calculate the complete size */
+	typessize = df->num_item_types*sizeof(DATAFILE_ITEM_TYPE);
+	headersize = sizeof(DATAFILE_HEADER);
+	offsetsize = df->num_items*sizeof(int) + df->num_datas*sizeof(int);
+	filesize = headersize + typessize + offsetsize + itemsize + datasize;
+	swapsize = filesize - datasize;
+	
+	(void)swapsize;
 	
 	if(DEBUG)
 		dbg_msg("datafile", "num_item_types=%d typessize=%d itemsize=%d datasize=%d", df->num_item_types, typessize, itemsize, datasize);
 	
-	// construct header
-	datafile_header header;
+	/* construct header */
+	DATAFILE_HEADER header;
 	header.id = ('D'<<24) | ('A'<<16) | ('T'<<8) | ('A');
 	header.version = 3;
 	header.size = filesize - 16;
@@ -349,96 +379,95 @@ int datafile_finish(datafile_out *df)
 	header.item_size = itemsize;
 	header.data_size = datasize;
 	
-	// TODO: apply swapping
-	// write header
+	/* TODO: apply swapping */
+	/* write header */
 	if(DEBUG)
 		dbg_msg("datafile", "headersize=%d", sizeof(header));
-	df->file.write(&header, sizeof(header));
+	io_write(df->file, &header, sizeof(header));
 	
-	// write types
-	for(int i = 0, count = 0; i < 0xffff; i++)
+	/* write types */
+	for(i = 0, count = 0; i < 0xffff; i++)
 	{
 		if(df->item_types[i].num)
 		{
-			// write info
-			item_type info;
+			/* write info */
 			info.type = i;
 			info.start = count;
 			info.num = df->item_types[i].num;
 			if(DEBUG)
 				dbg_msg("datafile", "writing type=%x start=%d num=%d", info.type, info.start, info.num);
-			df->file.write(&info, sizeof(info));
-			
+			io_write(df->file, &info, sizeof(info));
 			count += df->item_types[i].num;
 		}
 	}
 	
-	// write item offsets
-	for(int i = 0, offset = 0; i < 0xffff; i++)
+	/* write item offsets */
+	for(i = 0, offset = 0; i < 0xffff; i++)
 	{
 		if(df->item_types[i].num)
 		{
-			// write all items in of this type
+			/* write all items in of this type */
 			int k = df->item_types[i].first;
 			while(k != -1)
 			{
 				if(DEBUG)
 					dbg_msg("datafile", "writing item offset num=%d offset=%d", k, offset);
-				df->file.write(&offset, sizeof(offset));
-				offset += df->items[k].size + sizeof(item);
+				io_write(df->file, &offset, sizeof(offset));
+				offset += df->items[k].size + sizeof(DATAFILE_ITEM);
 				
-				// next
+				/* next */
 				k = df->items[k].next;
 			}
 		}
 	}
 	
-	// write data offsets
-	for(int i = 0, offset = 0; i < df->num_datas; i++)
+	/* write data offsets */
+	for(i = 0, offset = 0; i < df->num_datas; i++)
 	{
 		if(DEBUG)
 			dbg_msg("datafile", "writing data offset num=%d offset=%d", i, offset);
-		df->file.write(&offset, sizeof(offset));
+		io_write(df->file, &offset, sizeof(offset));
 		offset += df->datas[i].size;
 	}
 	
-	// write items
-	for(int i = 0; i < 0xffff; i++)
+	/* write items */
+	for(i = 0; i < 0xffff; i++)
 	{
 		if(df->item_types[i].num)
 		{
-			// write all items in of this type
+			/* write all items in of this type */
 			int k = df->item_types[i].first;
 			while(k != -1)
 			{
-				item itm;
 				itm.type_and_id = (i<<16)|df->items[k].id;
 				itm.size = df->items[k].size;
 				if(DEBUG)
 					dbg_msg("datafile", "writing item type=%x idx=%d id=%d size=%d", i, k, df->items[k].id, df->items[k].size);
-				df->file.write(&itm, sizeof(itm));
-				df->file.write(df->items[k].data, df->items[k].size);
 				
-				// next
+				io_write(df->file, &itm, sizeof(itm));
+				io_write(df->file, df->items[k].data, df->items[k].size);
+				
+				/* next */
 				k = df->items[k].next;
 			}
 		}
 	}
 	
-	// write data
-	for(int i = 0; i < df->num_datas; i++)
+	/* write data */
+	for(i = 0; i < df->num_datas; i++)
 	{
 		if(DEBUG)
 			dbg_msg("datafile", "writing data id=%d size=%d", i, df->datas[i].size);
-		df->file.write(df->datas[i].data, df->datas[i].size);
+		io_write(df->file, df->datas[i].data, df->datas[i].size);
 	}
 
-	// free data
-	for(int i = 0; i < df->num_items; i++)
+	/* free data */
+	for(i = 0; i < df->num_items; i++)
 		mem_free(df->items[i].data);
 
 	
-	delete df;
+	io_close(df->file);
+	mem_free(df);
 
 	if(DEBUG)
 		dbg_msg("datafile", "done");
diff --git a/src/engine/datafile.h b/src/engine/datafile.h
index 4e49fa03..8d1e8144 100644
--- a/src/engine/datafile.h
+++ b/src/engine/datafile.h
@@ -1,20 +1,20 @@
 
-// raw datafile access
-struct datafile;
+/* raw datafile access */
+typedef struct DATAFILE_t DATAFILE;
 
-// read access
-datafile *datafile_load(const char *filename);
-datafile *datafile_load_old(const char *filename);
-void *datafile_get_data(datafile *df, int index);
-void *datafile_get_item(datafile *df, int index, int *type, int *id);
-void datafile_get_type(datafile *df, int type, int *start, int *num);
-void *datafile_find_item(datafile *df, int type, int id);
-int datafile_num_items(datafile *df);
-void datafile_unload(datafile *df);
+/* read access */
+DATAFILE *datafile_load(const char *filename);
+DATAFILE *datafile_load_old(const char *filename);
+void *datafile_get_data(DATAFILE *df, int index);
+void *datafile_get_item(DATAFILE *df, int index, int *type, int *id);
+void datafile_get_type(DATAFILE *df, int type, int *start, int *num);
+void *datafile_find_item(DATAFILE *df, int type, int id);
+int datafile_num_items(DATAFILE *df);
+void datafile_unload(DATAFILE *df);
 
-// write access
-struct datafile_out;
-datafile_out *datafile_create(const char *filename);
-int datafile_add_data(datafile_out *df, int size, void *data);
-int datafile_add_item(datafile_out *df, int type, int id, int size, void *data);
-int datafile_finish(datafile_out *df);
+/* write access */
+typedef struct DATAFILE_OUT_t DATAFILE_OUT;
+DATAFILE_OUT *datafile_create(const char *filename);
+int datafile_add_data(DATAFILE_OUT *df, int size, void *data);
+int datafile_add_item(DATAFILE_OUT *df, int type, int id, int size, void *data);
+int datafile_finish(DATAFILE_OUT *df);
diff --git a/src/engine/detect.h b/src/engine/detect.h
new file mode 100644
index 00000000..242a5ce6
--- /dev/null
+++ b/src/engine/detect.h
@@ -0,0 +1,114 @@
+#ifndef BASELIB_FILE_CONFIG_H
+#define BASELIB_FILE_CONFIG_H
+
+/*
+  this file detected the family, platform and architecture
+  to compile for.
+*/
+
+/* platforms */
+
+/* windows Family */
+#if defined(WIN64) || defined(_WIN64)
+	/* Hmm, is this IA64 or x86-64? */
+	#define CONF_FAMILY_WINDOWS 1
+	#define CONF_FAMILY_STRING "windows"
+	#define CONF_PLATFORM_WIN64 1
+	#define CONF_PLATFORM_STRING "win64"
+#elif defined(WIN32) || defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__)
+	#define CONF_FAMILY_WINDOWS 1
+	#define CONF_FAMILY_STRING "windows"
+	#define CONF_PLATFORM_WIN32 1
+	#define CONF_PLATFORM_STRING "win32"
+#endif
+
+/* unix family */
+#if defined(__FreeBSD__)
+	#define CONF_FAMILY_UNIX 1
+	#define CONF_FAMILY_STRING "unix"
+	#define CONF_PLATFORM_FREEBSD 1
+	#define CONF_PLATFORM_STRING "freebsd"
+#endif
+
+#if defined(__OpenBSD__)
+	#define CONF_FAMILY_UNIX 1
+	#define CONF_FAMILY_STRING "unix"
+	#define CONF_PLATFORM_OPENBSD 1
+	#define CONF_PLATFORM_STRING "openbsd"
+#endif
+
+#if defined(__LINUX__) || defined(__linux__)
+	#define CONF_FAMILY_UNIX 1
+	#define CONF_FAMILY_STRING "unix"
+	#define CONF_PLATFORM_LINUX 1
+	#define CONF_PLATFORM_STRING "linux"
+#endif
+
+#if defined(MACOSX) || defined(__APPLE__) || defined(__DARWIN__)
+	#define CONF_FAMILY_UNIX 1
+	#define CONF_FAMILY_STRING "unix"
+	#define CONF_PLATFORM_MACOSX 1
+	#define CONF_PLATFORM_STRING "macosx"
+#endif
+
+#if defined(__sun)
+	#define CONF_FAMILY_UNIX 1
+	#define CONF_FAMILY_STRING "unix"
+	#define CONF_PLATFROM_SOLARIS 1
+	#define CONF_PLATFORM_STRING "solaris"
+#endif
+
+/* beos family */
+#if defined(__BeOS) || defined(__BEOS__)
+	#define CONF_FAMILY_BEOS 1
+	#define CONF_FAMILY_STRING "beos"
+	#define CONF_PLATFORM_BEOS 1
+	#define CONF_PLATFORM_STRING "beos"
+#endif
+
+
+/* architectures */
+#if defined(i386) || defined(__i386__) || defined(__x86__) || defined(CONF_PLATFORM_WIN32)
+	#define CONF_ARCH_IA32 1
+	#define CONF_ARCH_STRING "ia32"
+	#define CONF_ARCH_ENDIAN_LITTLE 1
+#endif
+
+#if defined(__ia64__)
+	#define CONF_ARCH_IA64 1
+	#define CONF_ARCH_STRING "ia64"
+	#define CONF_ARCH_ENDIAN_LITTLE 1
+#endif
+
+#if defined(__amd64__) || defined(__x86_64__)
+	#define CONF_ARCH_AMD64 1
+	#define CONF_ARCH_STRING "amd64"
+	#define CONF_ARCH_ENDIAN_LITTLE 1
+#endif
+
+#if defined(__powerpc__) || defined(__ppc__)
+	#define CONF_ARCH_PPC 1
+	#define CONF_ARCH_STRING "ppc"
+	#define CONF_ARCH_ENDIAN_BIG 1
+#endif
+
+#if defined(__sparc__)
+	#define CONF_ARCH_SPARC 1
+	#define CONF_ARCH_STRING "sparc"
+	#define CONF_ARCH_ENDIAN_BIG 1
+#endif
+
+
+#ifndef CONF_FAMILY_STRING
+#define CONF_FAMILY_STRING "unknown"
+#endif
+
+#ifndef CONF_PLATFORM_STRING
+#define CONF_PLATFORM_STRING "unknown"
+#endif
+
+#ifndef CONF_ARCH_STRING
+#define CONF_ARCH_STRING "unknown"
+#endif
+
+#endif
diff --git a/src/engine/external/glfw/include/GL/glfw.h b/src/engine/external/glfw/include/GL/glfw.h
new file mode 100644
index 00000000..e5af4cc9
--- /dev/null
+++ b/src/engine/external/glfw/include/GL/glfw.h
@@ -0,0 +1,486 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        glfw.h

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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 __glfw_h_

+#define __glfw_h_

+

+#ifdef __cplusplus

+extern "C" {

+#endif

+

+

+//========================================================================

+// Global definitions

+//========================================================================

+

+// We need a NULL pointer from time to time

+#ifndef NULL

+ #ifdef __cplusplus

+  #define NULL 0

+ #else

+  #define NULL ((void *)0)

+ #endif

+#endif // NULL

+

+

+// ------------------- BEGIN SYSTEM/COMPILER SPECIFIC --------------------

+

+// Please report any probles that you find with your compiler, which may

+// be solved in this section! There are several compilers that I have not

+// been able to test this file with yet.

+

+// First: If we are we on Windows, we want a single define for it (_WIN32)

+// (Note: For Cygwin the compiler flag -mwin32 should be used, but to

+// make sure that things run smoothly for Cygwin users, we add __CYGWIN__

+// to the list of "valid Win32 identifiers", which removes the need for

+// -mwin32)

+#if !defined(_WIN32) && (defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__))

+ #define _WIN32

+#endif // _WIN32

+

+// In order for extension support to be portable, we need to define an

+// OpenGL function call method. We use the keyword APIENTRY, which is

+// defined for Win32. (Note: Windows also needs this for <GL/gl.h>)

+#ifndef APIENTRY

+ #ifdef _WIN32

+  #define APIENTRY __stdcall

+ #else

+  #define APIENTRY

+ #endif

+ #define GL_APIENTRY_DEFINED

+#endif // APIENTRY

+

+

+// The following three defines are here solely to make some Windows-based

+// <GL/gl.h> files happy. Theoretically we could include <windows.h>, but

+// it has the major drawback of severely polluting our namespace.

+

+// Under Windows, we need WINGDIAPI defined

+#if !defined(WINGDIAPI) && defined(_WIN32)

+ #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__POCC__)

+  // Microsoft Visual C++, Borland C++ Builder and Pelles C

+  #define WINGDIAPI __declspec(dllimport)

+ #elif defined(__LCC__)

+  // LCC-Win32

+  #define WINGDIAPI __stdcall

+ #else

+  // Others (e.g. MinGW, Cygwin)

+  #define WINGDIAPI extern

+ #endif

+ #define GL_WINGDIAPI_DEFINED

+#endif // WINGDIAPI

+

+// Some <GL/glu.h> files also need CALLBACK defined

+#if !defined(CALLBACK) && defined(_WIN32)

+ #if defined(_MSC_VER)

+  // Microsoft Visual C++

+  #if (defined(_M_MRX000) || defined(_M_IX86) || defined(_M_ALPHA) || defined(_M_PPC)) && !defined(MIDL_PASS)

+   #define CALLBACK __stdcall

+  #else

+   #define CALLBACK

+  #endif

+ #else

+  // Other Windows compilers

+  #define CALLBACK __stdcall

+ #endif

+ #define GLU_CALLBACK_DEFINED

+#endif // CALLBACK

+

+// Microsoft Visual C++, Borland C++ and Pelles C <GL/glu.h> needs wchar_t

+#if defined(_WIN32) && (defined(_MSC_VER) || defined(__BORLANDC__) || defined(__POCC__)) && !defined(_WCHAR_T_DEFINED)

+ typedef unsigned short wchar_t;

+ #define _WCHAR_T_DEFINED

+#endif // _WCHAR_T_DEFINED

+

+

+// ---------------- GLFW related system specific defines -----------------

+

+#if defined(_WIN32) && defined(GLFW_BUILD_DLL)

+

+ // We are building a Win32 DLL

+ #define GLFWAPI      __declspec(dllexport)

+ #define GLFWAPIENTRY __stdcall

+ #define GLFWCALL     __stdcall

+

+#elif defined(_WIN32) && defined(GLFW_DLL)

+

+ // We are calling a Win32 DLL

+ #if defined(__LCC__)

+  #define GLFWAPI      extern

+ #else

+  #define GLFWAPI      __declspec(dllimport)

+ #endif

+ #define GLFWAPIENTRY __stdcall

+ #define GLFWCALL     __stdcall

+

+#else

+

+ // We are either building/calling a static lib or we are non-win32

+ #define GLFWAPIENTRY

+ #define GLFWAPI

+ #define GLFWCALL

+

+#endif

+

+// -------------------- END SYSTEM/COMPILER SPECIFIC ---------------------

+

+// Include standard OpenGL headers: GLFW uses GL_FALSE/GL_TRUE, and it is

+// convenient for the user to only have to include <GL/glfw.h>. This also

+// solves the problem with Windows <GL/gl.h> and <GL/glu.h> needing some

+// special defines which normally requires the user to include <windows.h>

+// (which is not a nice solution for portable programs).

+#if defined(__APPLE_CC__)

+ #include <OpenGL/gl.h>

+ #include <OpenGL/glu.h>

+#else

+ #include <GL/gl.h>

+ #include <GL/glu.h>

+#endif

+

+

+//========================================================================

+// GLFW version

+//========================================================================

+

+#define GLFW_VERSION_MAJOR    2

+#define GLFW_VERSION_MINOR    6

+#define GLFW_VERSION_REVISION 0

+

+

+//========================================================================

+// Input handling definitions

+//========================================================================

+

+// Key and button state/action definitions

+#define GLFW_RELEASE            0

+#define GLFW_PRESS              1

+

+// Keyboard key definitions: 8-bit ISO-8859-1 (Latin 1) encoding is used

+// for printable keys (such as A-Z, 0-9 etc), and values above 256

+// represent special (non-printable) keys (e.g. F1, Page Up etc).

+#define GLFW_KEY_UNKNOWN      -1

+#define GLFW_KEY_SPACE        32

+#define GLFW_KEY_SPECIAL      256

+#define GLFW_KEY_ESC          (GLFW_KEY_SPECIAL+1)

+#define GLFW_KEY_F1           (GLFW_KEY_SPECIAL+2)

+#define GLFW_KEY_F2           (GLFW_KEY_SPECIAL+3)

+#define GLFW_KEY_F3           (GLFW_KEY_SPECIAL+4)

+#define GLFW_KEY_F4           (GLFW_KEY_SPECIAL+5)

+#define GLFW_KEY_F5           (GLFW_KEY_SPECIAL+6)

+#define GLFW_KEY_F6           (GLFW_KEY_SPECIAL+7)

+#define GLFW_KEY_F7           (GLFW_KEY_SPECIAL+8)

+#define GLFW_KEY_F8           (GLFW_KEY_SPECIAL+9)

+#define GLFW_KEY_F9           (GLFW_KEY_SPECIAL+10)

+#define GLFW_KEY_F10          (GLFW_KEY_SPECIAL+11)

+#define GLFW_KEY_F11          (GLFW_KEY_SPECIAL+12)

+#define GLFW_KEY_F12          (GLFW_KEY_SPECIAL+13)

+#define GLFW_KEY_F13          (GLFW_KEY_SPECIAL+14)

+#define GLFW_KEY_F14          (GLFW_KEY_SPECIAL+15)

+#define GLFW_KEY_F15          (GLFW_KEY_SPECIAL+16)

+#define GLFW_KEY_F16          (GLFW_KEY_SPECIAL+17)

+#define GLFW_KEY_F17          (GLFW_KEY_SPECIAL+18)

+#define GLFW_KEY_F18          (GLFW_KEY_SPECIAL+19)

+#define GLFW_KEY_F19          (GLFW_KEY_SPECIAL+20)

+#define GLFW_KEY_F20          (GLFW_KEY_SPECIAL+21)

+#define GLFW_KEY_F21          (GLFW_KEY_SPECIAL+22)

+#define GLFW_KEY_F22          (GLFW_KEY_SPECIAL+23)

+#define GLFW_KEY_F23          (GLFW_KEY_SPECIAL+24)

+#define GLFW_KEY_F24          (GLFW_KEY_SPECIAL+25)

+#define GLFW_KEY_F25          (GLFW_KEY_SPECIAL+26)

+#define GLFW_KEY_UP           (GLFW_KEY_SPECIAL+27)

+#define GLFW_KEY_DOWN         (GLFW_KEY_SPECIAL+28)

+#define GLFW_KEY_LEFT         (GLFW_KEY_SPECIAL+29)

+#define GLFW_KEY_RIGHT        (GLFW_KEY_SPECIAL+30)

+#define GLFW_KEY_LSHIFT       (GLFW_KEY_SPECIAL+31)

+#define GLFW_KEY_RSHIFT       (GLFW_KEY_SPECIAL+32)

+#define GLFW_KEY_LCTRL        (GLFW_KEY_SPECIAL+33)

+#define GLFW_KEY_RCTRL        (GLFW_KEY_SPECIAL+34)

+#define GLFW_KEY_LALT         (GLFW_KEY_SPECIAL+35)

+#define GLFW_KEY_RALT         (GLFW_KEY_SPECIAL+36)

+#define GLFW_KEY_TAB          (GLFW_KEY_SPECIAL+37)

+#define GLFW_KEY_ENTER        (GLFW_KEY_SPECIAL+38)

+#define GLFW_KEY_BACKSPACE    (GLFW_KEY_SPECIAL+39)

+#define GLFW_KEY_INSERT       (GLFW_KEY_SPECIAL+40)

+#define GLFW_KEY_DEL          (GLFW_KEY_SPECIAL+41)

+#define GLFW_KEY_PAGEUP       (GLFW_KEY_SPECIAL+42)

+#define GLFW_KEY_PAGEDOWN     (GLFW_KEY_SPECIAL+43)

+#define GLFW_KEY_HOME         (GLFW_KEY_SPECIAL+44)

+#define GLFW_KEY_END          (GLFW_KEY_SPECIAL+45)

+#define GLFW_KEY_KP_0         (GLFW_KEY_SPECIAL+46)

+#define GLFW_KEY_KP_1         (GLFW_KEY_SPECIAL+47)

+#define GLFW_KEY_KP_2         (GLFW_KEY_SPECIAL+48)

+#define GLFW_KEY_KP_3         (GLFW_KEY_SPECIAL+49)

+#define GLFW_KEY_KP_4         (GLFW_KEY_SPECIAL+50)

+#define GLFW_KEY_KP_5         (GLFW_KEY_SPECIAL+51)

+#define GLFW_KEY_KP_6         (GLFW_KEY_SPECIAL+52)

+#define GLFW_KEY_KP_7         (GLFW_KEY_SPECIAL+53)

+#define GLFW_KEY_KP_8         (GLFW_KEY_SPECIAL+54)

+#define GLFW_KEY_KP_9         (GLFW_KEY_SPECIAL+55)

+#define GLFW_KEY_KP_DIVIDE    (GLFW_KEY_SPECIAL+56)

+#define GLFW_KEY_KP_MULTIPLY  (GLFW_KEY_SPECIAL+57)

+#define GLFW_KEY_KP_SUBTRACT  (GLFW_KEY_SPECIAL+58)

+#define GLFW_KEY_KP_ADD       (GLFW_KEY_SPECIAL+59)

+#define GLFW_KEY_KP_DECIMAL   (GLFW_KEY_SPECIAL+60)

+#define GLFW_KEY_KP_EQUAL     (GLFW_KEY_SPECIAL+61)

+#define GLFW_KEY_KP_ENTER     (GLFW_KEY_SPECIAL+62)

+#define GLFW_KEY_LAST         GLFW_KEY_KP_ENTER

+

+// Mouse button definitions

+#define GLFW_MOUSE_BUTTON_1      0

+#define GLFW_MOUSE_BUTTON_2      1

+#define GLFW_MOUSE_BUTTON_3      2

+#define GLFW_MOUSE_BUTTON_4      3

+#define GLFW_MOUSE_BUTTON_5      4

+#define GLFW_MOUSE_BUTTON_6      5

+#define GLFW_MOUSE_BUTTON_7      6

+#define GLFW_MOUSE_BUTTON_8      7

+#define GLFW_MOUSE_BUTTON_LAST   GLFW_MOUSE_BUTTON_8

+

+// Mouse button aliases

+#define GLFW_MOUSE_BUTTON_LEFT   GLFW_MOUSE_BUTTON_1

+#define GLFW_MOUSE_BUTTON_RIGHT  GLFW_MOUSE_BUTTON_2

+#define GLFW_MOUSE_BUTTON_MIDDLE GLFW_MOUSE_BUTTON_3

+

+

+// Joystick identifiers

+#define GLFW_JOYSTICK_1          0

+#define GLFW_JOYSTICK_2          1

+#define GLFW_JOYSTICK_3          2

+#define GLFW_JOYSTICK_4          3

+#define GLFW_JOYSTICK_5          4

+#define GLFW_JOYSTICK_6          5

+#define GLFW_JOYSTICK_7          6

+#define GLFW_JOYSTICK_8          7

+#define GLFW_JOYSTICK_9          8

+#define GLFW_JOYSTICK_10         9

+#define GLFW_JOYSTICK_11         10

+#define GLFW_JOYSTICK_12         11

+#define GLFW_JOYSTICK_13         12

+#define GLFW_JOYSTICK_14         13

+#define GLFW_JOYSTICK_15         14

+#define GLFW_JOYSTICK_16         15

+#define GLFW_JOYSTICK_LAST       GLFW_JOYSTICK_16

+

+

+//========================================================================

+// Other definitions

+//========================================================================

+

+// glfwOpenWindow modes

+#define GLFW_WINDOW               0x00010001

+#define GLFW_FULLSCREEN           0x00010002

+

+// glfwGetWindowParam tokens

+#define GLFW_OPENED               0x00020001

+#define GLFW_ACTIVE               0x00020002

+#define GLFW_ICONIFIED            0x00020003

+#define GLFW_ACCELERATED          0x00020004

+#define GLFW_RED_BITS             0x00020005

+#define GLFW_GREEN_BITS           0x00020006

+#define GLFW_BLUE_BITS            0x00020007

+#define GLFW_ALPHA_BITS           0x00020008

+#define GLFW_DEPTH_BITS           0x00020009

+#define GLFW_STENCIL_BITS         0x0002000A

+

+// The following constants are used for both glfwGetWindowParam

+// and glfwOpenWindowHint

+#define GLFW_REFRESH_RATE         0x0002000B

+#define GLFW_ACCUM_RED_BITS       0x0002000C

+#define GLFW_ACCUM_GREEN_BITS     0x0002000D

+#define GLFW_ACCUM_BLUE_BITS      0x0002000E

+#define GLFW_ACCUM_ALPHA_BITS     0x0002000F

+#define GLFW_AUX_BUFFERS          0x00020010

+#define GLFW_STEREO               0x00020011

+#define GLFW_WINDOW_NO_RESIZE     0x00020012

+#define GLFW_FSAA_SAMPLES         0x00020013

+

+// glfwEnable/glfwDisable tokens

+#define GLFW_MOUSE_CURSOR         0x00030001

+#define GLFW_STICKY_KEYS          0x00030002

+#define GLFW_STICKY_MOUSE_BUTTONS 0x00030003

+#define GLFW_SYSTEM_KEYS          0x00030004

+#define GLFW_KEY_REPEAT           0x00030005

+#define GLFW_AUTO_POLL_EVENTS     0x00030006

+

+// glfwWaitThread wait modes

+#define GLFW_WAIT                 0x00040001

+#define GLFW_NOWAIT               0x00040002

+

+// glfwGetJoystickParam tokens

+#define GLFW_PRESENT              0x00050001

+#define GLFW_AXES                 0x00050002

+#define GLFW_BUTTONS              0x00050003

+

+// glfwReadImage/glfwLoadTexture2D flags

+#define GLFW_NO_RESCALE_BIT       0x00000001 // Only for glfwReadImage

+#define GLFW_ORIGIN_UL_BIT        0x00000002

+#define GLFW_BUILD_MIPMAPS_BIT    0x00000004 // Only for glfwLoadTexture2D

+#define GLFW_ALPHA_MAP_BIT        0x00000008

+

+// Time spans longer than this (seconds) are considered to be infinity

+#define GLFW_INFINITY 100000.0

+

+

+//========================================================================

+// Typedefs

+//========================================================================

+

+// The video mode structure used by glfwGetVideoModes()

+typedef struct {

+    int Width, Height;

+    int RedBits, BlueBits, GreenBits;

+} GLFWvidmode;

+

+// Image/texture information

+typedef struct {

+    int Width, Height;

+    int Format;

+    int BytesPerPixel;

+    unsigned char *Data;

+} GLFWimage;

+

+// Thread ID

+typedef int GLFWthread;

+

+// Mutex object

+typedef void * GLFWmutex;

+

+// Condition variable object

+typedef void * GLFWcond;

+

+// Function pointer types

+typedef void (GLFWCALL * GLFWwindowsizefun)(int,int);

+typedef int  (GLFWCALL * GLFWwindowclosefun)(void);

+typedef void (GLFWCALL * GLFWwindowrefreshfun)(void);

+typedef void (GLFWCALL * GLFWmousebuttonfun)(int,int);

+typedef void (GLFWCALL * GLFWmouseposfun)(int,int);

+typedef void (GLFWCALL * GLFWmousewheelfun)(int);

+typedef void (GLFWCALL * GLFWkeyfun)(int,int);

+typedef void (GLFWCALL * GLFWcharfun)(int,int);

+typedef void (GLFWCALL * GLFWthreadfun)(void *);

+

+

+//========================================================================

+// Prototypes

+//========================================================================

+

+/*! @file glfw.h

+ */

+// GLFW initialization, termination and version querying

+/*! @fn glfwInit

+ */

+GLFWAPI int  GLFWAPIENTRY glfwInit( void );

+GLFWAPI void GLFWAPIENTRY glfwTerminate( void );

+GLFWAPI void GLFWAPIENTRY glfwGetVersion( int *major, int *minor, int *rev );

+

+// Window handling

+GLFWAPI int  GLFWAPIENTRY glfwOpenWindow( int width, int height, int redbits, int greenbits, int bluebits, int alphabits, int depthbits, int stencilbits, int mode );

+GLFWAPI void GLFWAPIENTRY glfwOpenWindowHint( int target, int hint );

+GLFWAPI void GLFWAPIENTRY glfwCloseWindow( void );

+GLFWAPI void GLFWAPIENTRY glfwSetWindowTitle( const char *title );

+GLFWAPI void GLFWAPIENTRY glfwGetWindowSize( int *width, int *height );

+GLFWAPI void GLFWAPIENTRY glfwSetWindowSize( int width, int height );

+GLFWAPI void GLFWAPIENTRY glfwSetWindowPos( int x, int y );

+GLFWAPI void GLFWAPIENTRY glfwIconifyWindow( void );

+GLFWAPI void GLFWAPIENTRY glfwRestoreWindow( void );

+GLFWAPI void GLFWAPIENTRY glfwSwapBuffers( void );

+GLFWAPI void GLFWAPIENTRY glfwSwapInterval( int interval );

+GLFWAPI int  GLFWAPIENTRY glfwGetWindowParam( int param );

+GLFWAPI void GLFWAPIENTRY glfwSetWindowSizeCallback( GLFWwindowsizefun cbfun );

+GLFWAPI void GLFWAPIENTRY glfwSetWindowCloseCallback( GLFWwindowclosefun cbfun );

+GLFWAPI void GLFWAPIENTRY glfwSetWindowRefreshCallback( GLFWwindowrefreshfun cbfun );

+

+// Video mode functions

+GLFWAPI int  GLFWAPIENTRY glfwGetVideoModes( GLFWvidmode *list, int maxcount );

+GLFWAPI void GLFWAPIENTRY glfwGetDesktopMode( GLFWvidmode *mode );

+

+// Input handling

+GLFWAPI void GLFWAPIENTRY glfwPollEvents( void );

+GLFWAPI void GLFWAPIENTRY glfwWaitEvents( void );

+GLFWAPI int  GLFWAPIENTRY glfwGetKey( int key );

+GLFWAPI int  GLFWAPIENTRY glfwGetMouseButton( int button );

+GLFWAPI void GLFWAPIENTRY glfwGetMousePos( int *xpos, int *ypos );

+GLFWAPI void GLFWAPIENTRY glfwSetMousePos( int xpos, int ypos );

+GLFWAPI int  GLFWAPIENTRY glfwGetMouseWheel( void );

+GLFWAPI void GLFWAPIENTRY glfwSetMouseWheel( int pos );

+GLFWAPI void GLFWAPIENTRY glfwSetKeyCallback( GLFWkeyfun cbfun );

+GLFWAPI void GLFWAPIENTRY glfwSetCharCallback( GLFWcharfun cbfun );

+GLFWAPI void GLFWAPIENTRY glfwSetMouseButtonCallback( GLFWmousebuttonfun cbfun );

+GLFWAPI void GLFWAPIENTRY glfwSetMousePosCallback( GLFWmouseposfun cbfun );

+GLFWAPI void GLFWAPIENTRY glfwSetMouseWheelCallback( GLFWmousewheelfun cbfun );

+

+// Joystick input

+GLFWAPI int GLFWAPIENTRY glfwGetJoystickParam( int joy, int param );

+GLFWAPI int GLFWAPIENTRY glfwGetJoystickPos( int joy, float *pos, int numaxes );

+GLFWAPI int GLFWAPIENTRY glfwGetJoystickButtons( int joy, unsigned char *buttons, int numbuttons );

+

+// Time

+GLFWAPI double GLFWAPIENTRY glfwGetTime( void );

+GLFWAPI void   GLFWAPIENTRY glfwSetTime( double time );

+GLFWAPI void   GLFWAPIENTRY glfwSleep( double time );

+

+// Extension support

+GLFWAPI int   GLFWAPIENTRY glfwExtensionSupported( const char *extension );

+GLFWAPI void* GLFWAPIENTRY glfwGetProcAddress( const char *procname );

+GLFWAPI void  GLFWAPIENTRY glfwGetGLVersion( int *major, int *minor, int *rev );

+

+// Threading support

+GLFWAPI GLFWthread GLFWAPIENTRY glfwCreateThread( GLFWthreadfun fun, void *arg );

+GLFWAPI void GLFWAPIENTRY glfwDestroyThread( GLFWthread ID );

+GLFWAPI int  GLFWAPIENTRY glfwWaitThread( GLFWthread ID, int waitmode );

+GLFWAPI GLFWthread GLFWAPIENTRY glfwGetThreadID( void );

+GLFWAPI GLFWmutex GLFWAPIENTRY glfwCreateMutex( void );

+GLFWAPI void GLFWAPIENTRY glfwDestroyMutex( GLFWmutex mutex );

+GLFWAPI void GLFWAPIENTRY glfwLockMutex( GLFWmutex mutex );

+GLFWAPI void GLFWAPIENTRY glfwUnlockMutex( GLFWmutex mutex );

+GLFWAPI GLFWcond GLFWAPIENTRY glfwCreateCond( void );

+GLFWAPI void GLFWAPIENTRY glfwDestroyCond( GLFWcond cond );

+GLFWAPI void GLFWAPIENTRY glfwWaitCond( GLFWcond cond, GLFWmutex mutex, double timeout );

+GLFWAPI void GLFWAPIENTRY glfwSignalCond( GLFWcond cond );

+GLFWAPI void GLFWAPIENTRY glfwBroadcastCond( GLFWcond cond );

+GLFWAPI int  GLFWAPIENTRY glfwGetNumberOfProcessors( void );

+

+// Enable/disable functions

+GLFWAPI void GLFWAPIENTRY glfwEnable( int token );

+GLFWAPI void GLFWAPIENTRY glfwDisable( int token );

+

+// Image/texture I/O support

+GLFWAPI int  GLFWAPIENTRY glfwReadImage( const char *name, GLFWimage *img, int flags );

+GLFWAPI int  GLFWAPIENTRY glfwReadMemoryImage( const void *data, long size, GLFWimage *img, int flags );

+GLFWAPI void GLFWAPIENTRY glfwFreeImage( GLFWimage *img );

+GLFWAPI int  GLFWAPIENTRY glfwLoadTexture2D( const char *name, int flags );

+GLFWAPI int  GLFWAPIENTRY glfwLoadMemoryTexture2D( const void *data, long size, int flags );

+GLFWAPI int  GLFWAPIENTRY glfwLoadTextureImage2D( GLFWimage *img, int flags );

+

+

+#ifdef __cplusplus

+}

+#endif

+

+#endif // __glfw_h_

diff --git a/src/engine/external/glfw/lib/enable.c b/src/engine/external/glfw/lib/enable.c
new file mode 100644
index 00000000..6231a1f9
--- /dev/null
+++ b/src/engine/external/glfw/lib/enable.c
@@ -0,0 +1,295 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        enable.c

+// Platform:    Any

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

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

+//****                  GLFW internal functions                       ****

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

+

+//========================================================================

+// Enable (show) mouse cursor

+//========================================================================

+

+static void _glfwEnableMouseCursor( void )

+{

+    int CenterPosX, CenterPosY;

+

+    if( !_glfwWin.Opened || !_glfwWin.MouseLock )

+    {

+        return;

+    }

+

+    // Show mouse cursor

+    _glfwPlatformShowMouseCursor();

+

+    CenterPosX = _glfwWin.Width / 2;

+    CenterPosY = _glfwWin.Height / 2;

+

+    if( CenterPosX != _glfwInput.MousePosX || CenterPosY != _glfwInput.MousePosY )

+    {

+	_glfwPlatformSetMouseCursorPos( CenterPosX, CenterPosY );

+

+	_glfwInput.MousePosX = CenterPosX;

+	_glfwInput.MousePosY = CenterPosY;

+

+	if( _glfwWin.MousePosCallback )

+	{

+	    _glfwWin.MousePosCallback( _glfwInput.MousePosX, 

+				       _glfwInput.MousePosY );

+	}

+    }

+

+    // From now on the mouse is unlocked

+    _glfwWin.MouseLock = GL_FALSE;

+}

+

+//========================================================================

+// Disable (hide) mouse cursor

+//========================================================================

+

+static void _glfwDisableMouseCursor( void )

+{

+    if( !_glfwWin.Opened || _glfwWin.MouseLock )

+    {

+        return;

+    }

+

+    // Hide mouse cursor

+    _glfwPlatformHideMouseCursor();

+

+    // Move cursor to the middle of the window

+    _glfwPlatformSetMouseCursorPos( _glfwWin.Width>>1,

+                                    _glfwWin.Height>>1 );

+

+    // From now on the mouse is locked

+    _glfwWin.MouseLock = GL_TRUE;

+}

+

+

+//========================================================================

+// _glfwEnableStickyKeys() - Enable sticky keys

+// _glfwDisableStickyKeys() - Disable sticky keys

+//========================================================================

+

+static void _glfwEnableStickyKeys( void )

+{

+    _glfwInput.StickyKeys = 1;

+}

+

+static void _glfwDisableStickyKeys( void )

+{

+    int i;

+

+    _glfwInput.StickyKeys = 0;

+

+    // Release all sticky keys

+    for( i = 0; i <= GLFW_KEY_LAST; i ++ )

+    {

+        if( _glfwInput.Key[ i ] == 2 )

+        {

+            _glfwInput.Key[ i ] = 0;

+        }

+    }

+}

+

+

+//========================================================================

+// _glfwEnableStickyMouseButtons() - Enable sticky mouse buttons

+// _glfwDisableStickyMouseButtons() - Disable sticky mouse buttons

+//========================================================================

+

+static void _glfwEnableStickyMouseButtons( void )

+{

+    _glfwInput.StickyMouseButtons = 1;

+}

+

+static void _glfwDisableStickyMouseButtons( void )

+{

+    int i;

+

+    _glfwInput.StickyMouseButtons = 0;

+

+    // Release all sticky mouse buttons

+    for( i = 0; i <= GLFW_MOUSE_BUTTON_LAST; i ++ )

+    {

+        if( _glfwInput.MouseButton[ i ] == 2 )

+        {

+            _glfwInput.MouseButton[ i ] = 0;

+        }

+    }

+}

+

+

+//========================================================================

+// _glfwEnableSystemKeys() - Enable system keys

+// _glfwDisableSystemKeys() - Disable system keys

+//========================================================================

+

+static void _glfwEnableSystemKeys( void )

+{

+    if( !_glfwWin.SysKeysDisabled )

+    {

+        return;

+    }

+

+    _glfwPlatformEnableSystemKeys();

+

+    // Indicate that system keys are no longer disabled

+    _glfwWin.SysKeysDisabled = GL_FALSE;

+}

+

+static void _glfwDisableSystemKeys( void )

+{

+    if( _glfwWin.SysKeysDisabled )

+    {

+        return;

+    }

+

+    _glfwPlatformDisableSystemKeys();

+

+    // Indicate that system keys are now disabled

+    _glfwWin.SysKeysDisabled = GL_TRUE;

+}

+

+

+//========================================================================

+// _glfwEnableKeyRepeat() - Enable key repeat

+// _glfwDisableKeyRepeat() - Disable key repeat

+//========================================================================

+

+static void _glfwEnableKeyRepeat( void )

+{

+    _glfwInput.KeyRepeat = 1;

+}

+

+static void _glfwDisableKeyRepeat( void )

+{

+    _glfwInput.KeyRepeat = 0;

+}

+

+

+//========================================================================

+// _glfwEnableAutoPollEvents() - Enable automatic event polling

+// _glfwDisableAutoPollEvents() - Disable automatic event polling

+//========================================================================

+

+static void _glfwEnableAutoPollEvents( void )

+{

+    _glfwWin.AutoPollEvents = 1;

+}

+

+static void _glfwDisableAutoPollEvents( void )

+{

+    _glfwWin.AutoPollEvents = 0;

+}

+

+

+

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

+//****                    GLFW user functions                         ****

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

+

+//========================================================================

+// glfwEnable() - Enable certain GLFW/window/system functions.

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwEnable( int token )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized )

+    {

+        return;

+    }

+

+    switch( token )

+    {

+    case GLFW_MOUSE_CURSOR:

+        _glfwEnableMouseCursor();

+        break;

+    case GLFW_STICKY_KEYS:

+        _glfwEnableStickyKeys();

+        break;

+    case GLFW_STICKY_MOUSE_BUTTONS:

+        _glfwEnableStickyMouseButtons();

+        break;

+    case GLFW_SYSTEM_KEYS:

+        _glfwEnableSystemKeys();

+        break;

+    case GLFW_KEY_REPEAT:

+        _glfwEnableKeyRepeat();

+        break;

+    case GLFW_AUTO_POLL_EVENTS:

+        _glfwEnableAutoPollEvents();

+        break;

+    default:

+        break;

+    }

+}

+

+

+//========================================================================

+// glfwDisable() - Disable certain GLFW/window/system functions.

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwDisable( int token )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized )

+    {

+        return;

+    }

+

+    switch( token )

+    {

+    case GLFW_MOUSE_CURSOR:

+        _glfwDisableMouseCursor();

+        break;

+    case GLFW_STICKY_KEYS:

+        _glfwDisableStickyKeys();

+        break;

+    case GLFW_STICKY_MOUSE_BUTTONS:

+        _glfwDisableStickyMouseButtons();

+        break;

+    case GLFW_SYSTEM_KEYS:

+        _glfwDisableSystemKeys();

+        break;

+    case GLFW_KEY_REPEAT:

+        _glfwDisableKeyRepeat();

+        break;

+    case GLFW_AUTO_POLL_EVENTS:

+        _glfwDisableAutoPollEvents();

+        break;

+    default:

+        break;

+    }

+}

+

diff --git a/src/engine/external/glfw/lib/fullscreen.c b/src/engine/external/glfw/lib/fullscreen.c
new file mode 100644
index 00000000..e9f09cc6
--- /dev/null
+++ b/src/engine/external/glfw/lib/fullscreen.c
@@ -0,0 +1,95 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        fullscreen.c

+// Platform:    Any

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

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

+//****                    GLFW user functions                         ****

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

+

+//========================================================================

+// glfwGetVideoModes() - Get a list of available video modes

+//========================================================================

+

+GLFWAPI int GLFWAPIENTRY glfwGetVideoModes( GLFWvidmode *list,

+    int maxcount )

+{

+    int         count, i, swap, res1, res2, depth1, depth2;

+    GLFWvidmode vm;

+

+    if( !_glfwInitialized || maxcount <= 0 || list == (GLFWvidmode*) 0 )

+    {

+        return 0;

+    }

+

+    // Get list of video modes

+    count = _glfwPlatformGetVideoModes( list, maxcount );

+

+    // Sort list (bubble sort)

+    do

+    {

+        swap = 0;

+        for( i = 0; i < count-1; ++ i )

+        {

+            res1   = list[i].Width*list[i].Height;

+            depth1 = list[i].RedBits+list[i].GreenBits+list[i].BlueBits;

+            res2   = list[i+1].Width*list[i+1].Height;

+            depth2 = list[i+1].RedBits+list[i+1].GreenBits+

+                     list[i+1].BlueBits;

+            if( (depth2<depth1) || ((depth2==depth1) && (res2<res1)) )

+            {

+                vm = list[i];

+                list[i] = list[i+1];

+                list[i+1] = vm;

+                swap = 1;

+            }

+        }

+    }

+    while( swap );

+

+    return count;

+}

+

+

+//========================================================================

+// glfwGetDesktopMode() - Get the desktop video mode

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwGetDesktopMode( GLFWvidmode *mode )

+{

+    if( !_glfwInitialized || mode == (GLFWvidmode*) 0 )

+    {

+        return;

+    }

+

+    _glfwPlatformGetDesktopMode( mode );

+}

+

diff --git a/src/engine/external/glfw/lib/glext.c b/src/engine/external/glfw/lib/glext.c
new file mode 100644
index 00000000..fda56fa2
--- /dev/null
+++ b/src/engine/external/glfw/lib/glext.c
@@ -0,0 +1,201 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        glext.c

+// Platform:    Any

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

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

+//****                  GLFW internal functions                       ****

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

+

+//========================================================================

+// _glfwStringInExtensionString() - Check if a string can be found in an

+// OpenGL extension string

+//========================================================================

+

+int _glfwStringInExtensionString( const char *string,

+    const GLubyte *extensions )

+{

+    const GLubyte *start;

+    GLubyte *where, *terminator;

+

+    // It takes a bit of care to be fool-proof about parsing the

+    // OpenGL extensions string. Don't be fooled by sub-strings,

+    // etc.

+    start = extensions;

+    while( 1 )

+    {

+        where = (GLubyte *) strstr( (const char *) start, string );

+        if( !where )

+        {

+            return GL_FALSE;

+        }

+        terminator = where + strlen( string );

+        if( where == start || *(where - 1) == ' ' )

+        {

+            if( *terminator == ' ' || *terminator == '\0' )

+            {

+                break;

+            }

+        }

+        start = terminator;

+    }

+

+    return GL_TRUE;

+}

+

+

+

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

+//****                    GLFW user functions                         ****

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

+

+//========================================================================

+// glfwExtensionSupported() - Check if an OpenGL extension is available

+// at runtime

+//========================================================================

+

+GLFWAPI int GLFWAPIENTRY glfwExtensionSupported( const char *extension )

+{

+    const GLubyte *extensions;

+    GLubyte       *where;

+

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return GL_FALSE;

+    }

+

+    // Extension names should not have spaces

+    where = (GLubyte *) strchr( extension, ' ' );

+    if( where || *extension == '\0' )

+    {

+        return GL_FALSE;

+    }

+

+    // Check if extension is in the standard OpenGL extensions string

+    extensions = (GLubyte *) glGetString( GL_EXTENSIONS );

+    if( extensions != NULL )

+    {

+        if( _glfwStringInExtensionString( extension, extensions ) )

+        {

+            return GL_TRUE;

+        }

+    }

+

+    // Additional platform specific extension checking (e.g. WGL)

+    if( _glfwPlatformExtensionSupported( extension ) )

+    {

+        return GL_TRUE;

+    }

+

+    return GL_FALSE;

+}

+

+

+//========================================================================

+// glfwGetProcAddress() - Get the function pointer to an OpenGL function.

+// This function can be used to get access to extended OpenGL functions.

+//========================================================================

+

+GLFWAPI void * GLFWAPIENTRY glfwGetProcAddress( const char *procname )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return NULL;

+    }

+

+    return _glfwPlatformGetProcAddress( procname );

+}

+

+

+//========================================================================

+// glfwGetGLVersion() - Get OpenGL version

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwGetGLVersion( int *major, int *minor,

+    int *rev )

+{

+    GLuint _major, _minor = 0, _rev = 0;

+    const GLubyte *version;

+    GLubyte *ptr;

+

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return;

+    }

+

+    // Get OpenGL version string

+    version = glGetString( GL_VERSION );

+    if( !version )

+    {

+        return;

+    }

+

+    // Parse string

+    ptr = (GLubyte*) version;

+    for( _major = 0; *ptr >= '0' && *ptr <= '9'; ptr ++ )

+    {

+        _major = 10*_major + (*ptr - '0');

+    }

+    if( *ptr == '.' )

+    {

+        ptr ++;

+        for( _minor = 0; *ptr >= '0' && *ptr <= '9'; ptr ++ )

+        {

+            _minor = 10*_minor + (*ptr - '0');

+        }

+        if( *ptr == '.' )

+        {

+            ptr ++;

+            for( _rev = 0; *ptr >= '0' && *ptr <= '9'; ptr ++ )

+            {

+                _rev = 10*_rev + (*ptr - '0');

+            }

+        }

+    }

+

+    // Return parsed values

+    if( major != NULL )

+    {

+        *major = _major;

+    }

+    if( minor != NULL )

+    {

+        *minor = _minor;

+    }

+    if( rev != NULL )

+    {

+        *rev = _rev;

+    }

+}

+

diff --git a/src/engine/external/glfw/lib/image.c b/src/engine/external/glfw/lib/image.c
new file mode 100644
index 00000000..3caa1518
--- /dev/null
+++ b/src/engine/external/glfw/lib/image.c
@@ -0,0 +1,629 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        image.c

+// Platform:    Any

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+//========================================================================

+// Description:

+//

+// This module acts as an interface for different image file formats (the

+// image file format is detected automatically).

+//

+// By default the loaded image is rescaled (using bilinear interpolation)

+// to the next higher 2^N x 2^M resolution, unless it has a valid

+// 2^N x 2^M resolution. The interpolation is quite slow, even if the

+// routine has been optimized for speed (a 200x200 RGB image is scaled to

+// 256x256 in ~30 ms on a P3-500).

+//

+// Paletted images are converted to RGB/RGBA images.

+//

+// A convenience function is also included (glfwLoadTexture2D), which

+// loads a texture image from a file directly to OpenGL texture memory,

+// with an option to generate all mipmap levels. GL_SGIS_generate_mipmap

+// is used whenever available, which should give an optimal mipmap

+// generation speed (possibly performed in hardware). A software fallback

+// method is included when GL_SGIS_generate_mipmap is not supported (it

+// generates all mipmaps of a 256x256 RGB texture in ~3 ms on a P3-500).

+//

+//========================================================================

+

+

+#include "internal.h"

+

+

+// We want to support automatic mipmap generation

+#ifndef GL_SGIS_generate_mipmap

+ #define GL_GENERATE_MIPMAP_SGIS       0x8191

+ #define GL_GENERATE_MIPMAP_HINT_SGIS  0x8192

+ #define GL_SGIS_generate_mipmap    1

+#endif // GL_SGIS_generate_mipmap

+

+

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

+//****                  GLFW internal functions                       ****

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

+

+//========================================================================

+// _glfwUpsampleImage() - Upsample image, from size w1 x h1 to w2 x h2

+//========================================================================

+

+static void _glfwUpsampleImage( unsigned char *src, unsigned char *dst,

+    int w1, int h1, int w2, int h2, int bpp )

+{

+    int m, n, k, x, y, col8;

+    float dx, dy, xstep, ystep, col, col1, col2;

+    unsigned char *src1, *src2, *src3, *src4;

+

+    // Calculate scaling factor

+    xstep = (float)(w1-1) / (float)(w2-1);

+    ystep = (float)(h1-1) / (float)(h2-1);

+

+    // Copy source data to destination data with bilinear interpolation

+    // Note: The rather strange look of this routine is a direct result of

+    // my attempts at optimizing it. Improvements are welcome!

+    dy = 0.0f;

+    y = 0;

+    for( n = 0; n < h2; n ++ )

+    {

+        dx = 0.0f;

+        src1 = &src[ y*w1*bpp ];

+        src3 = y < (h1-1) ? src1 + w1*bpp : src1;

+        src2 = src1 + bpp;

+        src4 = src3 + bpp;

+        x = 0;

+        for( m = 0; m < w2; m ++ )

+        {

+            for( k = 0; k < bpp; k ++ )

+            {

+                col1 = *src1 ++;

+                col2 = *src2 ++;

+                col = col1 + (col2 - col1) * dx;

+                col1 = *src3 ++;

+                col2 = *src4 ++;

+                col2 = col1 + (col2 - col1) * dx;

+                col += (col2 - col) * dy;

+                col8 = (int) (col + 0.5);

+                if( col8 >= 256 ) col8 = 255;

+                *dst++ = (unsigned char) col8;

+            }

+            dx += xstep;

+            if( dx >= 1.0f )

+            {

+                x ++;

+                dx -= 1.0f;

+                if( x >= (w1-1) )

+                {

+                    src2 = src1;

+                    src4 = src3;

+                }

+            }

+            else

+            {

+                src1 -= bpp;

+                src2 -= bpp;

+                src3 -= bpp;

+                src4 -= bpp;

+            }

+        }

+        dy += ystep;

+        if( dy >= 1.0f )

+        {

+            y ++;

+            dy -= 1.0f;

+        }

+    }

+}

+

+

+//========================================================================

+// _glfwHalveImage() - Build the next mip-map level

+//========================================================================

+

+static int _glfwHalveImage( GLubyte *src, int *width, int *height,

+    int components )

+{

+    int     halfwidth, halfheight, m, n, k, idx1, idx2;

+    GLubyte *dst;

+

+    // Last level?

+    if( *width <= 1 && *height <= 1 )

+    {

+        return GL_FALSE;

+    }

+

+    // Calculate new width and height (handle 1D case)

+    halfwidth  = *width > 1 ? *width / 2 : 1;

+    halfheight = *height > 1 ? *height / 2 : 1;

+

+    // Downsample image with a simple box-filter

+    dst = src;

+    if( *width == 1 || *height == 1 )

+    {

+        // 1D case

+        for( m = 0; m < halfwidth+halfheight-1; m ++ )

+        {

+            for( k = 0; k < components; k ++ )

+            {

+                *dst ++ = (GLubyte) (((int)*src +

+                                      (int)src[components] + 1) >> 1);

+                src ++;

+            }

+            src += components;

+        }

+    }

+    else

+    {

+        // 2D case

+        idx1 = *width*components;

+        idx2 = (*width+1)*components;

+        for( m = 0; m < halfheight; m ++ )

+        {

+            for( n = 0; n < halfwidth; n ++ )

+            {

+                for( k = 0; k < components; k ++ )

+                {

+                    *dst ++ = (GLubyte) (((int)*src +

+                                          (int)src[components] +

+                                          (int)src[idx1] +

+                                          (int)src[idx2] + 2) >> 2);

+                    src ++;

+                }

+                src += components;

+            }

+            src += components * (*width);

+        }

+    }

+

+    // Return new width and height

+    *width = halfwidth;

+    *height = halfheight;

+

+    return GL_TRUE;

+}

+

+

+//========================================================================

+// _glfwRescaleImage() - Rescales an image into power-of-two dimensions

+//========================================================================

+

+static int _glfwRescaleImage( GLFWimage* image )

+{

+    int     width, height, log2, newsize;

+    unsigned char *data;

+

+    // Calculate next larger 2^N width

+    for( log2 = 0, width = image->Width; width > 1; width >>= 1, log2 ++ )

+      ;

+    width  = (int) 1 << log2;

+    if( width < image->Width )

+    {

+	width <<= 1;

+    }

+

+    // Calculate next larger 2^M height

+    for( log2 = 0, height = image->Height; height > 1; height >>= 1, log2 ++ )

+      ;

+    height = (int) 1 << log2;

+    if( height < image->Height )

+    {

+	height <<= 1;

+    }

+

+    // Do we really need to rescale?

+    if( width != image->Width || height != image->Height )

+    {

+        // Allocate memory for new (upsampled) image data

+        newsize = width * height * image->BytesPerPixel;

+        data = (unsigned char *) malloc( newsize );

+        if( data == NULL )

+        {

+            free( image->Data );

+            return GL_FALSE;

+        }

+

+        // Copy old image data to new image data with interpolation

+        _glfwUpsampleImage( image->Data, data, image->Width, image->Height,

+                            width, height, image->BytesPerPixel );

+

+        // Free memory for old image data (not needed anymore)

+        free( image->Data );

+

+        // Set pointer to new image data, and set new image dimensions

+        image->Data   = data;

+        image->Width  = width;

+        image->Height = height;

+    }

+

+    return GL_TRUE;

+}

+

+

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

+//****                    GLFW user functions                         ****

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

+

+//========================================================================

+// glfwReadImage() - Read an image from a named file

+//========================================================================

+

+GLFWAPI int GLFWAPIENTRY glfwReadImage( const char *name, GLFWimage *img,

+    int flags )

+{

+    _GLFWstream stream;

+

+    // Is GLFW initialized?

+    if( !_glfwInitialized )

+    {

+        return GL_FALSE;

+    }

+

+    // Start with an empty image descriptor

+    img->Width         = 0;

+    img->Height        = 0;

+    img->BytesPerPixel = 0;

+    img->Data          = NULL;

+

+    // Open file

+    if( !_glfwOpenFileStream( &stream, name, "rb" ) )

+    {

+        return GL_FALSE;

+    }

+

+    // We only support TGA files at the moment

+    if( !_glfwReadTGA( &stream, img, flags ) )

+    {

+	_glfwCloseStream( &stream );

+        return GL_FALSE;

+    }

+

+    // Close stream

+    _glfwCloseStream( &stream );

+

+    // Should we rescale the image to closest 2^N x 2^M resolution?

+    if( !(flags & GLFW_NO_RESCALE_BIT) )

+    {

+	if( !_glfwRescaleImage( img ) )

+	{

+	    return GL_FALSE;

+	}

+    }

+

+    // Interpret BytesPerPixel as an OpenGL format

+    switch( img->BytesPerPixel )

+    {

+        default:

+        case 1:

+            if( flags & GLFW_ALPHA_MAP_BIT )

+            {

+                img->Format = GL_ALPHA;

+            }

+            else

+            {

+                img->Format = GL_LUMINANCE;

+            }

+            break;

+        case 3:

+            img->Format = GL_RGB;

+            break;

+        case 4:

+            img->Format = GL_RGBA;

+            break;

+    }

+

+    return GL_TRUE;

+}

+

+

+//========================================================================

+// glfwReadMemoryImage() - Read an image file from a memory buffer

+//========================================================================

+

+GLFWAPI int  GLFWAPIENTRY glfwReadMemoryImage( const void *data, long size, GLFWimage *img, int flags )

+{

+    _GLFWstream stream;

+

+    // Is GLFW initialized?

+    if( !_glfwInitialized )

+    {

+        return GL_FALSE;

+    }

+

+    // Start with an empty image descriptor

+    img->Width         = 0;

+    img->Height        = 0;

+    img->BytesPerPixel = 0;

+    img->Data          = NULL;

+

+    // Open buffer

+    if( !_glfwOpenBufferStream( &stream, (void*) data, size ) )

+    {

+        return GL_FALSE;

+    }

+

+    // We only support TGA files at the moment

+    if( !_glfwReadTGA( &stream, img, flags ) )

+    {

+	_glfwCloseStream( &stream );

+        return GL_FALSE;

+    }

+

+    // Close stream

+    _glfwCloseStream( &stream );

+

+    // Should we rescale the image to closest 2^N x 2^M resolution?

+    if( !(flags & GLFW_NO_RESCALE_BIT) )

+    {

+	if( !_glfwRescaleImage( img ) )

+	{

+	    return GL_FALSE;

+	}

+    }

+

+    // Interpret BytesPerPixel as an OpenGL format

+    switch( img->BytesPerPixel )

+    {

+        default:

+        case 1:

+            if( flags & GLFW_ALPHA_MAP_BIT )

+            {

+                img->Format = GL_ALPHA;

+            }

+            else

+            {

+                img->Format = GL_LUMINANCE;

+            }

+            break;

+        case 3:

+            img->Format = GL_RGB;

+            break;

+        case 4:

+            img->Format = GL_RGBA;

+            break;

+    }

+

+    return GL_TRUE;

+}

+

+

+//========================================================================

+// glfwFreeImage() - Free allocated memory for an image

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwFreeImage( GLFWimage *img )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized )

+    {

+        return;

+    }

+

+    // Free memory

+    if( img->Data != NULL )

+    {

+        free( img->Data );

+        img->Data = NULL;

+    }

+

+    // Clear all fields

+    img->Width         = 0;

+    img->Height        = 0;

+    img->Format        = 0;

+    img->BytesPerPixel = 0;

+}

+

+

+//========================================================================

+// glfwLoadTexture2D() - Read an image from a file, and upload it to

+// texture memory

+//========================================================================

+

+GLFWAPI int GLFWAPIENTRY glfwLoadTexture2D( const char *name, int flags )

+{

+    GLFWimage img;

+

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return GL_FALSE;

+    }

+

+    // Force rescaling if necessary

+    if( !_glfwWin.Has_GL_ARB_texture_non_power_of_two )

+    {

+      flags &= (~GLFW_NO_RESCALE_BIT);

+    }

+

+    // Read image from file

+    if( !glfwReadImage( name, &img, flags ) )

+    {

+        return GL_FALSE;

+    }

+

+    if( !glfwLoadTextureImage2D( &img, flags ) )

+    {

+	return GL_FALSE;

+    }

+

+    // Data buffer is not needed anymore

+    glfwFreeImage( &img );

+

+    return GL_TRUE;

+}

+

+

+//========================================================================

+// glfwLoadMemoryTexture2D() - Read an image from a buffer, and upload it to

+// texture memory

+//========================================================================

+

+GLFWAPI int  GLFWAPIENTRY glfwLoadMemoryTexture2D( const void *data, long size, int flags )

+{

+    GLFWimage img;

+

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return GL_FALSE;

+    }

+

+    // Force rescaling if necessary

+    if( !_glfwWin.Has_GL_ARB_texture_non_power_of_two )

+    {

+      flags &= (~GLFW_NO_RESCALE_BIT);

+    }

+

+    // Read image from file

+    if( !glfwReadMemoryImage( data, size, &img, flags ) )

+    {

+        return GL_FALSE;

+    }

+

+    if( !glfwLoadTextureImage2D( &img, flags ) )

+    {

+	return GL_FALSE;

+    }

+

+    // Data buffer is not needed anymore

+    glfwFreeImage( &img );

+

+    return GL_TRUE;

+}

+

+

+//========================================================================

+// glfwLoadTextureImage2D() - Upload an image object to texture memory

+//========================================================================

+

+GLFWAPI int  GLFWAPIENTRY glfwLoadTextureImage2D( GLFWimage *img, int flags )

+{

+    GLint   UnpackAlignment, GenMipMap;

+    int     level, format, AutoGen, newsize, n;

+    unsigned char *data, *dataptr;

+

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return GL_FALSE;

+    }

+

+    // TODO: Use GL_MAX_TEXTURE_SIZE or GL_PROXY_TEXTURE_2D to determine

+    //       whether the image size is valid.

+    // NOTE: May require box filter downsampling routine.

+

+    // Do we need to convert the alpha map to RGBA format (OpenGL 1.0)?

+    if( (_glfwWin.GLVerMajor == 1) && (_glfwWin.GLVerMinor == 0) &&

+        (img->Format == GL_ALPHA) )

+    {

+        // We go to RGBA representation instead

+        img->BytesPerPixel = 4;

+

+        // Allocate memory for new RGBA image data

+        newsize = img->Width * img->Height * img->BytesPerPixel;

+        data = (unsigned char *) malloc( newsize );

+        if( data == NULL )

+        {

+            free( img->Data );

+            return GL_FALSE;

+        }

+

+        // Convert Alpha map to RGBA

+        dataptr = data;

+        for( n = 0; n < (img->Width*img->Height); ++ n )

+        {

+            *dataptr ++ = 255;

+            *dataptr ++ = 255;

+            *dataptr ++ = 255;

+            *dataptr ++ = img->Data[n];

+        }

+

+        // Free memory for old image data (not needed anymore)

+        free( img->Data );

+

+        // Set pointer to new image data

+        img->Data = data;

+    }

+

+    // Set unpack alignment to one byte

+    glGetIntegerv( GL_UNPACK_ALIGNMENT, &UnpackAlignment );

+    glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );

+

+    // Should we use automatic mipmap generation?

+    AutoGen = ( flags & GLFW_BUILD_MIPMAPS_BIT ) &&

+              _glfwWin.Has_GL_SGIS_generate_mipmap;

+

+    // Enable automatic mipmap generation

+    if( AutoGen )

+    {

+        glGetTexParameteriv( GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,

+            &GenMipMap );

+        glTexParameteri( GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,

+            GL_TRUE );

+    }

+

+    // Format specification is different for OpenGL 1.0

+    if( _glfwWin.GLVerMajor == 1 && _glfwWin.GLVerMinor == 0 )

+    {

+        format = img->BytesPerPixel;

+    }

+    else

+    {

+        format = img->Format;

+    }

+

+    // Upload to texture memeory

+    level = 0;

+    do

+    {

+        // Upload this mipmap level

+        glTexImage2D( GL_TEXTURE_2D, level, format,

+            img->Width, img->Height, 0, format,

+            GL_UNSIGNED_BYTE, (void*) img->Data );

+

+        // Build next mipmap level manually, if required

+        if( ( flags & GLFW_BUILD_MIPMAPS_BIT ) && !AutoGen )

+        {

+            level = _glfwHalveImage( img->Data, &img->Width,

+                        &img->Height, img->BytesPerPixel ) ?

+                    level + 1 : 0;

+        }

+    }

+    while( level != 0 );

+

+    // Restore old automatic mipmap generation state

+    if( AutoGen )

+    {

+        glTexParameteri( GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,

+            GenMipMap );

+    }

+

+    // Restore old unpack alignment

+    glPixelStorei( GL_UNPACK_ALIGNMENT, UnpackAlignment );

+

+    return GL_TRUE;

+}

+

diff --git a/src/engine/external/glfw/lib/init.c b/src/engine/external/glfw/lib/init.c
new file mode 100644
index 00000000..6d149d84
--- /dev/null
+++ b/src/engine/external/glfw/lib/init.c
@@ -0,0 +1,108 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        init.c

+// Platform:    Any

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#define _init_c_

+#include "internal.h"

+

+

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

+//****                    GLFW user functions                         ****

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

+

+//========================================================================

+// glfwInit() - Initialize various GLFW state

+//========================================================================

+

+GLFWAPI int GLFWAPIENTRY glfwInit( void )

+{

+    // Is GLFW already initialized?

+    if( _glfwInitialized )

+    {

+        return GL_TRUE;

+    }

+

+    // Window is not yet opened

+    _glfwWin.Opened = GL_FALSE;

+

+    // Default enable/disable settings

+    _glfwWin.SysKeysDisabled = GL_FALSE;

+

+    // Clear window hints

+    _glfwClearWindowHints();

+

+    // Platform specific initialization

+    if( !_glfwPlatformInit() )

+    {

+        return GL_FALSE;

+    }

+

+    // Form now on, GLFW state is valid

+    _glfwInitialized = GL_TRUE;

+

+    return GL_TRUE;

+}

+

+

+

+//========================================================================

+// glfwTerminate() - Close window and kill all threads.

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwTerminate( void )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized )

+    {

+        return;

+    }

+

+    // Platform specific termination

+    if( !_glfwPlatformTerminate() )

+    {

+        return;

+    }

+

+    // GLFW is no longer initialized

+    _glfwInitialized = GL_FALSE;

+}

+

+

+//========================================================================

+// glfwGetVersion() - Get GLFW version

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwGetVersion( int *major, int *minor,

+    int *rev )

+{

+    if( major != NULL ) *major = GLFW_VERSION_MAJOR;

+    if( minor != NULL ) *minor = GLFW_VERSION_MINOR;

+    if( rev   != NULL ) *rev   = GLFW_VERSION_REVISION;

+}

+

diff --git a/src/engine/external/glfw/lib/input.c b/src/engine/external/glfw/lib/input.c
new file mode 100644
index 00000000..e944706b
--- /dev/null
+++ b/src/engine/external/glfw/lib/input.c
@@ -0,0 +1,280 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        input.c

+// Platform:    Any

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

+//========================================================================

+// glfwGetKey()

+//========================================================================

+

+GLFWAPI int GLFWAPIENTRY glfwGetKey( int key )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return GLFW_RELEASE;

+    }

+

+    // Is it a valid key?

+    if( key < 0 || key > GLFW_KEY_LAST )

+    {

+        return GLFW_RELEASE;

+    }

+

+    if( _glfwInput.Key[ key ] == GLFW_STICK )

+    {

+        // Sticky mode: release key now

+        _glfwInput.Key[ key ] = GLFW_RELEASE;

+        return GLFW_PRESS;

+    }

+

+    return (int) _glfwInput.Key[ key ];

+}

+

+

+//========================================================================

+// glfwGetMouseButton()

+//========================================================================

+

+GLFWAPI int GLFWAPIENTRY glfwGetMouseButton( int button )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return GLFW_RELEASE;

+    }

+

+    // Is it a valid mouse button?

+    if( button < 0 || button > GLFW_MOUSE_BUTTON_LAST )

+    {

+        return GLFW_RELEASE;

+    }

+

+    if( _glfwInput.MouseButton[ button ] == GLFW_STICK )

+    {

+        // Sticky mode: release mouse button now

+        _glfwInput.MouseButton[ button ] = GLFW_RELEASE;

+        return GLFW_PRESS;

+    }

+

+    return (int) _glfwInput.MouseButton[ button ];

+}

+

+

+//========================================================================

+// glfwGetMousePos()

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwGetMousePos( int *xpos, int *ypos )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return;

+    }

+

+    // Return mouse position

+    if( xpos != NULL )

+    {

+        *xpos = _glfwInput.MousePosX;

+    }

+    if( ypos != NULL )

+    {

+        *ypos = _glfwInput.MousePosY;

+    }

+}

+

+

+//========================================================================

+// glfwSetMousePos()

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwSetMousePos( int xpos, int ypos )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return;

+    }

+

+    // Don't do anything if the mouse position did not change

+    if( xpos == _glfwInput.MousePosX && ypos == _glfwInput.MousePosY )

+    {

+        return;

+    }

+

+    // Set GLFW mouse position

+    _glfwInput.MousePosX = xpos;

+    _glfwInput.MousePosY = ypos;

+

+    // If we have a locked mouse, do not change cursor position

+    if( _glfwWin.MouseLock )

+    {

+        return;

+    }

+

+    // Update physical cursor position

+    _glfwPlatformSetMouseCursorPos( xpos, ypos );

+}

+

+

+//========================================================================

+// glfwGetMouseWheel()

+//========================================================================

+

+GLFWAPI int GLFWAPIENTRY glfwGetMouseWheel( void )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return 0;

+    }

+

+    // Return mouse wheel position

+    return _glfwInput.WheelPos;

+}

+

+

+//========================================================================

+// glfwSetMouseWheel()

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwSetMouseWheel( int pos )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return;

+    }

+

+    // Set mouse wheel position

+    _glfwInput.WheelPos = pos;

+}

+

+

+//========================================================================

+// glfwSetKeyCallback() - Set callback function for keyboard input

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwSetKeyCallback( GLFWkeyfun cbfun )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return;

+    }

+

+    // Set callback function

+    _glfwWin.KeyCallback = cbfun;

+}

+

+

+//========================================================================

+// glfwSetCharCallback() - Set callback function for character input

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwSetCharCallback( GLFWcharfun cbfun )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return;

+    }

+

+    // Set callback function

+    _glfwWin.CharCallback = cbfun;

+}

+

+

+//========================================================================

+// glfwSetMouseButtonCallback() - Set callback function for mouse clicks

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwSetMouseButtonCallback( GLFWmousebuttonfun cbfun )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return;

+    }

+

+    // Set callback function

+    _glfwWin.MouseButtonCallback = cbfun;

+}

+

+

+//========================================================================

+// glfwSetMousePosCallback() - Set callback function for mouse moves

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwSetMousePosCallback( GLFWmouseposfun cbfun )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return;

+    }

+

+    // Set callback function

+    _glfwWin.MousePosCallback = cbfun;

+

+    // Call the callback function to let the application know the current

+    // mouse position

+    if( cbfun )

+    {

+        cbfun( _glfwInput.MousePosX, _glfwInput.MousePosY );

+    }

+}

+

+

+//========================================================================

+// glfwSetMouseWheelCallback() - Set callback function for mouse wheel

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwSetMouseWheelCallback( GLFWmousewheelfun cbfun )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return;

+    }

+

+    // Set callback function

+    _glfwWin.MouseWheelCallback = cbfun;

+

+    // Call the callback function to let the application know the current

+    // mouse wheel position

+    if( cbfun )

+    {

+        cbfun( _glfwInput.WheelPos );

+    }

+}

+

diff --git a/src/engine/external/glfw/lib/internal.h b/src/engine/external/glfw/lib/internal.h
new file mode 100644
index 00000000..1785d1e9
--- /dev/null
+++ b/src/engine/external/glfw/lib/internal.h
@@ -0,0 +1,210 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        internal.h

+// Platform:    Any

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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 _internal_h_

+#define _internal_h_

+

+//========================================================================

+// GLFWGLOBAL is a macro that places all global variables in the init.c

+// module (all other modules reference global variables as 'extern')

+//========================================================================

+

+#if defined( _init_c_ )

+#define GLFWGLOBAL

+#else

+#define GLFWGLOBAL extern

+#endif

+

+

+//========================================================================

+// Input handling definitions

+//========================================================================

+

+// Internal key and button state/action definitions

+#define GLFW_STICK              2

+

+

+//========================================================================

+// System independent include files

+//========================================================================

+

+#include <stdlib.h>

+#include <string.h>

+#include <stdio.h>

+

+

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

+// Platform specific definitions goes in platform.h (which also includes

+// glfw.h)

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

+

+#include "platform.h"

+

+

+//========================================================================

+// System independent global variables (GLFW internals)

+//========================================================================

+

+// Flag indicating if GLFW has been initialized

+#if defined( _init_c_ )

+int _glfwInitialized = 0;

+#else

+GLFWGLOBAL int _glfwInitialized;

+#endif

+

+

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

+// Window hints (set by glfwOpenWindowHint - will go into _GLFWthread)

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

+typedef struct {

+    int          RefreshRate;

+    int          AccumRedBits;

+    int          AccumGreenBits;

+    int          AccumBlueBits;

+    int          AccumAlphaBits;

+    int          AuxBuffers;

+    int          Stereo;

+    int          WindowNoResize;

+    int		 Samples;

+} _GLFWhints;

+

+GLFWGLOBAL _GLFWhints _glfwWinHints;

+

+

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

+// Abstracted data stream (for image I/O)

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

+typedef struct {

+    FILE*     File;

+    void*     Data;

+    long      Position;

+    long      Size;

+} _GLFWstream;

+

+

+//========================================================================

+// Prototypes for platform specific implementation functions

+//========================================================================

+

+// Init/terminate

+int _glfwPlatformInit( void );

+int _glfwPlatformTerminate( void );

+

+// Enable/Disable

+void _glfwPlatformEnableSystemKeys( void );

+void _glfwPlatformDisableSystemKeys( void );

+

+// Fullscreen

+int  _glfwPlatformGetVideoModes( GLFWvidmode *list, int maxcount );

+void _glfwPlatformGetDesktopMode( GLFWvidmode *mode );

+

+// OpenGL extensions

+int    _glfwPlatformExtensionSupported( const char *extension );

+void * _glfwPlatformGetProcAddress( const char *procname );

+

+// Joystick

+int _glfwPlatformGetJoystickParam( int joy, int param );

+int _glfwPlatformGetJoystickPos( int joy, float *pos, int numaxes );

+int _glfwPlatformGetJoystickButtons( int joy, unsigned char *buttons, int numbuttons );

+

+// Threads

+GLFWthread _glfwPlatformCreateThread( GLFWthreadfun fun, void *arg );

+void       _glfwPlatformDestroyThread( GLFWthread ID );

+int        _glfwPlatformWaitThread( GLFWthread ID, int waitmode );

+GLFWthread _glfwPlatformGetThreadID( void );

+GLFWmutex  _glfwPlatformCreateMutex( void );

+void       _glfwPlatformDestroyMutex( GLFWmutex mutex );

+void       _glfwPlatformLockMutex( GLFWmutex mutex );

+void       _glfwPlatformUnlockMutex( GLFWmutex mutex );

+GLFWcond   _glfwPlatformCreateCond( void );

+void       _glfwPlatformDestroyCond( GLFWcond cond );

+void       _glfwPlatformWaitCond( GLFWcond cond, GLFWmutex mutex, double timeout );

+void       _glfwPlatformSignalCond( GLFWcond cond );

+void       _glfwPlatformBroadcastCond( GLFWcond cond );

+int        _glfwPlatformGetNumberOfProcessors( void );

+

+// Time

+double _glfwPlatformGetTime( void );

+void   _glfwPlatformSetTime( double time );

+void   _glfwPlatformSleep( double time );

+

+// Window management

+int  _glfwPlatformOpenWindow( int width, int height, int redbits, int greenbits, int bluebits, int alphabits, int depthbits, int stencilbits, int mode, _GLFWhints* hints );

+void _glfwPlatformCloseWindow( void );

+void _glfwPlatformSetWindowTitle( const char *title );

+void _glfwPlatformSetWindowSize( int width, int height );

+void _glfwPlatformSetWindowPos( int x, int y );

+void _glfwPlatformIconifyWindow( void );

+void _glfwPlatformRestoreWindow( void );

+void _glfwPlatformSwapBuffers( void );

+void _glfwPlatformSwapInterval( int interval );

+void _glfwPlatformRefreshWindowParams( void );

+void _glfwPlatformPollEvents( void );

+void _glfwPlatformWaitEvents( void );

+void _glfwPlatformHideMouseCursor( void );

+void _glfwPlatformShowMouseCursor( void );

+void _glfwPlatformSetMouseCursorPos( int x, int y );

+

+

+//========================================================================

+// Prototypes for platform independent internal functions

+//========================================================================

+

+// Window management (window.c)

+void _glfwClearWindowHints( void );

+

+// Input handling (window.c)

+void _glfwClearInput( void );

+void _glfwInputDeactivation( void );

+void _glfwInputKey( int key, int action );

+void _glfwInputChar( int character, int action );

+void _glfwInputMouseClick( int button, int action );

+

+// Threads (thread.c)

+_GLFWthread * _glfwGetThreadPointer( int ID );

+void _glfwAppendThread( _GLFWthread * t );

+void _glfwRemoveThread( _GLFWthread * t );

+

+// OpenGL extensions (glext.c)

+int _glfwStringInExtensionString( const char *string, const GLubyte *extensions );

+

+// Abstracted data streams (stream.c)

+int  _glfwOpenFileStream( _GLFWstream *stream, const char *name, const char *mode );

+int  _glfwOpenBufferStream( _GLFWstream *stream, void *data, long size );

+long _glfwReadStream( _GLFWstream *stream, void *data, long size );

+long _glfwTellStream( _GLFWstream *stream );

+int  _glfwSeekStream( _GLFWstream *stream, long offset, int whence );

+void _glfwCloseStream( _GLFWstream *stream );

+

+// Targa image I/O (tga.c)

+int  _glfwReadTGA( _GLFWstream *s, GLFWimage *img, int flags );

+

+

+#endif // _internal_h_

diff --git a/src/engine/external/glfw/lib/joystick.c b/src/engine/external/glfw/lib/joystick.c
new file mode 100644
index 00000000..9ce139f5
--- /dev/null
+++ b/src/engine/external/glfw/lib/joystick.c
@@ -0,0 +1,101 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        joystick.c

+// Platform:    Any

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

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

+//****                    GLFW user functions                         ****

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

+

+//========================================================================

+// glfwGetJoystickParam() - Determine joystick capabilities

+//========================================================================

+

+GLFWAPI int GLFWAPIENTRY glfwGetJoystickParam( int joy, int param )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized )

+    {

+        return 0;

+    }

+

+    return _glfwPlatformGetJoystickParam( joy, param );

+}

+

+

+//========================================================================

+// glfwGetJoystickPos() - Get joystick axis positions

+//========================================================================

+

+GLFWAPI int GLFWAPIENTRY glfwGetJoystickPos( int joy, float *pos,

+    int numaxes )

+{

+    int       i;

+

+    // Is GLFW initialized?

+    if( !_glfwInitialized )

+    {

+        return 0;

+    }

+

+    // Clear positions

+    for( i = 0; i < numaxes; i++ )

+    {

+        pos[ i ] = 0.0f;

+    }

+

+    return _glfwPlatformGetJoystickPos( joy, pos, numaxes );

+}

+

+

+//========================================================================

+// glfwGetJoystickButtons() - Get joystick button states

+//========================================================================

+

+GLFWAPI int GLFWAPIENTRY glfwGetJoystickButtons( int joy,

+    unsigned char *buttons, int numbuttons )

+{

+    int       i;

+

+    // Is GLFW initialized?

+    if( !_glfwInitialized )

+    {

+        return 0;

+    }

+

+    // Clear button states

+    for( i = 0; i < numbuttons; i++ )

+    {

+        buttons[ i ] = GLFW_RELEASE;

+    }

+

+    return _glfwPlatformGetJoystickButtons( joy, buttons, numbuttons );

+}

diff --git a/src/engine/external/glfw/lib/macosx/macosx_enable.c b/src/engine/external/glfw/lib/macosx/macosx_enable.c
new file mode 100644
index 00000000..e4047366
--- /dev/null
+++ b/src/engine/external/glfw/lib/macosx/macosx_enable.c
@@ -0,0 +1,42 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        macosx_enable.c

+// Platform:    Mac OS X

+// API Version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+void _glfwPlatformEnableSystemKeys( void )

+{

+    // Nothing to do; event handling code checks the status of

+    // _glfwWin.SysKeysDisabled to ensure this behavior.

+}

+

+void _glfwPlatformDisableSystemKeys( void )

+{

+    // Nothing to do; event handling code checks the status of

+    // _glfwWin.SysKeysDisabled to ensure this behavior.

+}

+

diff --git a/src/engine/external/glfw/lib/macosx/macosx_fullscreen.c b/src/engine/external/glfw/lib/macosx/macosx_fullscreen.c
new file mode 100644
index 00000000..b16495fb
--- /dev/null
+++ b/src/engine/external/glfw/lib/macosx/macosx_fullscreen.c
@@ -0,0 +1,126 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        macosx_fullscreen.c

+// Platform:    Mac OS X

+// API Version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+//========================================================================

+// _glfwVideoModesEqual() - Compares two video modes

+//========================================================================

+

+static int _glfwVideoModesEqual( GLFWvidmode* first,

+                                 GLFWvidmode* second )

+{

+    if( first->Width != second->Width )

+	return 0;

+		

+    if( first->Height != second->Height )

+	return 0;

+		

+    if( first->RedBits + first->GreenBits + first->BlueBits !=

+      second->RedBits + second->GreenBits + second->BlueBits )

+	return 0;

+	

+    return 1;

+}

+                            

+//========================================================================

+// _glfwCGToGLFWVideoMode() - Converts a CG mode to a GLFW mode

+//========================================================================

+

+static void _glfwCGToGLFWVideoMode( CFDictionaryRef cgMode,

+                                    GLFWvidmode* glfwMode )

+{

+    int bitsPerSample;

+

+    CFNumberGetValue( CFDictionaryGetValue( cgMode, kCGDisplayWidth ),

+                     kCFNumberIntType,

+                     &(glfwMode->Width) );

+    CFNumberGetValue( CFDictionaryGetValue( cgMode, kCGDisplayHeight ),

+                     kCFNumberIntType,

+                     &(glfwMode->Height) );

+

+    CFNumberGetValue( CFDictionaryGetValue( cgMode, kCGDisplayBitsPerSample ),

+                     kCFNumberIntType,

+                     &bitsPerSample );

+

+    glfwMode->RedBits = bitsPerSample;

+    glfwMode->GreenBits = bitsPerSample;

+    glfwMode->BlueBits = bitsPerSample;

+}

+

+//========================================================================

+// _glfwPlatformGetVideoModes() - Get a list of available video modes

+//========================================================================

+

+int _glfwPlatformGetVideoModes( GLFWvidmode *list, int maxcount )

+{

+    int i, j, maxModes, numModes;

+    GLFWvidmode mode;

+    CFArrayRef availableModes = CGDisplayAvailableModes( kCGDirectMainDisplay );

+    CFIndex numberOfAvailableModes = CFArrayGetCount( availableModes );

+

+    numModes = 0;

+    maxModes = ( numberOfAvailableModes < maxcount ?

+                 numberOfAvailableModes :

+                 maxcount );

+

+    for( i = 0; i < maxModes; ++i )

+    {

+        _glfwCGToGLFWVideoMode( CFArrayGetValueAtIndex( availableModes, i ),

+                                &mode );

+

+        // Is it a valid mode? (only list depths >= 15 bpp)

+	if( mode.RedBits + mode.GreenBits + mode.BlueBits < 15 )

+	    continue;

+			

+        // Check for duplicate of current mode in target list

+      	for( j = 0; j < numModes; ++j )

+      	{

+      	    if( _glfwVideoModesEqual( &mode, &(list[j]) ) )

+      		break;

+      	}

+      	

+      	// If empty list or no match found

+      	if( numModes == 0 || j == numModes )

+      	    list[numModes++] = mode;

+    }

+

+    return numModes;

+}

+

+//========================================================================

+// glfwGetDesktopMode() - Get the desktop video mode

+//========================================================================

+

+void _glfwPlatformGetDesktopMode( GLFWvidmode *mode )

+{

+    _glfwCGToGLFWVideoMode( _glfwDesktopVideoMode, mode );

+}

+

diff --git a/src/engine/external/glfw/lib/macosx/macosx_glext.c b/src/engine/external/glfw/lib/macosx/macosx_glext.c
new file mode 100644
index 00000000..0b623a5c
--- /dev/null
+++ b/src/engine/external/glfw/lib/macosx/macosx_glext.c
@@ -0,0 +1,52 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        macosx_glext.c

+// Platform:    Mac OS X

+// API Version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+int _glfwPlatformExtensionSupported( const char *extension )

+{

+    // There are no AGL, CGL or NSGL extensions.

+    return GL_FALSE;

+}

+

+void * _glfwPlatformGetProcAddress( const char *procname )

+{

+    CFStringRef symbolName = CFStringCreateWithCString( kCFAllocatorDefault,

+                                                        procname,

+                                                        kCFStringEncodingASCII );

+

+    void *symbol = CFBundleGetFunctionPointerForName( _glfwLibrary.Libs.OpenGLFramework,

+                                                      symbolName );

+

+    CFRelease( symbolName );

+

+    return symbol;

+}

+

diff --git a/src/engine/external/glfw/lib/macosx/macosx_init.c b/src/engine/external/glfw/lib/macosx/macosx_init.c
new file mode 100644
index 00000000..c123daf0
--- /dev/null
+++ b/src/engine/external/glfw/lib/macosx/macosx_init.c
@@ -0,0 +1,194 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        macosx_init.c

+// Platform:    Mac OS X

+// API Version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+#include <unistd.h>

+

+//========================================================================

+// Global variables

+//========================================================================

+

+// KCHR resource pointer for keycode translation

+void *KCHRPtr;

+

+

+//========================================================================

+// _glfwInitThreads() - Initialize GLFW thread package

+//========================================================================

+

+static void _glfwInitThreads( void )

+{

+    // Initialize critical section handle

+    (void) pthread_mutex_init( &_glfwThrd.CriticalSection, NULL );

+

+    // The first thread (the main thread) has ID 0

+    _glfwThrd.NextID = 0;

+

+    // Fill out information about the main thread (this thread)

+    _glfwThrd.First.ID       = _glfwThrd.NextID ++;

+    _glfwThrd.First.Function = NULL;

+    _glfwThrd.First.PosixID  = pthread_self();

+    _glfwThrd.First.Previous = NULL;

+    _glfwThrd.First.Next     = NULL;

+}

+

+#define NO_BUNDLE_MESSAGE \

+    "Working in unbundled mode.  " \

+    "You should build a .app wrapper for your Mac OS X applications.\n"

+

+#define UNBUNDLED \

+    fprintf(stderr, NO_BUNDLE_MESSAGE); \

+    _glfwLibrary.Unbundled = 1; \

+    return

+

+void _glfwChangeToResourcesDirectory( void )

+{

+    CFBundleRef mainBundle = CFBundleGetMainBundle();

+    CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL( mainBundle );

+    char resourcesPath[ _GLFW_MAX_PATH_LENGTH ];

+    

+    CFStringRef lastComponent = CFURLCopyLastPathComponent( resourcesURL );

+    if ( kCFCompareEqualTo != CFStringCompare(

+            CFSTR( "Resources" ),

+            lastComponent,

+            0 ) )

+    {

+        UNBUNDLED;

+    }

+    

+    CFRelease( lastComponent );

+

+    if( !CFURLGetFileSystemRepresentation( resourcesURL,

+                                           TRUE,

+                                           (UInt8*)resourcesPath,

+                                           _GLFW_MAX_PATH_LENGTH ) )

+    {

+        CFRelease( resourcesURL );

+        UNBUNDLED;

+    }

+

+    CFRelease( resourcesURL );

+

+    if( chdir( resourcesPath ) != 0 )

+    {

+        UNBUNDLED;

+    }

+}

+

+int _glfwPlatformInit( void )

+{

+    struct timeval tv;

+    UInt32 nullDummy = 0;

+

+    _glfwWin.MacWindow = NULL;

+    _glfwWin.AGLContext = NULL;

+    _glfwWin.CGLContext = NULL;

+    _glfwWin.WindowFunctions = NULL;

+    _glfwWin.MouseUPP = NULL;

+    _glfwWin.CommandUPP = NULL;

+    _glfwWin.KeyboardUPP = NULL;

+    _glfwWin.WindowUPP = NULL;

+    

+    _glfwInput.Modifiers = 0;

+    

+    _glfwLibrary.Unbundled = 0;

+    

+    _glfwLibrary.Libs.OpenGLFramework

+        = CFBundleGetBundleWithIdentifier( CFSTR( "com.apple.opengl" ) );

+    if( _glfwLibrary.Libs.OpenGLFramework == NULL )

+    {

+        fprintf(

+            stderr,

+            "glfwInit failing because you aren't linked to OpenGL\n" );

+        return GL_FALSE;

+    }

+

+    _glfwDesktopVideoMode = CGDisplayCurrentMode( kCGDirectMainDisplay );

+    if( _glfwDesktopVideoMode == NULL )

+    {

+        fprintf(

+            stderr,

+            "glfwInit failing because it kind find the desktop display mode\n" );

+        return GL_FALSE;

+    }

+

+    _glfwInitThreads();

+

+    _glfwChangeToResourcesDirectory();

+

+    if( !_glfwInstallEventHandlers() )

+    {

+    	fprintf(

+            stderr,

+            "glfwInit failing because it can't install event handlers\n" );

+        _glfwPlatformTerminate();

+        return GL_FALSE;

+    }

+

+    // Ugly hack to reduce the nasty jump that occurs at the first non-

+    // sys keypress, caused by OS X loading certain meta scripts used

+    // for lexical- and raw keycode translation - instead of letting

+    // this happen while our application is running, we do some blunt

+    // function calls in advance just to get the script caching out of

+    // the way BEFORE our window/screen is opened. These calls might

+    // generate err return codes, but we don't care in this case.

+    // NOTE: KCHRPtr is declared globally, because we need it later on.

+    KCHRPtr = (void *)GetScriptVariable( smCurrentScript, smKCHRCache );

+    KeyTranslate( KCHRPtr, 0, &nullDummy );

+    UppercaseText( (char *)&nullDummy, 0, smSystemScript );

+

+    gettimeofday( &tv, NULL );

+    _glfwLibrary.Timer.t0 = tv.tv_sec + (double) tv.tv_usec / 1000000.0;

+

+    return GL_TRUE;

+}

+

+int _glfwPlatformTerminate( void )

+{

+    if( _glfwWin.MouseUPP != NULL )

+    {

+        DisposeEventHandlerUPP( _glfwWin.MouseUPP );

+        _glfwWin.MouseUPP = NULL;

+    }

+    if( _glfwWin.CommandUPP != NULL )

+    {

+        DisposeEventHandlerUPP( _glfwWin.CommandUPP );

+        _glfwWin.CommandUPP = NULL;

+    }

+    if( _glfwWin.KeyboardUPP != NULL )

+    {

+        DisposeEventHandlerUPP( _glfwWin.KeyboardUPP );

+        _glfwWin.KeyboardUPP = NULL;

+    }

+    

+    return GL_TRUE;

+}

+

diff --git a/src/engine/external/glfw/lib/macosx/macosx_joystick.c b/src/engine/external/glfw/lib/macosx/macosx_joystick.c
new file mode 100644
index 00000000..527de017
--- /dev/null
+++ b/src/engine/external/glfw/lib/macosx/macosx_joystick.c
@@ -0,0 +1,50 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        macosx_joystick.c

+// Platform:    Mac OS X

+// API Version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+// TO DO: use HID manager to implement joystick support.

+

+int _glfwPlatformGetJoystickParam( int joy, int param )

+{

+    // GL_FALSE == 0

+    return 0;

+}

+

+int _glfwPlatformGetJoystickPos( int joy, float *pos, int numaxes )

+{

+    return 0;

+}

+

+int _glfwPlatformGetJoystickButtons( int joy, unsigned char *buttons, int numbuttons )

+{

+    return 0;

+}

+

diff --git a/src/engine/external/glfw/lib/macosx/macosx_thread.c b/src/engine/external/glfw/lib/macosx/macosx_thread.c
new file mode 100644
index 00000000..c1213957
--- /dev/null
+++ b/src/engine/external/glfw/lib/macosx/macosx_thread.c
@@ -0,0 +1,414 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        macosx_thread.c

+// Platform:    Mac OS X

+// API Version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

+

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

+//****                  GLFW internal functions                       ****

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

+

+//========================================================================

+// _glfwNewThread() - This is simply a "wrapper" for calling the user

+// thread function.

+//========================================================================

+

+void * _glfwNewThread( void * arg )

+{

+    GLFWthreadfun threadfun;

+    _GLFWthread   *t;

+

+    // Get pointer to thread information for current thread

+    t = _glfwGetThreadPointer( glfwGetThreadID() );

+    if( t == NULL )

+    {

+        return 0;

+    }

+

+    // Get user thread function pointer

+    threadfun = t->Function;

+

+    // Call the user thread function

+    threadfun( arg );

+

+    // Remove thread from thread list

+    ENTER_THREAD_CRITICAL_SECTION

+        _glfwRemoveThread( t );

+    LEAVE_THREAD_CRITICAL_SECTION

+

+    // When the thread function returns, the thread will die...

+    return NULL;

+}

+

+

+

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

+//****               Platform implementation functions                ****

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

+

+//========================================================================

+// _glfwPlatformCreateThread() - Create a new thread

+//========================================================================

+

+GLFWthread _glfwPlatformCreateThread( GLFWthreadfun fun, void *arg )

+{

+    GLFWthread  ID;

+    _GLFWthread *t;

+    int         result;

+

+    // Enter critical section

+    ENTER_THREAD_CRITICAL_SECTION

+

+    // Create a new thread information memory area

+    t = (_GLFWthread *) malloc( sizeof(_GLFWthread) );

+    if( t == NULL )

+    {

+        // Leave critical section

+        LEAVE_THREAD_CRITICAL_SECTION

+        return -1;

+    }

+

+    // Get a new unique thread id

+    ID = _glfwThrd.NextID ++;

+

+    // Store thread information in the thread list

+    t->Function = fun;

+    t->ID       = ID;

+

+    // Create thread

+    result = pthread_create(

+                            &t->PosixID,      // Thread handle

+                            NULL,             // Default thread attributes

+                            _glfwNewThread,   // Thread function (a wrapper function)

+                            (void *)arg       // Argument to thread is user argument

+                            );

+

+    // Did the thread creation fail?

+    if( result != 0 )

+    {

+        free( (void *) t );

+        LEAVE_THREAD_CRITICAL_SECTION

+        return -1;

+    }

+

+    // Append thread to thread list

+    _glfwAppendThread( t );

+

+    // Leave critical section

+    LEAVE_THREAD_CRITICAL_SECTION

+

+    // Return the GLFW thread ID

+    return ID;

+}

+

+

+//========================================================================

+// _glfwPlatformDestroyThread() - Kill a thread. NOTE: THIS IS A VERY

+// DANGEROUS OPERATION, AND SHOULD NOT BE USED EXCEPT IN EXTREME

+// SITUATIONS!

+//========================================================================

+

+void _glfwPlatformDestroyThread( GLFWthread ID )

+{

+    _GLFWthread *t;

+

+    // Enter critical section

+    ENTER_THREAD_CRITICAL_SECTION

+

+    // Get thread information pointer

+    t = _glfwGetThreadPointer( ID );

+    if( t == NULL )

+    {

+        LEAVE_THREAD_CRITICAL_SECTION

+        return;

+    }

+

+    // Simply murder the process, no mercy!

+    pthread_kill( t->PosixID, SIGKILL );

+

+    // Remove thread from thread list

+    _glfwRemoveThread( t );

+

+    // Leave critical section

+    LEAVE_THREAD_CRITICAL_SECTION

+}

+

+

+//========================================================================

+// _glfwPlatformWaitThread() - Wait for a thread to die

+//========================================================================

+

+int _glfwPlatformWaitThread( GLFWthread ID, int waitmode )

+{

+    pthread_t   thread;

+    _GLFWthread *t;

+

+    // Enter critical section

+    ENTER_THREAD_CRITICAL_SECTION

+

+    // Get thread information pointer

+    t = _glfwGetThreadPointer( ID );

+

+    // Is the thread already dead?

+    if( t == NULL )

+    {

+        LEAVE_THREAD_CRITICAL_SECTION

+        return GL_TRUE;

+    }

+

+    // If got this far, the thread is alive => polling returns FALSE

+    if( waitmode == GLFW_NOWAIT )

+    {

+        LEAVE_THREAD_CRITICAL_SECTION

+        return GL_FALSE;

+    }

+

+    // Get thread handle

+    thread = t->PosixID;

+

+    // Leave critical section

+    LEAVE_THREAD_CRITICAL_SECTION

+

+    // Wait for thread to die

+    (void) pthread_join( thread, NULL );

+

+    return GL_TRUE;

+}

+

+

+//========================================================================

+// _glfwPlatformGetThreadID() - Return the thread ID for the current

+// thread

+//========================================================================

+

+GLFWthread _glfwPlatformGetThreadID( void )

+{

+    _GLFWthread *t;

+    GLFWthread  ID = -1;

+    pthread_t   posixID;

+

+    // Get current thread ID

+    posixID = pthread_self();

+

+    // Enter critical section

+    ENTER_THREAD_CRITICAL_SECTION

+

+    // Loop through entire list of threads to find the matching POSIX

+    // thread ID

+    for( t = &_glfwThrd.First; t != NULL; t = t->Next )

+    {

+        if( t->PosixID == posixID )

+        {

+            ID = t->ID;

+            break;

+        }

+    }

+

+    // Leave critical section

+    LEAVE_THREAD_CRITICAL_SECTION

+

+    // Return the found GLFW thread identifier

+    return ID;

+}

+

+

+//========================================================================

+// _glfwPlatformCreateMutex() - Create a mutual exclusion object

+//========================================================================

+

+GLFWmutex _glfwPlatformCreateMutex( void )

+{

+    pthread_mutex_t *mutex;

+

+    // Allocate memory for mutex

+    mutex = (pthread_mutex_t *) malloc( sizeof( pthread_mutex_t ) );

+    if( !mutex )

+    {

+        return NULL;

+    }

+

+    // Initialise a mutex object

+    (void) pthread_mutex_init( mutex, NULL );

+

+    // Cast to GLFWmutex and return

+    return (GLFWmutex) mutex;

+}

+

+

+//========================================================================

+// _glfwPlatformDestroyMutex() - Destroy a mutual exclusion object

+//========================================================================

+

+void _glfwPlatformDestroyMutex( GLFWmutex mutex )

+{

+    // Destroy the mutex object

+    pthread_mutex_destroy( (pthread_mutex_t *) mutex );

+

+    // Free memory for mutex object

+    free( (void *) mutex );

+}

+

+

+//========================================================================

+// _glfwPlatformLockMutex() - Request access to a mutex

+//========================================================================

+

+void _glfwPlatformLockMutex( GLFWmutex mutex )

+{

+    // Wait for mutex to be released

+    (void) pthread_mutex_lock( (pthread_mutex_t *) mutex );

+}

+

+

+//========================================================================

+// _glfwPlatformUnlockMutex() - Release a mutex

+//========================================================================

+

+void _glfwPlatformUnlockMutex( GLFWmutex mutex )

+{

+    // Release mutex

+    pthread_mutex_unlock( (pthread_mutex_t *) mutex );

+}

+

+

+//========================================================================

+// _glfwPlatformCreateCond() - Create a new condition variable object

+//========================================================================

+

+GLFWcond _glfwPlatformCreateCond( void )

+{

+    pthread_cond_t *cond;

+

+    // Allocate memory for condition variable

+    cond = (pthread_cond_t *) malloc( sizeof(pthread_cond_t) );

+    if( !cond )

+    {

+        return NULL;

+    }

+

+    // Initialise condition variable

+    (void) pthread_cond_init( cond, NULL );

+

+    // Cast to GLFWcond and return

+    return (GLFWcond) cond;

+}

+

+

+//========================================================================

+// _glfwPlatformDestroyCond() - Destroy a condition variable object

+//========================================================================

+

+void _glfwPlatformDestroyCond( GLFWcond cond )

+{

+    // Destroy the condition variable object

+    (void) pthread_cond_destroy( (pthread_cond_t *) cond );

+

+    // Free memory for condition variable object

+    free( (void *) cond );

+}

+

+

+//========================================================================

+// _glfwPlatformWaitCond() - Wait for a condition to be raised

+//========================================================================

+

+void _glfwPlatformWaitCond( GLFWcond cond, GLFWmutex mutex,

+                            double timeout )

+{

+    struct timeval  currenttime;

+    struct timespec wait;

+    long dt_sec, dt_usec;

+

+    // Select infinite or timed wait

+    if( timeout >= GLFW_INFINITY )

+    {

+        // Wait for condition (infinite wait)

+        (void) pthread_cond_wait( (pthread_cond_t *) cond,

+                                  (pthread_mutex_t *) mutex );

+    }

+    else

+    {

+        // Set timeout time, relatvie to current time

+        gettimeofday( &currenttime, NULL );

+        dt_sec  = (long) timeout;

+        dt_usec = (long) ((timeout - (double)dt_sec) * 1000000.0);

+        wait.tv_nsec = (currenttime.tv_usec + dt_usec) * 1000L;

+        if( wait.tv_nsec > 1000000000L )

+        {

+            wait.tv_nsec -= 1000000000L;

+            dt_sec ++;

+        }

+        wait.tv_sec  = currenttime.tv_sec + dt_sec;

+

+        // Wait for condition (timed wait)

+        (void) pthread_cond_timedwait( (pthread_cond_t *) cond,

+                                       (pthread_mutex_t *) mutex, &wait );

+    }

+}

+

+

+//========================================================================

+// _glfwPlatformSignalCond() - Signal a condition to one waiting thread

+//========================================================================

+

+void _glfwPlatformSignalCond( GLFWcond cond )

+{

+    // Signal condition

+    (void) pthread_cond_signal( (pthread_cond_t *) cond );

+}

+

+

+//========================================================================

+// _glfwPlatformBroadcastCond() - Broadcast a condition to all waiting

+// threads

+//========================================================================

+

+void _glfwPlatformBroadcastCond( GLFWcond cond )

+{

+    // Broadcast condition

+    (void) pthread_cond_broadcast( (pthread_cond_t *) cond );

+}

+

+

+//========================================================================

+// _glfwPlatformGetNumberOfProcessors() - Return the number of processors

+// in the system.

+//========================================================================

+

+int _glfwPlatformGetNumberOfProcessors( void )

+{

+    int n;

+

+    // Get number of processors online

+    _glfw_numprocessors( n );

+    return n;

+}

+

diff --git a/src/engine/external/glfw/lib/macosx/macosx_time.c b/src/engine/external/glfw/lib/macosx/macosx_time.c
new file mode 100644
index 00000000..cde52b4b
--- /dev/null
+++ b/src/engine/external/glfw/lib/macosx/macosx_time.c
@@ -0,0 +1,112 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        macosx_time.c

+// Platform:    Mac OS X

+// API Version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

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

+//****               Platform implementation functions                ****

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

+

+//========================================================================

+// Return timer value in seconds

+//========================================================================

+

+double _glfwPlatformGetTime( void )

+{

+    struct timeval  tv;

+

+    gettimeofday( &tv, NULL );

+    return tv.tv_sec + (double) tv.tv_usec / 1000000.0 - _glfwLibrary.Timer.t0;

+}

+

+

+//========================================================================

+// Set timer value in seconds

+//========================================================================

+

+void _glfwPlatformSetTime( double time )

+{

+    struct timeval  tv;

+

+    gettimeofday( &tv, NULL );

+    _glfwLibrary.Timer.t0 = tv.tv_sec + (double) tv.tv_usec / 1000000.0 - time;

+}

+

+

+//========================================================================

+// Put a thread to sleep for a specified amount of time

+//========================================================================

+

+void _glfwPlatformSleep( double time )

+{

+    if( time == 0.0 )

+    {

+	sched_yield();

+	return;

+    }

+

+    struct timeval  currenttime;

+    struct timespec wait;

+    pthread_mutex_t mutex;

+    pthread_cond_t  cond;

+    long dt_sec, dt_usec;

+

+    // Not all pthread implementations have a pthread_sleep() function. We

+    // do it the portable way, using a timed wait for a condition that we

+    // will never signal. NOTE: The unistd functions sleep/usleep suspends

+    // the entire PROCESS, not a signle thread, which is why we can not

+    // use them to implement glfwSleep.

+

+    // Set timeout time, relatvie to current time

+    gettimeofday( &currenttime, NULL );

+    dt_sec  = (long) time;

+    dt_usec = (long) ((time - (double)dt_sec) * 1000000.0);

+    wait.tv_nsec = (currenttime.tv_usec + dt_usec) * 1000L;

+    if( wait.tv_nsec > 1000000000L )

+    {

+        wait.tv_nsec -= 1000000000L;

+        dt_sec ++;

+    }

+    wait.tv_sec  = currenttime.tv_sec + dt_sec;

+

+    // Initialize condition and mutex objects

+    pthread_mutex_init( &mutex, NULL );

+    pthread_cond_init( &cond, NULL );

+

+    // Do a timed wait

+    pthread_mutex_lock( &mutex );

+    pthread_cond_timedwait( &cond, &mutex, &wait );

+    pthread_mutex_unlock( &mutex );

+

+    // Destroy condition and mutex objects

+    pthread_mutex_destroy( &mutex );

+    pthread_cond_destroy( &cond );

+}

+

diff --git a/src/engine/external/glfw/lib/macosx/macosx_window.c b/src/engine/external/glfw/lib/macosx/macosx_window.c
new file mode 100644
index 00000000..b8af0c4e
--- /dev/null
+++ b/src/engine/external/glfw/lib/macosx/macosx_window.c
@@ -0,0 +1,1279 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        macosx_window.c

+// Platform:    Mac OS X

+// API Version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+static _GLFWmacwindowfunctions _glfwMacFSWindowFunctions =

+{

+    _glfwMacFSOpenWindow,

+    _glfwMacFSCloseWindow,

+    _glfwMacFSSetWindowTitle,

+    _glfwMacFSSetWindowSize,

+    _glfwMacFSSetWindowPos,

+    _glfwMacFSIconifyWindow,

+    _glfwMacFSRestoreWindow,

+    _glfwMacFSRefreshWindowParams,

+    _glfwMacFSSetMouseCursorPos

+};

+

+static _GLFWmacwindowfunctions _glfwMacDWWindowFunctions =

+{

+    _glfwMacDWOpenWindow,

+    _glfwMacDWCloseWindow,

+    _glfwMacDWSetWindowTitle,

+    _glfwMacDWSetWindowSize,

+    _glfwMacDWSetWindowPos,

+    _glfwMacDWIconifyWindow,

+    _glfwMacDWRestoreWindow,

+    _glfwMacDWRefreshWindowParams,

+    _glfwMacDWSetMouseCursorPos

+};

+

+#define _glfwTestModifier( modifierMask, glfwKey ) \

+if ( changed & modifierMask ) \

+{ \

+    _glfwInputKey( glfwKey, (modifiers & modifierMask ? GLFW_PRESS : GLFW_RELEASE) ); \

+}

+

+void _glfwHandleMacModifierChange( UInt32 modifiers )

+{

+    UInt32 changed = modifiers ^ _glfwInput.Modifiers;

+

+    _glfwTestModifier( shiftKey,        GLFW_KEY_LSHIFT );

+    _glfwTestModifier( rightShiftKey,   GLFW_KEY_RSHIFT );

+    _glfwTestModifier( controlKey,      GLFW_KEY_LCTRL );

+    _glfwTestModifier( rightControlKey, GLFW_KEY_RCTRL );

+    _glfwTestModifier( optionKey,       GLFW_KEY_LALT );

+    _glfwTestModifier( rightOptionKey,  GLFW_KEY_RALT );

+

+    _glfwInput.Modifiers = modifiers;

+}

+

+void _glfwHandleMacKeyChange( UInt32 keyCode, int action )

+{

+    switch ( keyCode )

+    {

+        case MAC_KEY_ENTER:       _glfwInputKey( GLFW_KEY_ENTER,       action); break;

+        case MAC_KEY_RETURN:      _glfwInputKey( GLFW_KEY_KP_ENTER,    action); break;

+        case MAC_KEY_ESC:         _glfwInputKey( GLFW_KEY_ESC,         action); break;

+        case MAC_KEY_F1:          _glfwInputKey( GLFW_KEY_F1,          action); break;

+        case MAC_KEY_F2:          _glfwInputKey( GLFW_KEY_F2,          action); break;

+        case MAC_KEY_F3:          _glfwInputKey( GLFW_KEY_F3,          action); break;

+        case MAC_KEY_F4:          _glfwInputKey( GLFW_KEY_F4,          action); break;

+        case MAC_KEY_F5:          _glfwInputKey( GLFW_KEY_F5,          action); break;

+        case MAC_KEY_F6:          _glfwInputKey( GLFW_KEY_F6,          action); break;

+        case MAC_KEY_F7:          _glfwInputKey( GLFW_KEY_F7,          action); break;

+        case MAC_KEY_F8:          _glfwInputKey( GLFW_KEY_F8,          action); break;

+        case MAC_KEY_F9:          _glfwInputKey( GLFW_KEY_F9,          action); break;

+        case MAC_KEY_F10:         _glfwInputKey( GLFW_KEY_F10,         action); break;

+        case MAC_KEY_F11:         _glfwInputKey( GLFW_KEY_F11,         action); break;

+        case MAC_KEY_F12:         _glfwInputKey( GLFW_KEY_F12,         action); break;

+        case MAC_KEY_F13:         _glfwInputKey( GLFW_KEY_F13,         action); break;

+        case MAC_KEY_F14:         _glfwInputKey( GLFW_KEY_F14,         action); break;

+        case MAC_KEY_F15:         _glfwInputKey( GLFW_KEY_F15,         action); break;

+        case MAC_KEY_UP:          _glfwInputKey( GLFW_KEY_UP,          action); break;

+        case MAC_KEY_DOWN:        _glfwInputKey( GLFW_KEY_DOWN,        action); break;

+        case MAC_KEY_LEFT:        _glfwInputKey( GLFW_KEY_LEFT,        action); break;

+        case MAC_KEY_RIGHT:       _glfwInputKey( GLFW_KEY_RIGHT,       action); break;

+        case MAC_KEY_TAB:         _glfwInputKey( GLFW_KEY_TAB,         action); break;

+        case MAC_KEY_BACKSPACE:   _glfwInputKey( GLFW_KEY_BACKSPACE,   action); break;

+        case MAC_KEY_HELP:        _glfwInputKey( GLFW_KEY_INSERT,      action); break;

+        case MAC_KEY_DEL:         _glfwInputKey( GLFW_KEY_DEL,         action); break;

+        case MAC_KEY_PAGEUP:      _glfwInputKey( GLFW_KEY_PAGEUP,      action); break;

+        case MAC_KEY_PAGEDOWN:    _glfwInputKey( GLFW_KEY_PAGEDOWN,    action); break;

+        case MAC_KEY_HOME:        _glfwInputKey( GLFW_KEY_HOME,        action); break;

+        case MAC_KEY_END:         _glfwInputKey( GLFW_KEY_END,         action); break;

+        case MAC_KEY_KP_0:        _glfwInputKey( GLFW_KEY_KP_0,        action); break;

+        case MAC_KEY_KP_1:        _glfwInputKey( GLFW_KEY_KP_1,        action); break;

+        case MAC_KEY_KP_2:        _glfwInputKey( GLFW_KEY_KP_2,        action); break;

+        case MAC_KEY_KP_3:        _glfwInputKey( GLFW_KEY_KP_3,        action); break;

+        case MAC_KEY_KP_4:        _glfwInputKey( GLFW_KEY_KP_4,        action); break;

+        case MAC_KEY_KP_5:        _glfwInputKey( GLFW_KEY_KP_5,        action); break;

+        case MAC_KEY_KP_6:        _glfwInputKey( GLFW_KEY_KP_6,        action); break;

+        case MAC_KEY_KP_7:        _glfwInputKey( GLFW_KEY_KP_7,        action); break;

+        case MAC_KEY_KP_8:        _glfwInputKey( GLFW_KEY_KP_8,        action); break;

+        case MAC_KEY_KP_9:        _glfwInputKey( GLFW_KEY_KP_9,        action); break;

+        case MAC_KEY_KP_DIVIDE:   _glfwInputKey( GLFW_KEY_KP_DIVIDE,   action); break;

+        case MAC_KEY_KP_MULTIPLY: _glfwInputKey( GLFW_KEY_KP_MULTIPLY, action); break;

+        case MAC_KEY_KP_SUBTRACT: _glfwInputKey( GLFW_KEY_KP_SUBTRACT, action); break;

+        case MAC_KEY_KP_ADD:      _glfwInputKey( GLFW_KEY_KP_ADD,      action); break;

+        case MAC_KEY_KP_DECIMAL:  _glfwInputKey( GLFW_KEY_KP_DECIMAL,  action); break;

+        case MAC_KEY_KP_EQUAL:    _glfwInputKey( GLFW_KEY_KP_EQUAL,    action); break;

+        case MAC_KEY_KP_ENTER:    _glfwInputKey( GLFW_KEY_KP_ENTER,    action); break;

+        default:

+        {

+            extern void *KCHRPtr;

+            UInt32 state = 0;

+            char charCode = (char)KeyTranslate( KCHRPtr, keyCode, &state );

+            UppercaseText( &charCode, 1, smSystemScript );

+            _glfwInputKey( (unsigned char)charCode, action );

+        }

+        break;

+    }

+}

+

+EventTypeSpec GLFW_KEY_EVENT_TYPES[] =

+{

+    { kEventClassKeyboard, kEventRawKeyDown },

+    { kEventClassKeyboard, kEventRawKeyUp },

+    { kEventClassKeyboard, kEventRawKeyModifiersChanged }

+};

+

+OSStatus _glfwKeyEventHandler( EventHandlerCallRef handlerCallRef,

+                               EventRef event,

+                               void *userData )

+{

+    UInt32 keyCode;

+    short int keyChar;

+    UInt32 modifiers;

+

+    switch( GetEventKind( event ) )

+    {

+        case kEventRawKeyDown:

+        {

+            if( GetEventParameter( event,

+                                   kEventParamKeyCode,

+                                   typeUInt32,

+                                   NULL,

+                                   sizeof( UInt32 ),

+                                   NULL,

+                                   &keyCode ) == noErr )

+            {

+                _glfwHandleMacKeyChange( keyCode, GLFW_PRESS );

+            }

+            if( GetEventParameter( event,

+                                   kEventParamKeyUnicodes,

+                                   typeUnicodeText,

+                                   NULL,

+                                   sizeof(keyChar),

+                                   NULL,

+                                   &keyChar) == noErr )

+            {

+                _glfwInputChar( keyChar, GLFW_PRESS );

+            }

+            return noErr;

+        }

+

+        case kEventRawKeyUp:

+        {

+            if( GetEventParameter( event,

+                                   kEventParamKeyCode,

+                                   typeUInt32,

+                                   NULL,

+                                   sizeof( UInt32 ),

+                                   NULL,

+                                   &keyCode ) == noErr )

+            {

+                _glfwHandleMacKeyChange( keyCode, GLFW_RELEASE );

+            }

+            if( GetEventParameter( event,

+                                   kEventParamKeyUnicodes,

+                                   typeUnicodeText,

+                                   NULL,

+                                   sizeof(keyChar),

+                                   NULL,

+                                   &keyChar) == noErr )

+            {

+                _glfwInputChar( keyChar, GLFW_RELEASE );

+            }

+            return noErr;

+        }

+

+        case kEventRawKeyModifiersChanged:

+        {

+            if( GetEventParameter( event,

+                                   kEventParamKeyModifiers,

+                                   typeUInt32,

+                                   NULL,

+                                   sizeof( UInt32 ),

+                                   NULL,

+                                   &modifiers ) == noErr )

+            {

+                _glfwHandleMacModifierChange( modifiers );

+                return noErr;

+            }

+        }

+        break;

+    }

+

+    return eventNotHandledErr;

+}

+

+EventTypeSpec GLFW_MOUSE_EVENT_TYPES[] =

+{

+    { kEventClassMouse, kEventMouseDown },

+    { kEventClassMouse, kEventMouseUp },

+    { kEventClassMouse, kEventMouseMoved },

+    { kEventClassMouse, kEventMouseDragged },

+    { kEventClassMouse, kEventMouseWheelMoved },

+};

+

+OSStatus _glfwMouseEventHandler( EventHandlerCallRef handlerCallRef,

+                                 EventRef event,

+                                 void *userData )

+{

+    switch( GetEventKind( event ) )

+    {

+        case kEventMouseDown:

+        {

+            WindowRef window;

+            EventRecord oldStyleMacEvent;

+            ConvertEventRefToEventRecord( event, &oldStyleMacEvent );

+            if( FindWindow ( oldStyleMacEvent.where, &window ) == inMenuBar )

+            {

+                MenuSelect( oldStyleMacEvent.where );

+                HiliteMenu(0);

+                return noErr;

+            }

+            else

+            {

+                EventMouseButton button;

+                if( GetEventParameter( event,

+                                       kEventParamMouseButton,

+                                       typeMouseButton,

+                                       NULL,

+                                       sizeof( EventMouseButton ),

+                                       NULL,

+                                       &button ) == noErr )

+                {

+                    button -= kEventMouseButtonPrimary;

+                    if( button <= GLFW_MOUSE_BUTTON_LAST )

+                    {

+                        _glfwInputMouseClick( button

+                                              + GLFW_MOUSE_BUTTON_LEFT,

+                                              GLFW_PRESS );

+                    }

+                    return noErr;

+                }

+            }

+            break;

+        }

+

+        case kEventMouseUp:

+        {

+            EventMouseButton button;

+            if( GetEventParameter( event,

+                                   kEventParamMouseButton,

+                                   typeMouseButton,

+                                   NULL,

+                                   sizeof( EventMouseButton ),

+                                   NULL,

+                                   &button ) == noErr )

+            {

+                button -= kEventMouseButtonPrimary;

+                if( button <= GLFW_MOUSE_BUTTON_LAST )

+                {

+                    _glfwInputMouseClick( button

+                                          + GLFW_MOUSE_BUTTON_LEFT,

+                                          GLFW_RELEASE );

+                }

+                return noErr;

+            }

+            break;

+        }

+

+        case kEventMouseMoved:

+        case kEventMouseDragged:

+        {

+            HIPoint mouseLocation;

+	    if( _glfwWin.MouseLock )

+	    {

+		if( GetEventParameter( event,

+				       kEventParamMouseDelta,

+				       typeHIPoint,

+				       NULL,

+				       sizeof( HIPoint ),

+				       NULL,

+				       &mouseLocation ) != noErr )

+		{

+		    break;

+		}

+

+		_glfwInput.MousePosX += mouseLocation.x;

+		_glfwInput.MousePosY += mouseLocation.y;

+	    }

+	    else

+	    {

+		if( GetEventParameter( event,

+				       kEventParamMouseLocation,

+				       typeHIPoint,

+				       NULL,

+				       sizeof( HIPoint ),

+				       NULL,

+				       &mouseLocation ) != noErr )

+		{

+		    break;

+		}

+

+		_glfwInput.MousePosX = mouseLocation.x;

+		_glfwInput.MousePosY = mouseLocation.y;

+

+		if( !_glfwWin.Fullscreen )

+		{

+		    Rect content;

+		    GetWindowBounds( _glfwWin.MacWindow,

+		                     kWindowContentRgn,

+				     &content );

+

+		    _glfwInput.MousePosX -= content.left;

+		    _glfwInput.MousePosY -= content.top;

+		}

+	    }

+

+	    if( _glfwWin.MousePosCallback )

+	    {

+		_glfwWin.MousePosCallback( _glfwInput.MousePosX,

+					   _glfwInput.MousePosY );

+	    }

+

+            break;

+        }

+

+        case kEventMouseWheelMoved:

+        {

+            EventMouseWheelAxis axis;

+            if( GetEventParameter( event,

+                                   kEventParamMouseWheelAxis,

+                                   typeMouseWheelAxis,

+                                   NULL,

+                                   sizeof( EventMouseWheelAxis ),

+                                   NULL,

+                                   &axis) == noErr )

+            {

+                long wheelDelta;

+                if( axis == kEventMouseWheelAxisY &&

+                    GetEventParameter( event,

+                                       kEventParamMouseWheelDelta,

+                                       typeLongInteger,

+                                       NULL,

+                                       sizeof( long ),

+                                       NULL,

+                                       &wheelDelta ) == noErr )

+                {

+                    _glfwInput.WheelPos += wheelDelta;

+                    if( _glfwWin.MouseWheelCallback )

+                    {

+                        _glfwWin.MouseWheelCallback( _glfwInput.WheelPos );

+                    }

+                    return noErr;

+                }

+            }

+            break;

+        }

+    }

+

+    return eventNotHandledErr;

+}

+

+EventTypeSpec GLFW_COMMAND_EVENT_TYPES[] =

+{

+    { kEventClassCommand, kEventCommandProcess }

+};

+

+OSStatus _glfwCommandHandler( EventHandlerCallRef handlerCallRef,

+                                 EventRef event,

+                                 void *userData )

+{

+    if( _glfwWin.SysKeysDisabled )

+    {

+        // TO DO: give adequate UI feedback that this is the case

+        return eventNotHandledErr;

+    }

+

+    HICommand command;

+    if( GetEventParameter( event,

+                           kEventParamDirectObject,

+                           typeHICommand,

+                           NULL,

+                           sizeof( HICommand ),

+                           NULL,

+                           &command ) == noErr )

+    {

+        switch( command.commandID )

+        {

+            case kHICommandClose:

+            case kHICommandQuit:

+            {

+                // Check if the program wants us to close the window

+                if( _glfwWin.WindowCloseCallback )

+                {

+                    if( _glfwWin.WindowCloseCallback() )

+                    {

+                        glfwCloseWindow();

+                    }

+                }

+                else

+                {

+                    glfwCloseWindow();

+                }

+                return noErr;

+            }

+        }

+    }

+

+    return eventNotHandledErr;

+}

+

+EventTypeSpec GLFW_WINDOW_EVENT_TYPES[] =

+{

+  { kEventClassWindow, kEventWindowBoundsChanged },

+  { kEventClassWindow, kEventWindowClose },

+  { kEventClassWindow, kEventWindowDrawContent },

+  { kEventClassWindow, kEventWindowActivated },

+  { kEventClassWindow, kEventWindowDeactivated },

+};

+

+OSStatus _glfwWindowEventHandler( EventHandlerCallRef handlerCallRef,

+                              EventRef event,

+                              void *userData )

+{

+    switch( GetEventKind(event) )

+    {

+    	case kEventWindowBoundsChanged:

+    	{

+      	    WindowRef window;

+      	    GetEventParameter( event, kEventParamDirectObject, typeWindowRef, NULL,

+			       sizeof(WindowRef), NULL, &window );

+

+      	    Rect rect;

+      	    GetWindowPortBounds( window, &rect );

+

+      	    if( _glfwWin.Width != rect.right ||

+           	_glfwWin.Height != rect.bottom )

+      	    {

+        	aglUpdateContext(_glfwWin.AGLContext);

+

+        	_glfwWin.Width  = rect.right;

+        	_glfwWin.Height = rect.bottom;

+        	if( _glfwWin.WindowSizeCallback )

+        	{

+          	    _glfwWin.WindowSizeCallback( _glfwWin.Width,

+                                                _glfwWin.Height );

+        	}

+        	// Emulate (force) content invalidation

+        	if( _glfwWin.WindowRefreshCallback )

+        	{

+                    _glfwWin.WindowRefreshCallback();

+        	}

+      	    }

+      	    break;

+    	}

+

+    	case kEventWindowClose:

+    	{

+      	    // Check if the program wants us to close the window

+      	    if( _glfwWin.WindowCloseCallback )

+      	    {

+          	if( _glfwWin.WindowCloseCallback() )

+          	{

+              	    glfwCloseWindow();

+          	}

+     	    }

+      	    else

+      	    {

+          	glfwCloseWindow();

+      	    }

+      	    return noErr;

+    	}

+

+    	case kEventWindowDrawContent:

+    	{

+	    // Call user callback function

+            if( _glfwWin.WindowRefreshCallback )

+	    {

+		_glfwWin.WindowRefreshCallback();

+	    }

+	    break;

+        }

+

+	case kEventWindowActivated:

+	{

+	    _glfwWin.Active = GL_TRUE;

+	    break;

+	}

+

+	case kEventWindowDeactivated:

+	{

+	    _glfwWin.Active = GL_FALSE;

+	    _glfwInputDeactivation();

+	    break;

+	}

+    }

+

+    return eventNotHandledErr;

+}

+

+int _glfwInstallEventHandlers( void )

+{

+    OSStatus error;

+

+    _glfwWin.MouseUPP = NewEventHandlerUPP( _glfwMouseEventHandler );

+

+    error = InstallEventHandler( GetApplicationEventTarget(),

+                                 _glfwWin.MouseUPP,

+                                 GetEventTypeCount( GLFW_MOUSE_EVENT_TYPES ),

+                                 GLFW_MOUSE_EVENT_TYPES,

+                                 NULL,

+                                 NULL );

+    if( error != noErr )

+    {

+        fprintf( stderr, "glfwOpenWindow failing because it can't install mouse event handler\n" );

+        return GL_FALSE;

+    }

+

+    _glfwWin.CommandUPP = NewEventHandlerUPP( _glfwCommandHandler );

+

+    error = InstallEventHandler( GetApplicationEventTarget(),

+                                 _glfwWin.CommandUPP,

+                                 GetEventTypeCount( GLFW_COMMAND_EVENT_TYPES ),

+                                 GLFW_COMMAND_EVENT_TYPES,

+                                 NULL,

+                                 NULL );

+    if( error != noErr )

+    {

+        fprintf( stderr, "glfwOpenWindow failing because it can't install command event handler\n" );

+        return GL_FALSE;

+    }

+

+    _glfwWin.KeyboardUPP = NewEventHandlerUPP( _glfwKeyEventHandler );

+

+    error = InstallEventHandler( GetApplicationEventTarget(),

+                                 _glfwWin.KeyboardUPP,

+                                 GetEventTypeCount( GLFW_KEY_EVENT_TYPES ),

+                                 GLFW_KEY_EVENT_TYPES,

+                                 NULL,

+                                 NULL );

+    if( error != noErr )

+    {

+        fprintf( stderr, "glfwOpenWindow failing because it can't install key event handler\n" );

+        return GL_FALSE;

+    }

+

+    return GL_TRUE;

+}

+

+#define _setAGLAttribute( aglAttributeName, AGLparameter ) \

+if ( AGLparameter != 0 ) \

+{ \

+    AGLpixelFormatAttributes[numAGLAttrs++] = aglAttributeName; \

+    AGLpixelFormatAttributes[numAGLAttrs++] = AGLparameter; \

+}

+

+#define _getAGLAttribute( aglAttributeName, variableName ) \

+{ \

+    GLint aglValue; \

+    (void)aglDescribePixelFormat( pixelFormat, aglAttributeName, &aglValue ); \

+    variableName = aglValue; \

+}

+

+#define _setCGLAttribute( cglAttributeName, CGLparameter ) \

+if ( CGLparameter != 0 ) \

+{ \

+    CGLpixelFormatAttributes[ numCGLAttrs++ ] = cglAttributeName; \

+    CGLpixelFormatAttributes[ numCGLAttrs++ ] = CGLparameter; \

+}

+

+#define _getCGLAttribute( cglAttributeName, variableName ) \

+{ \

+    long cglValue; \

+    (void)CGLDescribePixelFormat( CGLpfObj, 0, cglAttributeName, &cglValue ); \

+    variableName = cglValue; \

+}

+

+int  _glfwPlatformOpenWindow( int width,

+                              int height,

+                              int redbits,

+                              int greenbits,

+                              int bluebits,

+                              int alphabits,

+                              int depthbits,

+                              int stencilbits,

+                              int mode,

+                              _GLFWhints* hints )

+{

+    OSStatus error;

+    ProcessSerialNumber psn;

+

+    unsigned int windowAttributes;

+

+    // TO DO: Refactor this function!

+    _glfwWin.WindowFunctions = ( _glfwWin.Fullscreen ?

+                               &_glfwMacFSWindowFunctions :

+                               &_glfwMacDWWindowFunctions );

+

+    // Windowed or fullscreen; AGL or CGL? Quite the mess...

+    // AGL appears to be the only choice for attaching OpenGL contexts to

+    // Carbon windows, but it leaves the user no control over fullscreen

+    // mode stretching. Solution: AGL for windowed, CGL for fullscreen.

+    if( !_glfwWin.Fullscreen )

+    {

+        // create AGL pixel format attribute list

+        GLint AGLpixelFormatAttributes[256];

+        int numAGLAttrs = 0;

+

+        AGLpixelFormatAttributes[numAGLAttrs++] = AGL_RGBA;

+        AGLpixelFormatAttributes[numAGLAttrs++] = AGL_DOUBLEBUFFER;

+

+        if( hints->Stereo )

+        {

+            AGLpixelFormatAttributes[numAGLAttrs++] = AGL_STEREO;

+        }

+

+        _setAGLAttribute( AGL_AUX_BUFFERS,      hints->AuxBuffers);

+        _setAGLAttribute( AGL_RED_SIZE,         redbits );

+        _setAGLAttribute( AGL_GREEN_SIZE,       greenbits );

+        _setAGLAttribute( AGL_BLUE_SIZE,        bluebits );

+        _setAGLAttribute( AGL_ALPHA_SIZE,       alphabits );

+        _setAGLAttribute( AGL_DEPTH_SIZE,       depthbits );

+        _setAGLAttribute( AGL_STENCIL_SIZE,     stencilbits );

+        _setAGLAttribute( AGL_ACCUM_RED_SIZE,   hints->AccumRedBits );

+        _setAGLAttribute( AGL_ACCUM_GREEN_SIZE, hints->AccumGreenBits );

+        _setAGLAttribute( AGL_ACCUM_BLUE_SIZE,  hints->AccumBlueBits );

+        _setAGLAttribute( AGL_ACCUM_ALPHA_SIZE, hints->AccumAlphaBits );

+

+	if( hints->Samples > 1 )

+	{

+	    _setAGLAttribute( AGL_SAMPLE_BUFFERS_ARB, 1 );

+	    _setAGLAttribute( AGL_SAMPLES_ARB, hints->Samples );

+	    AGLpixelFormatAttributes[numAGLAttrs++] = AGL_NO_RECOVERY;

+	}

+

+        AGLpixelFormatAttributes[numAGLAttrs++] = AGL_NONE;

+

+        // create pixel format descriptor

+        AGLDevice mainMonitor = GetMainDevice();

+        AGLPixelFormat pixelFormat = aglChoosePixelFormat( &mainMonitor,

+                                                           1,

+                                                           AGLpixelFormatAttributes );

+        if( pixelFormat == NULL )

+        {

+            fprintf( stderr, "glfwOpenWindow failing because it can't create a pixel format\n" );

+            return GL_FALSE;

+        }

+

+        // store pixel format's values for _glfwPlatformGetWindowParam's use

+        _getAGLAttribute( AGL_ACCELERATED,      _glfwWin.Accelerated );

+        _getAGLAttribute( AGL_RED_SIZE,         _glfwWin.RedBits );

+        _getAGLAttribute( AGL_GREEN_SIZE,       _glfwWin.GreenBits );

+        _getAGLAttribute( AGL_BLUE_SIZE,        _glfwWin.BlueBits );

+        _getAGLAttribute( AGL_ALPHA_SIZE,       _glfwWin.AlphaBits );

+        _getAGLAttribute( AGL_DEPTH_SIZE,       _glfwWin.DepthBits );

+        _getAGLAttribute( AGL_STENCIL_SIZE,     _glfwWin.StencilBits );

+        _getAGLAttribute( AGL_ACCUM_RED_SIZE,   _glfwWin.AccumRedBits );

+        _getAGLAttribute( AGL_ACCUM_GREEN_SIZE, _glfwWin.AccumGreenBits );

+        _getAGLAttribute( AGL_ACCUM_BLUE_SIZE,  _glfwWin.AccumBlueBits );

+        _getAGLAttribute( AGL_ACCUM_ALPHA_SIZE, _glfwWin.AccumAlphaBits );

+        _getAGLAttribute( AGL_AUX_BUFFERS,      _glfwWin.AuxBuffers );

+        _getAGLAttribute( AGL_STEREO,           _glfwWin.Stereo );

+        _getAGLAttribute( AGL_SAMPLES_ARB,      _glfwWin.Samples );

+        _glfwWin.RefreshRate = hints->RefreshRate;

+

+        // create AGL context

+        _glfwWin.AGLContext = aglCreateContext( pixelFormat, NULL );

+

+        aglDestroyPixelFormat( pixelFormat );

+

+        if( _glfwWin.AGLContext == NULL )

+        {

+            fprintf( stderr, "glfwOpenWindow failing because it can't create an OpenGL context\n" );

+            _glfwPlatformCloseWindow();

+            return GL_FALSE;

+        }

+

+        if (_glfwLibrary.Unbundled)

+        {

+            if( GetCurrentProcess( &psn ) != noErr )

+            {

+                fprintf( stderr, "glfwOpenWindow failing because it can't get its PSN\n" );

+                _glfwPlatformCloseWindow();

+                return GL_FALSE;

+            }

+

+    	    if( TransformProcessType( &psn, kProcessTransformToForegroundApplication ) != noErr )

+            {

+                fprintf( stderr, "glfwOpenWindow failing because it can't become a foreground application\n" );

+                _glfwPlatformCloseWindow();

+                return GL_FALSE;

+            }

+            

+            /* Keith Bauer 2007-07-12 - I don't believe this is desirable

+    	    if( SetFrontProcess( &psn ) != noErr )

+            {

+                fprintf( stderr, "glfwOpenWindow failing because it can't become the front process\n" );

+                _glfwPlatformCloseWindow();

+                return GL_FALSE;

+            }

+            */

+        }

+	    

+        // create window

+        Rect windowContentBounds;

+        windowContentBounds.left = 0;

+        windowContentBounds.top = 0;

+        windowContentBounds.right = width;

+        windowContentBounds.bottom = height;

+

+        windowAttributes = ( kWindowCloseBoxAttribute        \

+                           | kWindowCollapseBoxAttribute     \

+                           | kWindowStandardHandlerAttribute );

+

+        if( hints->WindowNoResize )

+        {

+            windowAttributes |= kWindowLiveResizeAttribute;

+        }

+        else

+        {

+            windowAttributes |= ( kWindowFullZoomAttribute | kWindowResizableAttribute );

+        }

+

+        error = CreateNewWindow( kDocumentWindowClass,

+                                 windowAttributes,

+                                 &windowContentBounds,

+                                 &( _glfwWin.MacWindow ) );

+        if( ( error != noErr ) || ( _glfwWin.MacWindow == NULL ) )

+        {

+            fprintf( stderr, "glfwOpenWindow failing because it can't create a window\n" );

+            _glfwPlatformCloseWindow();

+            return GL_FALSE;

+        }

+

+        _glfwWin.WindowUPP = NewEventHandlerUPP( _glfwWindowEventHandler );

+

+        error = InstallWindowEventHandler( _glfwWin.MacWindow,

+                                           _glfwWin.WindowUPP,

+                                           GetEventTypeCount( GLFW_WINDOW_EVENT_TYPES ),

+                                           GLFW_WINDOW_EVENT_TYPES,

+                                           NULL,

+                                           NULL );

+        if( error != noErr )

+        {

+            fprintf( stderr, "glfwOpenWindow failing because it can't install window event handlers\n" );

+            _glfwPlatformCloseWindow();

+            return GL_FALSE;

+        }

+

+        // Don't care if we fail here

+        (void)SetWindowTitleWithCFString( _glfwWin.MacWindow, CFSTR( "GLFW Window" ) );

+        (void)RepositionWindow( _glfwWin.MacWindow,

+                                NULL,

+                                kWindowCenterOnMainScreen );

+

+        if( !aglSetDrawable( _glfwWin.AGLContext,

+                             GetWindowPort( _glfwWin.MacWindow ) ) )

+        {

+            fprintf( stderr, "glfwOpenWindow failing because it can't draw to the window\n" );

+            _glfwPlatformCloseWindow();

+            return GL_FALSE;

+        }

+

+        // Make OpenGL context current

+        if( !aglSetCurrentContext( _glfwWin.AGLContext ) )

+        {

+            fprintf( stderr, "glfwOpenWindow failing because it can't make the OpenGL context current\n" );

+            _glfwPlatformCloseWindow();

+            return GL_FALSE;

+        }

+

+        // show window

+        ShowWindow( _glfwWin.MacWindow );

+

+        return GL_TRUE;

+    }

+    else

+    {

+        CGDisplayErr cgErr;

+        CGLError cglErr;

+

+        CFDictionaryRef optimalMode;

+

+        CGLPixelFormatObj CGLpfObj;

+        long numCGLvs = 0;

+

+        CGLPixelFormatAttribute CGLpixelFormatAttributes[64];

+        int numCGLAttrs = 0;

+

+        // variables for enumerating color depths

+        long rgbColorDepth;

+        long rgbaAccumDepth = 0;

+        int rgbChannelDepth = 0;

+

+        // CGL pixel format attributes

+        _setCGLAttribute( kCGLPFADisplayMask,

+                          CGDisplayIDToOpenGLDisplayMask( kCGDirectMainDisplay ) );

+

+        if( hints->Stereo )

+        {

+            CGLpixelFormatAttributes[ numCGLAttrs++ ] = kCGLPFAStereo;

+        }

+

+	if( hints->Samples > 1 )

+	{

+	    _setCGLAttribute( kCGLPFASamples,       (CGLPixelFormatAttribute)hints->Samples );

+	    _setCGLAttribute( kCGLPFASampleBuffers, (CGLPixelFormatAttribute)1 );

+	    CGLpixelFormatAttributes[ numCGLAttrs++ ] = kCGLPFANoRecovery;

+	}

+

+        CGLpixelFormatAttributes[ numCGLAttrs++ ]     = kCGLPFAFullScreen;

+        CGLpixelFormatAttributes[ numCGLAttrs++ ]     = kCGLPFADoubleBuffer;

+        CGLpixelFormatAttributes[ numCGLAttrs++ ]     = kCGLPFAAccelerated;

+        CGLpixelFormatAttributes[ numCGLAttrs++ ]     = kCGLPFANoRecovery;

+        CGLpixelFormatAttributes[ numCGLAttrs++ ]     = kCGLPFAMinimumPolicy;

+

+        _setCGLAttribute( kCGLPFAAccumSize,

+                          (CGLPixelFormatAttribute)( hints->AccumRedBits \

+                                                   + hints->AccumGreenBits \

+                                                   + hints->AccumBlueBits \

+                                                   + hints->AccumAlphaBits ) );

+

+        _setCGLAttribute( kCGLPFAAlphaSize,   (CGLPixelFormatAttribute)alphabits );

+        _setCGLAttribute( kCGLPFADepthSize,   (CGLPixelFormatAttribute)depthbits );

+        _setCGLAttribute( kCGLPFAStencilSize, (CGLPixelFormatAttribute)stencilbits );

+        _setCGLAttribute( kCGLPFAAuxBuffers,  (CGLPixelFormatAttribute)hints->AuxBuffers );

+

+        CGLpixelFormatAttributes[ numCGLAttrs++ ]     = (CGLPixelFormatAttribute)NULL;

+

+        // create a suitable pixel format with above attributes..

+        cglErr = CGLChoosePixelFormat( CGLpixelFormatAttributes,

+                                       &CGLpfObj,

+                                       &numCGLvs );

+        if( cglErr != kCGLNoError )

+	{

+	    return GL_FALSE;

+	}

+

+        // ..and create a rendering context using that pixel format

+        cglErr = CGLCreateContext( CGLpfObj, NULL, &_glfwWin.CGLContext );

+        if( cglErr != kCGLNoError )

+	{

+	    return GL_FALSE;

+	}

+

+        // enumerate depth of RGB channels - unlike AGL, CGL works with

+        // a single parameter reflecting the full depth of the frame buffer

+        (void)CGLDescribePixelFormat( CGLpfObj, 0, kCGLPFAColorSize, &rgbColorDepth );

+        if( rgbColorDepth == 24 || rgbColorDepth == 32 )

+	{

+	    rgbChannelDepth = 8;

+	}

+        if( rgbColorDepth == 16 )

+	{

+	    rgbChannelDepth = 5;

+	}

+

+        // get pixel depth of accumulator - I haven't got the slightest idea

+        // how this number conforms to any other channel depth than 8 bits,

+        // so this might end up giving completely knackered results...

+        (void)CGLDescribePixelFormat( CGLpfObj, 0, kCGLPFAAccumSize, &rgbaAccumDepth );

+        if( rgbaAccumDepth == 32 )

+	{

+	    rgbaAccumDepth = 8;

+	}

+

+        // store values of pixel format for _glfwPlatformGetWindowParam's use

+        _getCGLAttribute( kCGLPFAAccelerated, _glfwWin.Accelerated );

+        _getCGLAttribute( rgbChannelDepth,    _glfwWin.RedBits );

+        _getCGLAttribute( rgbChannelDepth,    _glfwWin.GreenBits );

+        _getCGLAttribute( rgbChannelDepth,    _glfwWin.BlueBits );

+        _getCGLAttribute( kCGLPFAAlphaSize,   _glfwWin.AlphaBits );

+        _getCGLAttribute( kCGLPFADepthSize,   _glfwWin.DepthBits );

+        _getCGLAttribute( kCGLPFAStencilSize, _glfwWin.StencilBits );

+        _getCGLAttribute( rgbaAccumDepth,     _glfwWin.AccumRedBits );

+        _getCGLAttribute( rgbaAccumDepth,     _glfwWin.AccumGreenBits );

+        _getCGLAttribute( rgbaAccumDepth,     _glfwWin.AccumBlueBits );

+        _getCGLAttribute( rgbaAccumDepth,     _glfwWin.AccumAlphaBits );

+        _getCGLAttribute( kCGLPFAAuxBuffers,  _glfwWin.AuxBuffers );

+        _getCGLAttribute( kCGLPFAStereo,      _glfwWin.Stereo );

+        _glfwWin.RefreshRate = hints->RefreshRate;

+

+        // destroy our pixel format

+        (void)CGLDestroyPixelFormat( CGLpfObj );

+

+        // capture the display for our application

+        cgErr = CGCaptureAllDisplays();

+        if( cgErr != kCGErrorSuccess )

+	{

+	    return GL_FALSE;

+	}

+

+        // find closest matching NON-STRETCHED display mode..

+        optimalMode = CGDisplayBestModeForParametersAndRefreshRateWithProperty( kCGDirectMainDisplay,

+	                                                                            rgbColorDepth,

+	                                                                            width,

+	/* Check further to the right -> */                                         height,

+	                                                                            hints->RefreshRate,

+	                                                                            NULL,

+	                                                                            NULL );

+        if( optimalMode == NULL )

+	{

+	    return GL_FALSE;

+	}

+

+        // ..and switch to that mode

+        cgErr = CGDisplaySwitchToMode( kCGDirectMainDisplay, optimalMode );

+        if( cgErr != kCGErrorSuccess )

+	{

+	    return GL_FALSE;

+	}

+

+        // switch to our OpenGL context, and bring it up fullscreen

+        cglErr = CGLSetCurrentContext( _glfwWin.CGLContext );

+        if( cglErr != kCGLNoError )

+	{

+	    return GL_FALSE;

+	}

+

+        cglErr = CGLSetFullScreen( _glfwWin.CGLContext );

+        if( cglErr != kCGLNoError )

+	{

+	    return GL_FALSE;

+	}

+

+        return GL_TRUE;

+    }

+}

+

+void _glfwPlatformCloseWindow( void )

+{

+    if( _glfwWin.WindowFunctions != NULL )

+    {

+        if( _glfwWin.WindowUPP != NULL )

+        {

+            DisposeEventHandlerUPP( _glfwWin.WindowUPP );

+            _glfwWin.WindowUPP = NULL;

+        }

+

+        _glfwWin.WindowFunctions->CloseWindow();

+

+        if( !_glfwWin.Fullscreen && _glfwWin.AGLContext != NULL )

+        {

+            aglSetCurrentContext( NULL );

+            aglSetDrawable( _glfwWin.AGLContext, NULL );

+            aglDestroyContext( _glfwWin.AGLContext );

+            _glfwWin.AGLContext = NULL;

+        }

+

+        if( _glfwWin.Fullscreen && _glfwWin.CGLContext != NULL )

+        {

+            CGLSetCurrentContext( NULL );

+            CGLClearDrawable( _glfwWin.CGLContext );

+            CGLDestroyContext( _glfwWin.CGLContext );

+            CGReleaseAllDisplays();

+            _glfwWin.CGLContext = NULL;

+        }

+

+        if( _glfwWin.MacWindow != NULL )

+        {

+            ReleaseWindow( _glfwWin.MacWindow );

+            _glfwWin.MacWindow = NULL;

+        }

+

+        _glfwWin.WindowFunctions = NULL;

+    }

+}

+

+void _glfwPlatformSetWindowTitle( const char *title )

+{

+    _glfwWin.WindowFunctions->SetWindowTitle( title );

+}

+

+void _glfwPlatformSetWindowSize( int width, int height )

+{

+    _glfwWin.WindowFunctions->SetWindowSize( width, height );

+}

+

+void _glfwPlatformSetWindowPos( int x, int y )

+{

+    _glfwWin.WindowFunctions->SetWindowPos( x, y );

+}

+

+void _glfwPlatformIconifyWindow( void )

+{

+    _glfwWin.WindowFunctions->IconifyWindow();

+}

+

+void _glfwPlatformRestoreWindow( void )

+{

+    _glfwWin.WindowFunctions->RestoreWindow();

+}

+

+void _glfwPlatformSwapBuffers( void )

+{

+    if( !_glfwWin.Fullscreen )

+    {

+        aglSwapBuffers( _glfwWin.AGLContext );

+    }

+    else

+    {

+        CGLFlushDrawable( _glfwWin.CGLContext );

+    }

+}

+

+void _glfwPlatformSwapInterval( int interval )

+{

+    GLint AGLparameter = interval;

+

+    // CGL doesn't seem to like intervals other than 0 (vsync off) or 1 (vsync on)

+    long CGLparameter = ( interval == 0 ? 0 : 1 );

+

+    if( !_glfwWin.Fullscreen )

+    {

+        // Don't care if we fail here..

+        (void)aglSetInteger( _glfwWin.AGLContext,

+                             AGL_SWAP_INTERVAL,

+                             &AGLparameter );

+    }

+    else

+    {

+        // ..or here

+        (void)CGLSetParameter( _glfwWin.CGLContext,

+                               kCGLCPSwapInterval,

+                               &CGLparameter );

+    }

+}

+

+void _glfwPlatformRefreshWindowParams( void )

+{

+    _glfwWin.WindowFunctions->RefreshWindowParams();

+}

+

+int _glfwPlatformGetWindowParam( int param )

+{

+    switch ( param )

+    {

+        case GLFW_ACCELERATED:      return _glfwWin.Accelerated;    break;

+        case GLFW_RED_BITS:         return _glfwWin.RedBits;        break;

+        case GLFW_GREEN_BITS:       return _glfwWin.GreenBits;      break;

+        case GLFW_BLUE_BITS:        return _glfwWin.BlueBits;       break;

+        case GLFW_ALPHA_BITS:       return _glfwWin.AlphaBits;      break;

+        case GLFW_DEPTH_BITS:       return _glfwWin.DepthBits;      break;

+        case GLFW_STENCIL_BITS:     return _glfwWin.StencilBits;    break;

+        case GLFW_ACCUM_RED_BITS:   return _glfwWin.AccumRedBits;   break;

+        case GLFW_ACCUM_GREEN_BITS: return _glfwWin.AccumGreenBits; break;

+        case GLFW_ACCUM_BLUE_BITS:  return _glfwWin.AccumBlueBits;  break;

+        case GLFW_ACCUM_ALPHA_BITS: return _glfwWin.AccumAlphaBits; break;

+        case GLFW_AUX_BUFFERS:      return _glfwWin.AuxBuffers;     break;

+        case GLFW_STEREO:           return _glfwWin.Stereo;         break;

+        case GLFW_REFRESH_RATE:     return _glfwWin.RefreshRate;    break;

+        default:                    return GL_FALSE;

+    }

+}

+

+void _glfwPlatformPollEvents( void )

+{

+    EventRef event;

+    EventTargetRef eventDispatcher = GetEventDispatcherTarget();

+

+    while ( ReceiveNextEvent( 0, NULL, 0.0, TRUE, &event ) == noErr )

+    {

+        SendEventToEventTarget( event, eventDispatcher );

+        ReleaseEvent( event );

+    }

+}

+

+void _glfwPlatformWaitEvents( void )

+{

+    EventRef event;

+

+    // Wait for new events

+    ReceiveNextEvent( 0, NULL, kEventDurationForever, FALSE, &event );

+

+    // Poll new events

+    _glfwPlatformPollEvents();

+}

+

+void _glfwPlatformHideMouseCursor( void )

+{

+    // TO DO: What if we fail here?

+    CGDisplayHideCursor( kCGDirectMainDisplay );

+    CGAssociateMouseAndMouseCursorPosition( false );

+}

+

+void _glfwPlatformShowMouseCursor( void )

+{

+    // TO DO: What if we fail here?

+    CGDisplayShowCursor( kCGDirectMainDisplay );

+    CGAssociateMouseAndMouseCursorPosition( true );

+}

+

+void _glfwPlatformSetMouseCursorPos( int x, int y )

+{

+    _glfwWin.WindowFunctions->SetMouseCursorPos( x, y );

+}

+

+int _glfwMacFSOpenWindow( int width,

+                          int height,

+                          int redbits,

+                          int greenbits,

+                          int bluebits,

+                          int alphabits,

+                          int depthbits,

+                          int stencilbits,

+                          int accumredbits,

+                          int accumgreenbits,

+                          int accumbluebits,

+                          int accumalphabits,

+                          int auxbuffers,

+                          int stereo,

+                          int refreshrate )

+{

+    return GL_FALSE;

+}

+

+void _glfwMacFSCloseWindow( void )

+{

+    // TO DO: un-capture displays, &c.

+}

+

+void _glfwMacFSSetWindowTitle( const char *title )

+{

+    // no-op really, change "fake" mini-window title

+    _glfwMacDWSetWindowTitle( title );

+}

+

+void _glfwMacFSSetWindowSize( int width, int height )

+{

+    // TO DO: something funky for full-screen

+    _glfwMacDWSetWindowSize( width, height );

+}

+

+void _glfwMacFSSetWindowPos( int x, int y )

+{

+    // no-op really, change "fake" mini-window position

+    _glfwMacDWSetWindowPos( x, y );

+}

+

+void _glfwMacFSIconifyWindow( void )

+{

+    // TO DO: Something funky for full-screen

+    _glfwMacDWIconifyWindow();

+}

+

+void _glfwMacFSRestoreWindow( void )

+{

+    _glfwMacDWRestoreWindow();

+    // TO DO: Something funky for full-screen

+}

+

+void _glfwMacFSRefreshWindowParams( void )

+{

+    // TO DO: implement this!

+}

+

+void _glfwMacFSSetMouseCursorPos( int x, int y )

+{

+    // TO DO: what if we fail here?

+    CGDisplayMoveCursorToPoint( kCGDirectMainDisplay,

+                                CGPointMake( x, y ) );

+}

+

+int  _glfwMacDWOpenWindow( int width,

+                           int height,

+                           int redbits,

+                           int greenbits,

+                           int bluebits,

+                           int alphabits,

+                           int depthbits,

+                           int stencilbits,

+                           int accumredbits,

+                           int accumgreenbits,

+                           int accumbluebits,

+                           int accumalphabits,

+                           int auxbuffers,

+                           int stereo,

+                           int refreshrate )

+{

+    return GL_FALSE;

+}

+

+void _glfwMacDWCloseWindow( void )

+{

+}

+

+void _glfwMacDWSetWindowTitle( const char *title )

+{

+    CFStringRef windowTitle = CFStringCreateWithCString( kCFAllocatorDefault,

+                                                         title,

+                                                         kCFStringEncodingISOLatin1 );

+

+    // Don't care if we fail

+    (void)SetWindowTitleWithCFString( _glfwWin.MacWindow, windowTitle );

+

+    CFRelease( windowTitle );

+}

+

+void _glfwMacDWSetWindowSize( int width, int height )

+{

+    SizeWindow( _glfwWin.MacWindow,

+                width,

+                height,

+                TRUE );

+}

+

+void _glfwMacDWSetWindowPos( int x, int y )

+{

+    // TO DO: take main monitor bounds into account

+    MoveWindow( _glfwWin.MacWindow,

+                x,

+                y,

+                FALSE );

+}

+

+void _glfwMacDWIconifyWindow( void )

+{

+    // TO DO: What if we fail here?

+    (void)CollapseWindow( _glfwWin.MacWindow,

+                          TRUE );

+}

+

+void _glfwMacDWRestoreWindow( void )

+{

+    // TO DO: What if we fail here?

+    (void)CollapseWindow( _glfwWin.MacWindow,

+                          FALSE );

+}

+

+void _glfwMacDWRefreshWindowParams( void )

+{

+    // TO DO: implement this!

+}

+

+void _glfwMacDWSetMouseCursorPos( int x, int y )

+{

+    Rect content;

+    GetWindowBounds(_glfwWin.MacWindow, kWindowContentRgn, &content);

+

+    _glfwInput.MousePosX = x + content.left;

+    _glfwInput.MousePosY = y + content.top;

+

+    CGDisplayMoveCursorToPoint( kCGDirectMainDisplay,

+			        CGPointMake( _glfwInput.MousePosX,

+					     _glfwInput.MousePosY ) );

+}

+

diff --git a/src/engine/external/glfw/lib/macosx/platform.h b/src/engine/external/glfw/lib/macosx/platform.h
new file mode 100644
index 00000000..6f90df88
--- /dev/null
+++ b/src/engine/external/glfw/lib/macosx/platform.h
@@ -0,0 +1,349 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        platform.h

+// Platform:    Mac OS X

+// API Version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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 _platform_h_

+#define _platform_h_

+

+

+// This is the Mac OS X version of GLFW

+#define _GLFW_MAC_OS_X

+

+

+// Include files

+#include <Carbon/Carbon.h>

+#include <OpenGL/OpenGL.h>

+#include <AGL/agl.h>

+#include <sched.h>

+#include <pthread.h>

+#include <sys/sysctl.h>

+#include "../../include/GL/glfw.h"

+

+

+//========================================================================

+// Defines

+//========================================================================

+

+#define _GLFW_MAX_PATH_LENGTH (8192)

+

+#define MAC_KEY_ENTER       0x24

+#define MAC_KEY_RETURN      0x34

+#define MAC_KEY_ESC         0x35

+#define MAC_KEY_F1          0x7A

+#define MAC_KEY_F2          0x78

+#define MAC_KEY_F3          0x63

+#define MAC_KEY_F4          0x76

+#define MAC_KEY_F5          0x60

+#define MAC_KEY_F6          0x61

+#define MAC_KEY_F7          0x62

+#define MAC_KEY_F8          0x64

+#define MAC_KEY_F9          0x65

+#define MAC_KEY_F10         0x6D

+#define MAC_KEY_F11         0x67

+#define MAC_KEY_F12         0x6F

+#define MAC_KEY_F13         0x69

+#define MAC_KEY_F14         0x6B

+#define MAC_KEY_F15         0x71

+#define MAC_KEY_UP          0x7E

+#define MAC_KEY_DOWN        0x7D

+#define MAC_KEY_LEFT        0x7B

+#define MAC_KEY_RIGHT       0x7C

+#define MAC_KEY_TAB         0x30

+#define MAC_KEY_BACKSPACE   0x33

+#define MAC_KEY_HELP        0x72

+#define MAC_KEY_DEL         0x75

+#define MAC_KEY_PAGEUP      0x74

+#define MAC_KEY_PAGEDOWN    0x79

+#define MAC_KEY_HOME        0x73

+#define MAC_KEY_END         0x77

+#define MAC_KEY_KP_0        0x52

+#define MAC_KEY_KP_1        0x53

+#define MAC_KEY_KP_2        0x54

+#define MAC_KEY_KP_3        0x55

+#define MAC_KEY_KP_4        0x56

+#define MAC_KEY_KP_5        0x57

+#define MAC_KEY_KP_6        0x58

+#define MAC_KEY_KP_7        0x59

+#define MAC_KEY_KP_8        0x5B

+#define MAC_KEY_KP_9        0x5C

+#define MAC_KEY_KP_DIVIDE   0x4B

+#define MAC_KEY_KP_MULTIPLY 0x43

+#define MAC_KEY_KP_SUBTRACT 0x4E

+#define MAC_KEY_KP_ADD      0x45

+#define MAC_KEY_KP_DECIMAL  0x41

+#define MAC_KEY_KP_EQUAL    0x51

+#define MAC_KEY_KP_ENTER    0x4C

+

+//========================================================================

+// full-screen/desktop-window "virtual" function table

+//========================================================================

+

+typedef int  ( * GLFWmacopenwindowfun )( int, int, int, int, int, int, int, int, int, int, int, int, int, int, int );

+typedef void ( * GLFWmacclosewindowfun )( void );

+typedef void ( * GLFWmacsetwindowtitlefun )( const char * );

+typedef void ( * GLFWmacsetwindowsizefun )( int, int );

+typedef void ( * GLFWmacsetwindowposfun )( int, int );

+typedef void ( * GLFWmaciconifywindowfun )( void );

+typedef void ( * GLFWmacrestorewindowfun )( void );

+typedef void ( * GLFWmacrefreshwindowparamsfun )( void );

+typedef void ( * GLFWmacsetmousecursorposfun )( int, int );

+

+typedef struct

+{

+    GLFWmacopenwindowfun          OpenWindow;

+    GLFWmacclosewindowfun         CloseWindow;

+    GLFWmacsetwindowtitlefun      SetWindowTitle;

+    GLFWmacsetwindowsizefun       SetWindowSize;

+    GLFWmacsetwindowposfun        SetWindowPos;

+    GLFWmaciconifywindowfun       IconifyWindow;

+    GLFWmacrestorewindowfun       RestoreWindow;

+    GLFWmacrefreshwindowparamsfun RefreshWindowParams;

+    GLFWmacsetmousecursorposfun   SetMouseCursorPos;

+}

+_GLFWmacwindowfunctions;

+

+

+//========================================================================

+// Global variables (GLFW internals)

+//========================================================================

+

+GLFWGLOBAL CFDictionaryRef _glfwDesktopVideoMode;

+

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

+// Window structure

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

+typedef struct _GLFWwin_struct _GLFWwin;

+

+struct _GLFWwin_struct {

+

+    // ========= PLATFORM INDEPENDENT MANDATORY PART =========================

+

+    // Window states

+    int       Opened;          // Flag telling if window is opened or not

+    int       Active;          // Application active flag

+    int       Iconified;       // Window iconified flag

+

+    // User callback functions

+    GLFWwindowsizefun    WindowSizeCallback;

+    GLFWwindowclosefun   WindowCloseCallback;

+    GLFWwindowrefreshfun WindowRefreshCallback;

+    GLFWmousebuttonfun   MouseButtonCallback;

+    GLFWmouseposfun      MousePosCallback;

+    GLFWmousewheelfun    MouseWheelCallback;

+    GLFWkeyfun           KeyCallback;

+    GLFWcharfun          CharCallback;

+

+    // User selected window settings

+    int       Fullscreen;      // Fullscreen flag

+    int       MouseLock;       // Mouse-lock flag

+    int       AutoPollEvents;  // Auto polling flag

+    int       SysKeysDisabled; // System keys disabled flag

+    int       RefreshRate;     // Refresh rate (for fullscreen mode)

+    int       WindowNoResize;  // Resize- and maximize gadgets disabled flag

+    int	      Samples;

+

+    // Window status

+    int       Width, Height;   // Window width and heigth

+

+    // Extensions & OpenGL version

+    int       Has_GL_SGIS_generate_mipmap;

+    int       Has_GL_ARB_texture_non_power_of_two;

+    int       GLVerMajor,GLVerMinor;

+

+

+    // ========= PLATFORM SPECIFIC PART ======================================

+

+    WindowRef               MacWindow;

+    AGLContext              AGLContext;

+    CGLContextObj           CGLContext;

+

+    EventHandlerUPP         MouseUPP;

+    EventHandlerUPP         CommandUPP;

+    EventHandlerUPP         KeyboardUPP;

+    EventHandlerUPP         WindowUPP;

+

+    _GLFWmacwindowfunctions* WindowFunctions;

+

+    // for easy access by _glfwPlatformGetWindowParam

+    int Accelerated;

+    int RedBits, GreenBits, BlueBits, AlphaBits;

+    int DepthBits;

+    int StencilBits;

+    int AccumRedBits, AccumGreenBits, AccumBlueBits, AccumAlphaBits;

+    int AuxBuffers;

+    int Stereo;

+};

+

+GLFWGLOBAL _GLFWwin _glfwWin;

+

+

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

+// User input status (some of this should go in _GLFWwin)

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

+GLFWGLOBAL struct {

+

+    // ========= PLATFORM INDEPENDENT MANDATORY PART =========================

+

+    // Mouse status

+    int  MousePosX, MousePosY;

+    int  WheelPos;

+    char MouseButton[ GLFW_MOUSE_BUTTON_LAST+1 ];

+

+    // Keyboard status

+    char Key[ GLFW_KEY_LAST+1 ];

+    int  LastChar;

+

+    // User selected settings

+    int  StickyKeys;

+    int  StickyMouseButtons;

+    int  KeyRepeat;

+

+

+    // ========= PLATFORM SPECIFIC PART ======================================

+

+    UInt32 Modifiers;

+

+} _glfwInput;

+

+

+

+

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

+// Thread information

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

+typedef struct _GLFWthread_struct _GLFWthread;

+

+// Thread record (one for each thread)

+struct _GLFWthread_struct {

+    // Pointer to previous and next threads in linked list

+    _GLFWthread   *Previous, *Next;

+

+    // GLFW user side thread information

+    GLFWthread    ID;

+    GLFWthreadfun Function;

+

+    // System side thread information

+    pthread_t     PosixID;

+};

+

+// General thread information

+GLFWGLOBAL struct {

+    // Critical section lock

+    pthread_mutex_t  CriticalSection;

+

+    // Next thread ID to use (increments for every created thread)

+    GLFWthread       NextID;

+

+    // First thread in linked list (always the main thread)

+    _GLFWthread      First;

+} _glfwThrd;

+

+

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

+// Library global data

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

+GLFWGLOBAL struct {

+

+    // Timer data

+    struct {

+	double       t0;

+    } Timer;

+

+    struct {

+	    // Bundle for dynamically-loading extension function pointers

+    	CFBundleRef OpenGLFramework;

+    } Libs;

+    

+    int Unbundled;

+    

+} _glfwLibrary;

+

+

+

+//========================================================================

+// Macros for encapsulating critical code sections (i.e. making parts

+// of GLFW thread safe)

+//========================================================================

+

+// Define so we can use the same thread code as X11

+#define _glfw_numprocessors(n) { \

+    int mib[2], ncpu; \

+    size_t len = 1; \

+    mib[0] = CTL_HW; \

+    mib[1] = HW_NCPU; \

+    n      = 1; \

+    if( sysctl( mib, 2, &ncpu, &len, NULL, 0 ) != -1 ) \

+    { \

+        if( len > 0 ) \

+        { \

+            n = ncpu; \

+        } \

+    } \

+}

+

+// Thread list management

+#define ENTER_THREAD_CRITICAL_SECTION \

+pthread_mutex_lock( &_glfwThrd.CriticalSection );

+#define LEAVE_THREAD_CRITICAL_SECTION \

+pthread_mutex_unlock( &_glfwThrd.CriticalSection );

+

+

+//========================================================================

+// Prototypes for platform specific internal functions

+//========================================================================

+

+void  _glfwChangeToResourcesDirectory( void );

+

+int  _glfwInstallEventHandlers( void );

+

+//========================================================================

+// Prototypes for full-screen/desktop-window "virtual" functions

+//========================================================================

+

+int  _glfwMacFSOpenWindow( int width, int height, int redbits, int greenbits, int bluebits, int alphabits, int depthbits, int stencilbits, int accumredbits, int accumgreenbits, int accumbluebits, int accumalphabits, int auxbuffers, int stereo, int refreshrate );

+void _glfwMacFSCloseWindow( void );

+void _glfwMacFSSetWindowTitle( const char *title );

+void _glfwMacFSSetWindowSize( int width, int height );

+void _glfwMacFSSetWindowPos( int x, int y );

+void _glfwMacFSIconifyWindow( void );

+void _glfwMacFSRestoreWindow( void );

+void _glfwMacFSRefreshWindowParams( void );

+void _glfwMacFSSetMouseCursorPos( int x, int y );

+

+int  _glfwMacDWOpenWindow( int width, int height, int redbits, int greenbits, int bluebits, int alphabits, int depthbits, int stencilbits, int accumredbits, int accumgreenbits, int accumbluebits, int accumalphabits, int auxbuffers, int stereo, int refreshrate );

+void _glfwMacDWCloseWindow( void );

+void _glfwMacDWSetWindowTitle( const char *title );

+void _glfwMacDWSetWindowSize( int width, int height );

+void _glfwMacDWSetWindowPos( int x, int y );

+void _glfwMacDWIconifyWindow( void );

+void _glfwMacDWRestoreWindow( void );

+void _glfwMacDWRefreshWindowParams( void );

+void _glfwMacDWSetMouseCursorPos( int x, int y );

+

+#endif // _platform_h_

diff --git a/src/engine/external/glfw/lib/stream.c b/src/engine/external/glfw/lib/stream.c
new file mode 100644
index 00000000..34f75c85
--- /dev/null
+++ b/src/engine/external/glfw/lib/stream.c
@@ -0,0 +1,194 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        stream.c

+// Platform:    Any

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+

+#include "internal.h"

+

+

+//========================================================================

+// Opens a GLFW stream with a file

+//========================================================================

+

+int _glfwOpenFileStream( _GLFWstream *stream, const char* name, const char* mode )

+{

+    memset( stream, 0, sizeof(_GLFWstream) );

+

+    stream->File = fopen( name, mode );

+    if( stream->File == NULL )

+    {

+	return GL_FALSE;

+    }

+

+    return GL_TRUE;

+}

+

+

+//========================================================================

+// Opens a GLFW stream with a memory block

+//========================================================================

+

+int _glfwOpenBufferStream( _GLFWstream *stream, void *data, long size )

+{

+    memset( stream, 0, sizeof(_GLFWstream) );

+

+    stream->Data = data;

+    stream->Size = size;

+    return GL_TRUE;

+}

+

+

+//========================================================================

+// Reads data from a GLFW stream

+//========================================================================

+

+long _glfwReadStream( _GLFWstream *stream, void *data, long size )

+{

+    if( stream->File != NULL )

+    {

+	return fread( data, 1, size, stream->File );

+    }

+

+    if( stream->Data != NULL )

+    {

+	// Check for EOF

+	if( stream->Position == stream->Size )

+	{

+	    return 0;

+	}

+

+	// Clamp read size to available data

+	if( stream->Position + size > stream->Size )

+	{

+	    size = stream->Size - stream->Position;

+	}

+	

+	// Perform data read

+	memcpy( data, (unsigned char*) stream->Data + stream->Position, size );

+	stream->Position += size;

+	return size;

+    }

+

+    return 0;

+}

+

+

+//========================================================================

+// Returns the current position of a GLFW stream

+//========================================================================

+

+long _glfwTellStream( _GLFWstream *stream )

+{

+    if( stream->File != NULL )

+    {

+	return ftell( stream->File );

+    }

+

+    if( stream->Data != NULL )

+    {

+	return stream->Position;

+    }

+

+    return 0;

+}

+

+

+//========================================================================

+// Sets the current position of a GLFW stream

+//========================================================================

+

+int _glfwSeekStream( _GLFWstream *stream, long offset, int whence )

+{

+    long position;

+

+    if( stream->File != NULL )

+    {

+	if( fseek( stream->File, offset, whence ) != 0 )

+	{

+	    return GL_FALSE;

+	}

+

+	return GL_TRUE;

+    }

+

+    if( stream->Data != NULL )

+    {

+	position = offset;

+

+	// Handle whence parameter

+	if( whence == SEEK_CUR )

+	{

+	    position += stream->Position;

+	}

+	else if( whence == SEEK_END )

+	{

+	    position += stream->Size;

+	}

+	else if( whence != SEEK_SET )

+	{

+	    return GL_FALSE;

+	}

+

+	// Clamp offset to buffer bounds and apply it

+	if( position > stream->Size )

+	{

+	    stream->Position = stream->Size;

+	}

+	else if( position < 0 )

+	{

+	    stream->Position = 0;

+	}

+	else

+	{

+	    stream->Position = position;

+	}

+	

+	return GL_TRUE;

+    }

+

+    return GL_FALSE;

+}

+

+

+//========================================================================

+// Closes a GLFW stream

+//========================================================================

+

+void _glfwCloseStream( _GLFWstream *stream )

+{

+    if( stream->File != NULL )

+    {

+	fclose( stream->File );

+    }

+

+    // Nothing to be done about (user allocated) memory blocks

+

+    memset( stream, 0, sizeof(_GLFWstream) );

+}

+

diff --git a/src/engine/external/glfw/lib/tga.c b/src/engine/external/glfw/lib/tga.c
new file mode 100644
index 00000000..51e73844
--- /dev/null
+++ b/src/engine/external/glfw/lib/tga.c
@@ -0,0 +1,405 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        tga.c

+// Platform:    Any

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+//========================================================================

+// Description:

+//

+// TGA format image file loader. This module supports version 1 Targa

+// images, with these restrictions:

+//  - Pixel format may only be 8, 24 or 32 bits

+//  - Colormaps must be no longer than 256 entries

+//

+//========================================================================

+

+

+#include "internal.h"

+

+

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

+//****            GLFW internal functions & declarations              ****

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

+

+//========================================================================

+// TGA file header information

+//========================================================================

+

+typedef struct {

+    int idlen;                 // 1 byte

+    int cmaptype;              // 1 byte

+    int imagetype;             // 1 byte

+    int cmapfirstidx;          // 2 bytes

+    int cmaplen;               // 2 bytes

+    int cmapentrysize;         // 1 byte

+    int xorigin;               // 2 bytes

+    int yorigin;               // 2 bytes

+    int width;                 // 2 bytes

+    int height;                // 2 bytes

+    int bitsperpixel;          // 1 byte

+    int imageinfo;             // 1 byte

+    int _alphabits;            // (derived from imageinfo)

+    int _origin;               // (derived from imageinfo)

+} _tga_header_t;

+

+#define _TGA_CMAPTYPE_NONE      0

+#define _TGA_CMAPTYPE_PRESENT   1

+

+#define _TGA_IMAGETYPE_NONE     0

+#define _TGA_IMAGETYPE_CMAP     1

+#define _TGA_IMAGETYPE_TC       2

+#define _TGA_IMAGETYPE_GRAY     3

+#define _TGA_IMAGETYPE_CMAP_RLE 9

+#define _TGA_IMAGETYPE_TC_RLE   10

+#define _TGA_IMAGETYPE_GRAY_RLE 11

+

+#define _TGA_IMAGEINFO_ALPHA_MASK   0x0f

+#define _TGA_IMAGEINFO_ALPHA_SHIFT  0

+#define _TGA_IMAGEINFO_ORIGIN_MASK  0x30

+#define _TGA_IMAGEINFO_ORIGIN_SHIFT 4

+

+#define _TGA_ORIGIN_BL 0

+#define _TGA_ORIGIN_BR 1

+#define _TGA_ORIGIN_UL 2

+#define _TGA_ORIGIN_UR 3

+

+

+//========================================================================

+// _glfwReadTGAHeader() - Read TGA file header (and check that it is

+// valid)

+//========================================================================

+

+static int _glfwReadTGAHeader( _GLFWstream *s, _tga_header_t *h )

+{

+    unsigned char buf[ 18 ];

+    int pos;

+

+    // Read TGA file header from file

+    pos = _glfwTellStream( s );

+    _glfwReadStream( s, buf, 18 );

+

+    // Interpret header (endian independent parsing)

+    h->idlen         = (int) buf[0];

+    h->cmaptype      = (int) buf[1];

+    h->imagetype     = (int) buf[2];

+    h->cmapfirstidx  = (int) buf[3] | (((int) buf[4]) << 8);

+    h->cmaplen       = (int) buf[5] | (((int) buf[6]) << 8);

+    h->cmapentrysize = (int) buf[7];

+    h->xorigin       = (int) buf[8] | (((int) buf[9]) << 8);

+    h->yorigin       = (int) buf[10] | (((int) buf[11]) << 8);

+    h->width         = (int) buf[12] | (((int) buf[13]) << 8);

+    h->height        = (int) buf[14] | (((int) buf[15]) << 8);

+    h->bitsperpixel  = (int) buf[16];

+    h->imageinfo     = (int) buf[17];

+

+    // Extract alphabits and origin information

+    h->_alphabits = (int) (h->imageinfo & _TGA_IMAGEINFO_ALPHA_MASK) >>

+                     _TGA_IMAGEINFO_ALPHA_SHIFT;

+    h->_origin    = (int) (h->imageinfo & _TGA_IMAGEINFO_ORIGIN_MASK) >>

+                     _TGA_IMAGEINFO_ORIGIN_SHIFT;

+

+    // Validate TGA header (is this a TGA file?)

+    if( (h->cmaptype == 0 || h->cmaptype == 1) &&

+        ((h->imagetype >= 1 && h->imagetype <= 3) ||

+         (h->imagetype >= 9 && h->imagetype <= 11)) &&

+         (h->bitsperpixel == 8 || h->bitsperpixel == 24 ||

+          h->bitsperpixel == 32) )

+    {

+        // Skip the ID field

+        _glfwSeekStream( s, h->idlen, SEEK_CUR );

+

+        // Indicate that the TGA header was valid

+        return GL_TRUE;

+    }

+    else

+    {

+        // Restore file position

+        _glfwSeekStream( s, pos, SEEK_SET );

+

+        // Indicate that the TGA header was invalid

+        return GL_FALSE;

+    }

+}

+

+//========================================================================

+// _glfwReadTGA_RLE() - Read Run-Length Encoded data

+//========================================================================

+

+static void _glfwReadTGA_RLE( unsigned char *buf, int size, int bpp,

+    _GLFWstream *s )

+{

+    int repcount, bytes, k, n;

+    unsigned char pixel[ 4 ];

+    char c;

+

+    // Dummy check

+    if( bpp > 4 )

+    {

+        return;

+    }

+

+    while( size > 0 )

+    {

+        // Get repetition count

+	_glfwReadStream( s, &c, 1 );

+        repcount = (unsigned int) c;

+        bytes = ((repcount & 127) + 1) * bpp;

+        if( size < bytes )

+        {

+            bytes = size;

+        }

+

+        // Run-Length packet?

+        if( repcount & 128 )

+        {

+            _glfwReadStream( s, pixel, bpp );

+            for( n = 0; n < (repcount & 127) + 1; n ++ )

+            {

+                for( k = 0; k < bpp; k ++ )

+                {

+                    *buf ++ = pixel[ k ];

+                }

+            }

+        }

+        else

+        {

+            // It's a Raw packet

+            _glfwReadStream( s, buf, bytes );

+            buf += bytes;

+        }

+

+        size -= bytes;

+    }

+}

+

+

+//========================================================================

+// _glfwReadTGA() - Read a TGA image from a file

+//========================================================================

+

+int _glfwReadTGA( _GLFWstream *s, GLFWimage *img, int flags )

+{

+    _tga_header_t h;

+    unsigned char *cmap, *pix, tmp, *src, *dst;

+    int cmapsize, pixsize, pixsize2;

+    int bpp, bpp2, k, m, n, swapx, swapy;

+

+    // Read TGA header

+    if( !_glfwReadTGAHeader( s, &h ) )

+    {

+        return 0;

+    }

+

+    // Is there a colormap?

+    cmapsize = (h.cmaptype == _TGA_CMAPTYPE_PRESENT ? 1 : 0) * h.cmaplen *

+               ((h.cmapentrysize+7) / 8);

+    if( cmapsize > 0 )

+    {

+        // Is it a colormap that we can handle?

+        if( (h.cmapentrysize != 24 && h.cmapentrysize != 32) ||

+            h.cmaplen == 0 || h.cmaplen > 256 )

+        {

+            return 0;

+        }

+

+        // Allocate memory for colormap

+        cmap = (unsigned char *) malloc( cmapsize );

+        if( cmap == NULL )

+        {

+            return 0;

+        }

+

+        // Read colormap from file

+        _glfwReadStream( s, cmap, cmapsize );

+    }

+    else

+    {

+        cmap = NULL;

+    }

+

+    // Size of pixel data

+    pixsize = h.width * h.height * ((h.bitsperpixel + 7) / 8);

+

+    // Bytes per pixel (pixel data - unexpanded)

+    bpp = (h.bitsperpixel + 7) / 8;

+

+    // Bytes per pixel (expanded pixels - not colormap indeces)

+    if( cmap )

+    {

+        bpp2 = (h.cmapentrysize + 7) / 8;

+    }

+    else

+    {

+        bpp2 = bpp;

+    }

+

+    // For colormaped images, the RGB/RGBA image data may use more memory

+    // than the stored pixel data

+    pixsize2 = h.width * h.height * bpp2;

+

+    // Allocate memory for pixel data

+    pix = (unsigned char *) malloc( pixsize2 );

+    if( pix == NULL )

+    {

+        if( cmap )

+        {

+            free( cmap );

+        }

+        return 0;

+    }

+

+    // Read pixel data from file

+    if( h.imagetype >= _TGA_IMAGETYPE_CMAP_RLE )

+    {

+        _glfwReadTGA_RLE( pix, pixsize, bpp, s );

+    }

+    else

+    {

+        _glfwReadStream( s, pix, pixsize );

+    }

+

+    // If the image origin is not what we want, re-arrange the pixels

+    switch( h._origin )

+    {

+    default:

+    case _TGA_ORIGIN_UL:

+        swapx = 0;

+        swapy = 1;

+        break;

+

+    case _TGA_ORIGIN_BL:

+        swapx = 0;

+        swapy = 0;

+        break;

+

+    case _TGA_ORIGIN_UR:

+        swapx = 1;

+        swapy = 1;

+        break;

+

+    case _TGA_ORIGIN_BR:

+        swapx = 1;

+        swapy = 0;

+        break;

+    }

+    if( (swapy && !(flags & GLFW_ORIGIN_UL_BIT)) ||

+        (!swapy && (flags & GLFW_ORIGIN_UL_BIT)) )

+    {

+        src = pix;

+        dst = &pix[ (h.height-1)*h.width*bpp ];

+        for( n = 0; n < h.height/2; n ++ )

+        {

+            for( m = 0; m < h.width ; m ++ )

+            {

+                for( k = 0; k < bpp; k ++ )

+                {

+                    tmp     = *src;

+                    *src ++ = *dst;

+                    *dst ++ = tmp;

+                }

+            }

+            dst -= 2*h.width*bpp;

+        }

+    }

+    if( swapx )

+    {

+        src = pix;

+        dst = &pix[ (h.width-1)*bpp ];

+        for( n = 0; n < h.height; n ++ )

+        {

+            for( m = 0; m < h.width/2 ; m ++ )

+            {

+                for( k = 0; k < bpp; k ++ )

+                {

+                    tmp     = *src;

+                    *src ++ = *dst;

+                    *dst ++ = tmp;

+                }

+                dst -= 2*bpp;

+            }

+            src += ((h.width+1)/2)*bpp;

+            dst += ((3*h.width+1)/2)*bpp;

+        }

+    }

+

+    // Convert BGR/BGRA to RGB/RGBA, and optionally colormap indeces to

+    // RGB/RGBA values

+    if( cmap )

+    {

+        // Convert colormap pixel format (BGR -> RGB or BGRA -> RGBA)

+        if( bpp2 == 3 || bpp2 == 4 )

+        {

+            for( n = 0; n < h.cmaplen; n ++ )

+            {

+                tmp                = cmap[ n*bpp2 ];

+                cmap[ n*bpp2 ]     = cmap[ n*bpp2 + 2 ];

+                cmap[ n*bpp2 + 2 ] = tmp;

+            }

+        }

+

+        // Convert pixel data to RGB/RGBA data

+        for( m = h.width * h.height - 1; m >= 0; m -- )

+        {

+            n = pix[ m ];

+            for( k = 0; k < bpp2; k ++ )

+            {

+                pix[ m*bpp2 + k ] = cmap[ n*bpp2 + k ];

+            }

+        }

+

+        // Free memory for colormap (it's not needed anymore)

+        free( cmap );

+    }

+    else

+    {

+        // Convert image pixel format (BGR -> RGB or BGRA -> RGBA)

+        if( bpp2 == 3 || bpp2 == 4 )

+        {

+            src = pix;

+            dst = &pix[ 2 ];

+            for( n = 0; n < h.height * h.width; n ++ )

+            {

+                tmp  = *src;

+                *src = *dst;

+                *dst = tmp;

+                src += bpp2;

+                dst += bpp2;

+            }

+        }

+    }

+

+    // Fill out GLFWimage struct (the Format field will be set by

+    // glfwReadImage)

+    img->Width         = h.width;

+    img->Height        = h.height;

+    img->BytesPerPixel = bpp2;

+    img->Data          = pix;

+

+    return 1;

+}

+

diff --git a/src/engine/external/glfw/lib/thread.c b/src/engine/external/glfw/lib/thread.c
new file mode 100644
index 00000000..8094332c
--- /dev/null
+++ b/src/engine/external/glfw/lib/thread.c
@@ -0,0 +1,340 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        thread.c

+// Platform:    Any

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

+

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

+//****                  GLFW internal functions                       ****

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

+

+//========================================================================

+// _glfwGetThreadPointer() - Find pointer to thread with a matching ID

+//========================================================================

+

+_GLFWthread * _glfwGetThreadPointer( int ID )

+{

+    _GLFWthread *t;

+

+    for( t = &_glfwThrd.First; t != NULL; t = t->Next )

+    {

+        if( t->ID == ID )

+        {

+            break;

+        }

+    }

+

+    return t;

+}

+

+

+//========================================================================

+// _glfwAppendThread() - Append thread to thread list

+//========================================================================

+

+void _glfwAppendThread( _GLFWthread * t )

+{

+    _GLFWthread *t_tmp;

+

+    t_tmp = &_glfwThrd.First;

+    while( t_tmp->Next != NULL )

+    {

+        t_tmp = t_tmp->Next;

+    }

+    t_tmp->Next = t;

+    t->Previous = t_tmp;

+    t->Next     = NULL;

+}

+

+

+//========================================================================

+// _glfwRemoveThread() - Remove thread from thread list

+//========================================================================

+

+void _glfwRemoveThread( _GLFWthread * t )

+{

+    if( t->Previous != NULL )

+    {

+        t->Previous->Next = t->Next;

+    }

+    if( t->Next != NULL )

+    {

+        t->Next->Previous = t->Previous;

+    }

+    free( (void *) t );

+}

+

+

+

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

+//****                     GLFW user functions                        ****

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

+

+//========================================================================

+// glfwCreateThread() - Create a new thread

+//========================================================================

+

+GLFWAPI GLFWthread GLFWAPIENTRY glfwCreateThread( GLFWthreadfun fun,

+    void *arg )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized )

+    {

+        return -1;

+    }

+

+    // Return the GLFW thread ID

+    return _glfwPlatformCreateThread( fun, arg );

+}

+

+

+//========================================================================

+// glfwDestroyThread() - Kill a thread. NOTE: THIS IS A VERY DANGEROUS

+// OPERATION, AND SHOULD NOT BE USED EXCEPT IN EXTREME SITUATIONS!

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwDestroyThread( GLFWthread ID )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized )

+    {

+        return;

+    }

+

+    // Is it a valid thread? (killing the main thread is not allowed)

+    if( ID < 1 )

+    {

+        return;

+    }

+

+    _glfwPlatformDestroyThread( ID );

+}

+

+

+//========================================================================

+// glfwWaitThread() - Wait for a thread to die

+//========================================================================

+

+GLFWAPI int GLFWAPIENTRY glfwWaitThread( GLFWthread ID, int waitmode )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized )

+    {

+        return GL_TRUE;

+    }

+

+    // Is it a valid thread? (waiting for the main thread is not allowed)

+    if( ID < 1 )

+    {

+        return GL_TRUE;

+    }

+

+    return _glfwPlatformWaitThread( ID, waitmode );

+}

+

+

+//========================================================================

+// glfwGetThreadID() - Return the thread ID for the current thread

+//========================================================================

+

+GLFWAPI GLFWthread GLFWAPIENTRY glfwGetThreadID( void )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized )

+    {

+        return 0;

+    }

+

+    return _glfwPlatformGetThreadID();

+}

+

+

+//========================================================================

+// glfwCreateMutex() - Create a mutual exclusion object

+//========================================================================

+

+GLFWAPI GLFWmutex GLFWAPIENTRY glfwCreateMutex( void )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized )

+    {

+        return (GLFWmutex) 0;

+    }

+

+    return _glfwPlatformCreateMutex();

+}

+

+

+//========================================================================

+// glfwDestroyMutex() - Destroy a mutual exclusion object

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwDestroyMutex( GLFWmutex mutex )

+{

+    // Initialized & valid mutex (no real way of assuring this)?

+    if( !_glfwInitialized || !mutex )

+    {

+        return;

+    }

+

+    _glfwPlatformDestroyMutex( mutex );

+}

+

+

+//========================================================================

+// glfwLockMutex() - Request access to a mutex

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwLockMutex( GLFWmutex mutex )

+{

+    // Initialized & valid mutex (no real way of assuring this)?

+    if( !_glfwInitialized && !mutex )

+    {

+        return;

+    }

+

+    _glfwPlatformLockMutex( mutex );

+}

+

+

+//========================================================================

+// glfwUnlockMutex() - Release a mutex

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwUnlockMutex( GLFWmutex mutex )

+{

+    // Initialized & valid mutex (no real way of assuring this)?

+    if( !_glfwInitialized && !mutex )

+    {

+        return;

+    }

+

+    _glfwPlatformUnlockMutex( mutex );

+}

+

+

+//========================================================================

+// glfwCreateCond() - Create a new condition variable object

+//========================================================================

+

+GLFWAPI GLFWcond GLFWAPIENTRY glfwCreateCond( void )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized )

+    {

+        return (GLFWcond) 0;

+    }

+

+    return _glfwPlatformCreateCond();

+}

+

+

+//========================================================================

+// glfwDestroyCond() - Destroy a condition variable object

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwDestroyCond( GLFWcond cond )

+{

+    // Initialized & valid condition variable?

+    if( !_glfwInitialized || !cond )

+    {

+        return;

+    }

+

+    _glfwPlatformDestroyCond( cond );

+}

+

+

+//========================================================================

+// glfwWaitCond() - Wait for a condition to be raised

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwWaitCond( GLFWcond cond, GLFWmutex mutex,

+    double timeout )

+{

+    // Initialized & valid condition variable and mutex?

+    if( !_glfwInitialized || !cond || !mutex )

+    {

+        return;

+    }

+

+    _glfwPlatformWaitCond( cond, mutex, timeout );

+}

+

+

+//========================================================================

+// glfwSignalCond() - Signal a condition to one waiting thread

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwSignalCond( GLFWcond cond )

+{

+    // Initialized & valid condition variable?

+    if( !_glfwInitialized || !cond )

+    {

+        return;

+    }

+

+    _glfwPlatformSignalCond( cond );

+}

+

+

+//========================================================================

+// glfwBroadcastCond() - Broadcast a condition to all waiting threads

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwBroadcastCond( GLFWcond cond )

+{

+    // Initialized & valid condition variable?

+    if( !_glfwInitialized || !cond )

+    {

+        return;

+    }

+

+    _glfwPlatformBroadcastCond( cond );

+}

+

+

+//========================================================================

+// glfwGetNumberOfProcessors() - Return the number of processors in the

+// system. This information can be useful for determining the optimal

+// number of threads to use for performing a certain task.

+//========================================================================

+

+GLFWAPI int GLFWAPIENTRY glfwGetNumberOfProcessors( void )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized )

+    {

+        return 0;

+    }

+

+    return _glfwPlatformGetNumberOfProcessors();

+}

diff --git a/src/engine/external/glfw/lib/time.c b/src/engine/external/glfw/lib/time.c
new file mode 100644
index 00000000..7f9f106d
--- /dev/null
+++ b/src/engine/external/glfw/lib/time.c
@@ -0,0 +1,83 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        time.c

+// Platform:    Any

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

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

+//****                    GLFW user functions                         ****

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

+

+//========================================================================

+// glfwGetTime() - Return timer value in seconds

+//========================================================================

+

+GLFWAPI double GLFWAPIENTRY glfwGetTime( void )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized )

+    {

+        return 0.0;

+    }

+

+    return _glfwPlatformGetTime();

+}

+

+

+//========================================================================

+// glfwSetTime() - Set timer value in seconds

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwSetTime( double time )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized )

+    {

+        return;

+    }

+

+    _glfwPlatformSetTime( time );

+}

+

+

+//========================================================================

+// glfwSleep() - Put a thread to sleep for a specified amount of time

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwSleep( double time )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized )

+    {

+        return;

+    }

+

+    _glfwPlatformSleep( time );

+}

diff --git a/src/engine/external/glfw/lib/win32/glfwdll.def b/src/engine/external/glfw/lib/win32/glfwdll.def
new file mode 100644
index 00000000..1b40765a
--- /dev/null
+++ b/src/engine/external/glfw/lib/win32/glfwdll.def
@@ -0,0 +1,67 @@
+LIBRARY GLFW.DLL
+
+EXPORTS
+glfwBroadcastCond
+glfwCloseWindow
+glfwCreateCond
+glfwCreateMutex
+glfwCreateThread
+glfwDestroyCond
+glfwDestroyMutex
+glfwDestroyThread
+glfwDisable
+glfwEnable
+glfwExtensionSupported
+glfwFreeImage
+glfwGetDesktopMode
+glfwGetGLVersion
+glfwGetJoystickButtons
+glfwGetJoystickParam
+glfwGetJoystickPos
+glfwGetKey
+glfwGetMouseButton
+glfwGetMousePos
+glfwGetMouseWheel
+glfwGetNumberOfProcessors
+glfwGetProcAddress
+glfwGetThreadID
+glfwGetTime
+glfwGetVersion
+glfwGetVideoModes
+glfwGetWindowParam
+glfwGetWindowSize
+glfwIconifyWindow
+glfwInit
+glfwLoadMemoryTexture2D
+glfwLoadTexture2D
+glfwLoadTextureImage2D
+glfwLockMutex
+glfwOpenWindow
+glfwOpenWindowHint
+glfwPollEvents
+glfwReadImage
+glfwReadMemoryImage
+glfwRestoreWindow
+glfwSetCharCallback
+glfwSetKeyCallback
+glfwSetMouseButtonCallback
+glfwSetMousePos
+glfwSetMousePosCallback
+glfwSetMouseWheel
+glfwSetMouseWheelCallback
+glfwSetTime
+glfwSetWindowCloseCallback
+glfwSetWindowRefreshCallback
+glfwSetWindowPos
+glfwSetWindowSize
+glfwSetWindowSizeCallback
+glfwSetWindowTitle
+glfwSignalCond
+glfwSleep
+glfwSwapBuffers
+glfwSwapInterval
+glfwTerminate
+glfwUnlockMutex
+glfwWaitCond
+glfwWaitEvents
+glfwWaitThread
diff --git a/src/engine/external/glfw/lib/win32/glfwdll_mgw1.def b/src/engine/external/glfw/lib/win32/glfwdll_mgw1.def
new file mode 100644
index 00000000..b193aa95
--- /dev/null
+++ b/src/engine/external/glfw/lib/win32/glfwdll_mgw1.def
@@ -0,0 +1,67 @@
+LIBRARY GLFW.DLL
+
+EXPORTS
+glfwBroadcastCond = glfwBroadcastCond@4
+glfwCloseWindow = glfwCloseWindow@0
+glfwCreateCond = glfwCreateCond@0
+glfwCreateMutex = glfwCreateMutex@0
+glfwCreateThread = glfwCreateThread@8
+glfwDestroyCond = glfwDestroyCond@4
+glfwDestroyMutex = glfwDestroyMutex@4
+glfwDestroyThread = glfwDestroyThread@4
+glfwDisable = glfwDisable@4
+glfwEnable = glfwEnable@4
+glfwExtensionSupported = glfwExtensionSupported@4
+glfwFreeImage = glfwFreeImage@4
+glfwGetDesktopMode = glfwGetDesktopMode@4
+glfwGetGLVersion = glfwGetGLVersion@12
+glfwGetJoystickButtons = glfwGetJoystickButtons@12
+glfwGetJoystickParam = glfwGetJoystickParam@8
+glfwGetJoystickPos = glfwGetJoystickPos@12
+glfwGetKey = glfwGetKey@4
+glfwGetMouseButton = glfwGetMouseButton@4
+glfwGetMousePos = glfwGetMousePos@8
+glfwGetMouseWheel = glfwGetMouseWheel@0
+glfwGetNumberOfProcessors = glfwGetNumberOfProcessors@0
+glfwGetProcAddress = glfwGetProcAddress@4
+glfwGetThreadID = glfwGetThreadID@0
+glfwGetTime = glfwGetTime@0
+glfwGetVersion = glfwGetVersion@12
+glfwGetVideoModes = glfwGetVideoModes@8
+glfwGetWindowParam = glfwGetWindowParam@4
+glfwGetWindowSize = glfwGetWindowSize@8
+glfwIconifyWindow = glfwIconifyWindow@0
+glfwInit = glfwInit@0
+glfwLoadMemoryTexture2D = glfwLoadMemoryTexture2D@12
+glfwLoadTexture2D = glfwLoadTexture2D@8
+glfwLoadTextureImage2D = glfwLoadTextureImage2D@8
+glfwLockMutex = glfwLockMutex@4
+glfwOpenWindow = glfwOpenWindow@36
+glfwOpenWindowHint = glfwOpenWindowHint@8
+glfwPollEvents = glfwPollEvents@0
+glfwReadImage = glfwReadImage@12
+glfwReadMemoryImage = glfwReadMemoryImage@16
+glfwRestoreWindow = glfwRestoreWindow@0
+glfwSetCharCallback = glfwSetCharCallback@4
+glfwSetKeyCallback = glfwSetKeyCallback@4
+glfwSetMouseButtonCallback = glfwSetMouseButtonCallback@4
+glfwSetMousePos = glfwSetMousePos@8
+glfwSetMousePosCallback = glfwSetMousePosCallback@4
+glfwSetMouseWheel = glfwSetMouseWheel@4
+glfwSetMouseWheelCallback = glfwSetMouseWheelCallback@4
+glfwSetTime = glfwSetTime@8
+glfwSetWindowCloseCallback = glfwSetWindowCloseCallback@4
+glfwSetWindowRefreshCallback = glfwSetWindowRefreshCallback@4
+glfwSetWindowPos = glfwSetWindowPos@8
+glfwSetWindowSize = glfwSetWindowSize@8
+glfwSetWindowSizeCallback = glfwSetWindowSizeCallback@4
+glfwSetWindowTitle = glfwSetWindowTitle@4
+glfwSignalCond = glfwSignalCond@4
+glfwSleep = glfwSleep@8
+glfwSwapBuffers = glfwSwapBuffers@0
+glfwSwapInterval = glfwSwapInterval@4
+glfwTerminate = glfwTerminate@0
+glfwUnlockMutex = glfwUnlockMutex@4
+glfwWaitCond = glfwWaitCond@16
+glfwWaitEvents = glfwWaitEvents@0
+glfwWaitThread = glfwWaitThread@8
diff --git a/src/engine/external/glfw/lib/win32/glfwdll_mgw2.def b/src/engine/external/glfw/lib/win32/glfwdll_mgw2.def
new file mode 100644
index 00000000..e42f664e
--- /dev/null
+++ b/src/engine/external/glfw/lib/win32/glfwdll_mgw2.def
@@ -0,0 +1,67 @@
+LIBRARY GLFW.DLL
+
+EXPORTS
+glfwBroadcastCond@4
+glfwCloseWindow@0
+glfwCreateCond@0
+glfwCreateMutex@0
+glfwCreateThread@8
+glfwDestroyCond@4
+glfwDestroyMutex@4
+glfwDestroyThread@4
+glfwDisable@4
+glfwEnable@4
+glfwExtensionSupported@4
+glfwFreeImage@4
+glfwGetDesktopMode@4
+glfwGetGLVersion@12
+glfwGetJoystickButtons@12
+glfwGetJoystickParam@8
+glfwGetJoystickPos@12
+glfwGetKey@4
+glfwGetMouseButton@4
+glfwGetMousePos@8
+glfwGetMouseWheel@0
+glfwGetNumberOfProcessors@0
+glfwGetProcAddress@4
+glfwGetThreadID@0
+glfwGetTime@0
+glfwGetVersion@12
+glfwGetVideoModes@8
+glfwGetWindowParam@4
+glfwGetWindowSize@8
+glfwIconifyWindow@0
+glfwInit@0
+glfwLoadMemoryTexture2D@12
+glfwLoadTexture2D@8
+glfwLoadTextureImage2D@8
+glfwLockMutex@4
+glfwOpenWindow@36
+glfwOpenWindowHint@8
+glfwPollEvents@0
+glfwReadImage@12
+glfwReadMemoryImage@16
+glfwRestoreWindow@0
+glfwSetCharCallback@4
+glfwSetKeyCallback@4
+glfwSetMouseButtonCallback@4
+glfwSetMousePos@8
+glfwSetMousePosCallback@4
+glfwSetMouseWheel@4
+glfwSetMouseWheelCallback@4
+glfwSetTime@8
+glfwSetWindowCloseCallback@4
+glfwSetWindowRefreshCallback@4
+glfwSetWindowPos@8
+glfwSetWindowSize@8
+glfwSetWindowSizeCallback@4
+glfwSetWindowTitle@4
+glfwSignalCond@4
+glfwSleep@8
+glfwSwapBuffers@0
+glfwSwapInterval@4
+glfwTerminate@0
+glfwUnlockMutex@4
+glfwWaitCond@16
+glfwWaitEvents@0
+glfwWaitThread@8
diff --git a/src/engine/external/glfw/lib/win32/glfwdll_pellesc.def b/src/engine/external/glfw/lib/win32/glfwdll_pellesc.def
new file mode 100644
index 00000000..cbb214c8
--- /dev/null
+++ b/src/engine/external/glfw/lib/win32/glfwdll_pellesc.def
@@ -0,0 +1,65 @@
+LIBRARY GLFW
+
+EXPORTS
+glfwBroadcastCond = glfwBroadcastCond@4
+glfwCloseWindow = glfwCloseWindow@0
+glfwCreateCond = glfwCreateCond@0
+glfwCreateMutex = glfwCreateMutex@0
+glfwCreateThread = glfwCreateThread@8
+glfwDestroyCond = glfwDestroyCond@4
+glfwDestroyMutex = glfwDestroyMutex@4
+glfwDestroyThread = glfwDestroyThread@4
+glfwDisable = glfwDisable@4
+glfwEnable = glfwEnable@4
+glfwExtensionSupported = glfwExtensionSupported@4
+glfwFreeImage = glfwFreeImage@4
+glfwGetDesktopMode = glfwGetDesktopMode@4
+glfwGetGLVersion = glfwGetGLVersion@12
+glfwGetJoystickButtons = glfwGetJoystickButtons@12
+glfwGetJoystickParam = glfwGetJoystickParam@8
+glfwGetJoystickPos = glfwGetJoystickPos@12
+glfwGetKey = glfwGetKey@4
+glfwGetMouseButton = glfwGetMouseButton@4
+glfwGetMousePos = glfwGetMousePos@8
+glfwGetMouseWheel = glfwGetMouseWheel@0
+glfwGetNumberOfProcessors = glfwGetNumberOfProcessors@0
+glfwGetProcAddress = glfwGetProcAddress@4
+glfwGetThreadID = glfwGetThreadID@0
+glfwGetTime = glfwGetTime@0
+glfwGetVersion = glfwGetVersion@12
+glfwGetVideoModes = glfwGetVideoModes@8
+glfwGetWindowParam = glfwGetWindowParam@4
+glfwGetWindowSize = glfwGetWindowSize@8
+glfwIconifyWindow = glfwIconifyWindow@0
+glfwInit = glfwInit@0
+glfwLoadTexture2D = glfwLoadTexture2D@8
+glfwLockMutex = glfwLockMutex@4
+glfwOpenWindow = glfwOpenWindow@36
+glfwOpenWindowHint = glfwOpenWindowHint@8
+glfwPollEvents = glfwPollEvents@0
+glfwReadImage = glfwReadImage@12
+glfwReadMemoryImage = glfwReadMemoryImage@16
+glfwRestoreWindow = glfwRestoreWindow@0
+glfwSetCharCallback = glfwSetCharCallback@4
+glfwSetKeyCallback = glfwSetKeyCallback@4
+glfwSetMouseButtonCallback = glfwSetMouseButtonCallback@4
+glfwSetMousePos = glfwSetMousePos@8
+glfwSetMousePosCallback = glfwSetMousePosCallback@4
+glfwSetMouseWheel = glfwSetMouseWheel@4
+glfwSetMouseWheelCallback = glfwSetMouseWheelCallback@4
+glfwSetTime = glfwSetTime@8
+glfwSetWindowCloseCallback = glfwSetWindowCloseCallback@4
+glfwSetWindowRefreshCallback = glfwSetWindowRefreshCallback@4
+glfwSetWindowPos = glfwSetWindowPos@8
+glfwSetWindowSize = glfwSetWindowSize@8
+glfwSetWindowSizeCallback = glfwSetWindowSizeCallback@4
+glfwSetWindowTitle = glfwSetWindowTitle@4
+glfwSignalCond = glfwSignalCond@4
+glfwSleep = glfwSleep@8
+glfwSwapBuffers = glfwSwapBuffers@0
+glfwSwapInterval = glfwSwapInterval@4
+glfwTerminate = glfwTerminate@0
+glfwUnlockMutex = glfwUnlockMutex@4
+glfwWaitCond = glfwWaitCond@16
+glfwWaitEvents = glfwWaitEvents@0
+glfwWaitThread = glfwWaitThread@8
diff --git a/src/engine/external/glfw/lib/win32/platform.h b/src/engine/external/glfw/lib/win32/platform.h
new file mode 100644
index 00000000..25ada3b0
--- /dev/null
+++ b/src/engine/external/glfw/lib/win32/platform.h
@@ -0,0 +1,468 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        platform.h

+// Platform:    Windows

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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 _platform_h_

+#define _platform_h_

+

+

+// This is the Windows version of GLFW

+#define _GLFW_WIN32

+

+

+// Include files

+#include <windows.h>

+#include <mmsystem.h>

+#include "../../include/GL/glfw.h"

+

+

+//========================================================================

+// Hack: Define things that some <windows.h>'s do not define

+//========================================================================

+

+// Some old versions of w32api (used by MinGW and Cygwin) define

+// WH_KEYBOARD_LL without typedef:ing KBDLLHOOKSTRUCT (!)

+#if defined(__MINGW32__) || defined(__CYGWIN__)

+#include <w32api.h>

+#if defined(WH_KEYBOARD_LL) && (__W32API_MAJOR_VERSION == 1) && (__W32API_MINOR_VERSION <= 2)

+#undef WH_KEYBOARD_LL

+#endif

+#endif

+

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

+// ** NOTE **  If this gives you compiler errors and you are using MinGW

+// (or Dev-C++), update to w32api version 1.3 or later:

+// http://sourceforge.net/project/showfiles.php?group_id=2435

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

+#ifndef WH_KEYBOARD_LL

+#define WH_KEYBOARD_LL 13

+typedef struct tagKBDLLHOOKSTRUCT {

+  DWORD   vkCode;

+  DWORD   scanCode;

+  DWORD   flags;

+  DWORD   time;

+  DWORD   dwExtraInfo;

+} KBDLLHOOKSTRUCT, FAR *LPKBDLLHOOKSTRUCT, *PKBDLLHOOKSTRUCT;

+#endif // WH_KEYBOARD_LL

+

+#ifndef LLKHF_ALTDOWN

+#define LLKHF_ALTDOWN  0x00000020

+#endif

+

+#ifndef SPI_SETSCREENSAVERRUNNING

+#define SPI_SETSCREENSAVERRUNNING 97

+#endif

+#ifndef SPI_GETANIMATION

+#define SPI_GETANIMATION 72

+#endif

+#ifndef SPI_SETANIMATION

+#define SPI_SETANIMATION 73

+#endif

+#ifndef SPI_GETFOREGROUNDLOCKTIMEOUT

+#define SPI_GETFOREGROUNDLOCKTIMEOUT 0x2000

+#endif

+#ifndef SPI_SETFOREGROUNDLOCKTIMEOUT

+#define SPI_SETFOREGROUNDLOCKTIMEOUT 0x2001

+#endif

+

+#ifndef CDS_FULLSCREEN

+#define CDS_FULLSCREEN 4

+#endif

+

+#ifndef PFD_GENERIC_ACCELERATED

+#define PFD_GENERIC_ACCELERATED 0x00001000

+#endif

+#ifndef PFD_DEPTH_DONTCARE

+#define PFD_DEPTH_DONTCARE 0x20000000

+#endif

+

+#ifndef ENUM_CURRENT_SETTINGS

+#define ENUM_CURRENT_SETTINGS -1

+#endif

+#ifndef ENUM_REGISTRY_SETTINGS

+#define ENUM_REGISTRY_SETTINGS -2

+#endif

+

+#ifndef WM_MOUSEWHEEL

+#define WM_MOUSEWHEEL 0x020A

+#endif

+#ifndef WHEEL_DELTA

+#define WHEEL_DELTA 120

+#endif

+

+#ifndef WM_XBUTTONDOWN

+#define WM_XBUTTONDOWN 0x020B

+#endif

+#ifndef WM_XBUTTONUP

+#define WM_XBUTTONUP 0x020C

+#endif

+#ifndef XBUTTON1

+#define XBUTTON1 1

+#endif

+#ifndef XBUTTON2

+#define XBUTTON2 2

+#endif

+

+// wglSwapIntervalEXT typedef (Win32 buffer-swap interval control)

+typedef int (APIENTRY * WGLSWAPINTERVALEXT_T) (int interval);

+// wglChoosePixelFormatARB typedef

+typedef BOOL (WINAPI * WGLCHOOSEPIXELFORMATARB_T) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);

+// wglGetPixelFormatAttribivARB typedef

+typedef BOOL (WINAPI * WGLGETPIXELFORMATATTRIBIVARB_T) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);

+

+#define WGL_DRAW_TO_WINDOW_ARB    0x2001

+#define WGL_SUPPORT_OPENGL_ARB    0x2010

+#define WGL_ACCELERATION_ARB      0x2003

+#define WGL_FULL_ACCELERATION_ARB 0x2027

+#define WGL_DOUBLE_BUFFER_ARB     0x2011

+#define WGL_STEREO_ARB            0x2012

+#define WGL_COLOR_BITS_ARB        0x2014

+#define WGL_RED_BITS_ARB          0x2015

+#define WGL_GREEN_BITS_ARB        0x2017

+#define WGL_BLUE_BITS_ARB         0x2019

+#define WGL_ALPHA_BITS_ARB        0x201B

+#define WGL_ACCUM_BITS_ARB        0x201D 

+#define WGL_ACCUM_RED_BITS_ARB    0x201E 

+#define WGL_ACCUM_GREEN_BITS_ARB  0x201F 

+#define WGL_ACCUM_BLUE_BITS_ARB   0x2020 

+#define WGL_ACCUM_ALPHA_BITS_ARB  0x2021 

+#define WGL_DEPTH_BITS_ARB        0x2022

+#define WGL_STENCIL_BITS_ARB      0x2023

+#define WGL_AUX_BUFFERS_ARB       0x2024 

+#define WGL_SAMPLE_BUFFERS_ARB    0x2041

+#define WGL_SAMPLES_ARB           0x2042

+

+

+//========================================================================

+// DLLs that are loaded at glfwInit()

+//========================================================================

+

+// gdi32.dll function pointer typedefs

+#ifndef _GLFW_NO_DLOAD_GDI32

+typedef int  (WINAPI * CHOOSEPIXELFORMAT_T) (HDC,CONST PIXELFORMATDESCRIPTOR*);

+typedef int  (WINAPI * DESCRIBEPIXELFORMAT_T) (HDC,int,UINT,LPPIXELFORMATDESCRIPTOR);

+typedef int  (WINAPI * GETPIXELFORMAT_T) (HDC);

+typedef BOOL (WINAPI * SETPIXELFORMAT_T) (HDC,int,const PIXELFORMATDESCRIPTOR*);

+typedef BOOL (WINAPI * SWAPBUFFERS_T) (HDC);

+#endif // _GLFW_NO_DLOAD_GDI32

+

+// winmm.dll function pointer typedefs

+#ifndef _GLFW_NO_DLOAD_WINMM

+typedef MMRESULT (WINAPI * JOYGETDEVCAPSA_T) (UINT,LPJOYCAPSA,UINT);

+typedef MMRESULT (WINAPI * JOYGETPOS_T) (UINT,LPJOYINFO);

+typedef MMRESULT (WINAPI * JOYGETPOSEX_T) (UINT,LPJOYINFOEX);

+typedef DWORD (WINAPI * TIMEGETTIME_T) (void);

+#endif // _GLFW_NO_DLOAD_WINMM

+

+

+// gdi32.dll shortcuts

+#ifndef _GLFW_NO_DLOAD_GDI32

+#define _glfw_ChoosePixelFormat   _glfwLibrary.Libs.ChoosePixelFormat

+#define _glfw_DescribePixelFormat _glfwLibrary.Libs.DescribePixelFormat

+#define _glfw_GetPixelFormat      _glfwLibrary.Libs.GetPixelFormat

+#define _glfw_SetPixelFormat      _glfwLibrary.Libs.SetPixelFormat

+#define _glfw_SwapBuffers         _glfwLibrary.Libs.SwapBuffers

+#else

+#define _glfw_ChoosePixelFormat   ChoosePixelFormat

+#define _glfw_DescribePixelFormat DescribePixelFormat

+#define _glfw_GetPixelFormat      GetPixelFormat

+#define _glfw_SetPixelFormat      SetPixelFormat

+#define _glfw_SwapBuffers         SwapBuffers

+#endif // _GLFW_NO_DLOAD_GDI32

+

+// winmm.dll shortcuts

+#ifndef _GLFW_NO_DLOAD_WINMM

+#define _glfw_joyGetDevCaps _glfwLibrary.Libs.joyGetDevCapsA

+#define _glfw_joyGetPos     _glfwLibrary.Libs.joyGetPos

+#define _glfw_joyGetPosEx   _glfwLibrary.Libs.joyGetPosEx

+#define _glfw_timeGetTime   _glfwLibrary.Libs.timeGetTime

+#else

+#define _glfw_joyGetDevCaps joyGetDevCapsA

+#define _glfw_joyGetPos     joyGetPos

+#define _glfw_joyGetPosEx   joyGetPosEx

+#define _glfw_timeGetTime   timeGetTime

+#endif // _GLFW_NO_DLOAD_WINMM

+

+

+//========================================================================

+// Global variables (GLFW internals)

+//========================================================================

+

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

+// Window structure

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

+typedef struct _GLFWwin_struct _GLFWwin;

+

+struct _GLFWwin_struct {

+

+// ========= PLATFORM INDEPENDENT MANDATORY PART =========================

+

+    // User callback functions

+    GLFWwindowsizefun    WindowSizeCallback;

+    GLFWwindowclosefun   WindowCloseCallback;

+    GLFWwindowrefreshfun WindowRefreshCallback;

+    GLFWmousebuttonfun   MouseButtonCallback;

+    GLFWmouseposfun      MousePosCallback;

+    GLFWmousewheelfun    MouseWheelCallback;

+    GLFWkeyfun           KeyCallback;

+    GLFWcharfun          CharCallback;

+

+    // User selected window settings

+    int       Fullscreen;      // Fullscreen flag

+    int       MouseLock;       // Mouse-lock flag

+    int       AutoPollEvents;  // Auto polling flag

+    int       SysKeysDisabled; // System keys disabled flag

+    int       WindowNoResize;  // Resize- and maximize gadgets disabled flag

+

+    // Window status & parameters

+    int       Opened;          // Flag telling if window is opened or not

+    int       Active;          // Application active flag

+    int       Iconified;       // Window iconified flag

+    int       Width, Height;   // Window width and heigth

+    int       Accelerated;     // GL_TRUE if window is HW accelerated

+    int       RedBits;

+    int       GreenBits;

+    int       BlueBits;

+    int       AlphaBits;

+    int       DepthBits;

+    int       StencilBits;

+    int       AccumRedBits;

+    int       AccumGreenBits;

+    int       AccumBlueBits;

+    int       AccumAlphaBits;

+    int       AuxBuffers;

+    int       Stereo;

+    int       RefreshRate;     // Vertical monitor refresh rate

+    int       Samples;

+

+    // Extensions & OpenGL version

+    int       Has_GL_SGIS_generate_mipmap;

+    int       Has_GL_ARB_texture_non_power_of_two;

+    int       GLVerMajor,GLVerMinor;

+

+

+// ========= PLATFORM SPECIFIC PART ======================================

+

+    // Platform specific window resources

+    HDC       DC;              // Private GDI device context

+    HGLRC     RC;              // Permanent rendering context

+    HWND      Wnd;             // Window handle

+    ATOM      ClassAtom;       // Window class atom

+    int       ModeID;          // Mode ID for fullscreen mode

+    HHOOK     KeyboardHook;    // Keyboard hook handle

+    DWORD     dwStyle;         // Window styles used for window creation

+    DWORD     dwExStyle;       // --"--

+

+    // Platform specific extensions (context specific)

+    WGLSWAPINTERVALEXT_T SwapInterval;

+    WGLCHOOSEPIXELFORMATARB_T ChoosePixelFormat;

+    WGLGETPIXELFORMATATTRIBIVARB_T GetPixelFormatAttribiv;

+

+    // Various platform specific internal variables

+    int       OldMouseLock;    // Old mouse-lock flag (used for remembering

+                               // mouse-lock state when iconifying)

+    int       OldMouseLockValid;

+    int       DesiredRefreshRate; // Desired vertical monitor refresh rate

+

+};

+

+GLFWGLOBAL _GLFWwin _glfwWin;

+

+

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

+// User input status (most of this should go in _GLFWwin)

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

+GLFWGLOBAL struct {

+

+// ========= PLATFORM INDEPENDENT MANDATORY PART =========================

+

+    // Mouse status

+    int  MousePosX, MousePosY;

+    int  WheelPos;

+    char MouseButton[ GLFW_MOUSE_BUTTON_LAST+1 ];

+

+    // Keyboard status

+    char Key[ GLFW_KEY_LAST+1 ];

+    int  LastChar;

+

+    // User selected settings

+    int  StickyKeys;

+    int  StickyMouseButtons;

+    int  KeyRepeat;

+

+

+// ========= PLATFORM SPECIFIC PART ======================================

+

+    // Platform specific internal variables

+    int  MouseMoved, OldMouseX, OldMouseY;

+

+} _glfwInput;

+

+

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

+// Library global data

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

+GLFWGLOBAL struct {

+

+// ========= PLATFORM SPECIFIC PART ======================================

+

+  HINSTANCE Instance;        // Instance of the application

+

+  // Timer data

+  struct {

+      int          HasPerformanceCounter;

+      double       Resolution;

+      unsigned int t0_32;

+      __int64      t0_64;

+  } Timer;

+

+  // System information

+  struct {

+      int     WinVer;

+      int     HasUnicode;

+      DWORD   ForegroundLockTimeout;

+  } Sys;

+

+#if !defined(_GLFW_NO_DLOAD_WINMM) || !defined(_GLFW_NO_DLOAD_GDI32)

+  // Library handles and function pointers

+  struct {

+#ifndef _GLFW_NO_DLOAD_GDI32

+      // gdi32.dll

+      HINSTANCE             gdi32;

+      CHOOSEPIXELFORMAT_T   ChoosePixelFormat;

+      DESCRIBEPIXELFORMAT_T DescribePixelFormat;

+      GETPIXELFORMAT_T      GetPixelFormat;

+      SETPIXELFORMAT_T      SetPixelFormat;

+      SWAPBUFFERS_T         SwapBuffers;

+#endif // _GLFW_NO_DLOAD_GDI32

+

+      // winmm.dll

+#ifndef _GLFW_NO_DLOAD_WINMM

+      HINSTANCE             winmm;

+      JOYGETDEVCAPSA_T      joyGetDevCapsA;

+      JOYGETPOS_T           joyGetPos;

+      JOYGETPOSEX_T         joyGetPosEx;

+      TIMEGETTIME_T         timeGetTime;

+#endif // _GLFW_NO_DLOAD_WINMM

+  } Libs;

+#endif

+

+} _glfwLibrary;

+

+

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

+// Thread record (one for each thread)

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

+typedef struct _GLFWthread_struct _GLFWthread;

+

+struct _GLFWthread_struct {

+

+// ========= PLATFORM INDEPENDENT MANDATORY PART =========================

+

+    // Pointer to previous and next threads in linked list

+    _GLFWthread   *Previous, *Next;

+

+    // GLFW user side thread information

+    GLFWthread    ID;

+    GLFWthreadfun Function;

+

+// ========= PLATFORM SPECIFIC PART ======================================

+

+    // System side thread information

+    HANDLE        Handle;

+    DWORD         WinID;

+

+};

+

+

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

+// General thread information

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

+GLFWGLOBAL struct {

+

+// ========= PLATFORM INDEPENDENT MANDATORY PART =========================

+

+    // Next thread ID to use (increments for every created thread)

+    GLFWthread       NextID;

+

+    // First thread in linked list (always the main thread)

+    _GLFWthread      First;

+

+// ========= PLATFORM SPECIFIC PART ======================================

+

+    // Critical section lock

+    CRITICAL_SECTION CriticalSection;

+

+} _glfwThrd;

+

+

+

+//========================================================================

+// Macros for encapsulating critical code sections (i.e. making parts

+// of GLFW thread safe)

+//========================================================================

+

+// Thread list management

+#define ENTER_THREAD_CRITICAL_SECTION \

+        EnterCriticalSection( &_glfwThrd.CriticalSection );

+#define LEAVE_THREAD_CRITICAL_SECTION \

+        LeaveCriticalSection( &_glfwThrd.CriticalSection );

+

+

+//========================================================================

+// Various Windows version constants

+//========================================================================

+

+#define _GLFW_WIN_UNKNOWN    0x0000  // Earlier than 95 or NT4

+#define _GLFW_WIN_95         0x0001

+#define _GLFW_WIN_98         0x0002

+#define _GLFW_WIN_ME         0x0003

+#define _GLFW_WIN_UNKNOWN_9x 0x0004  // Later than ME

+#define _GLFW_WIN_NT4        0x0101

+#define _GLFW_WIN_2K         0x0102

+#define _GLFW_WIN_XP         0x0103

+#define _GLFW_WIN_NET_SERVER 0x0104

+#define _GLFW_WIN_UNKNOWN_NT 0x0105  // Later than .NET Server

+

+

+//========================================================================

+// Prototypes for platform specific internal functions

+//========================================================================

+

+// Time

+void _glfwInitTimer( void );

+

+// Fullscreen support

+int _glfwGetClosestVideoModeBPP( int *w, int *h, int *bpp, int *refresh );

+int _glfwGetClosestVideoMode( int *w, int *h, int *r, int *g, int *b, int *refresh );

+void _glfwSetVideoModeMODE( int mode );

+void _glfwSetVideoMode( int *w, int *h, int r, int g, int b, int refresh );

+

+

+#endif // _platform_h_

diff --git a/src/engine/external/glfw/lib/win32/win32_dllmain.c b/src/engine/external/glfw/lib/win32/win32_dllmain.c
new file mode 100644
index 00000000..0cfed043
--- /dev/null
+++ b/src/engine/external/glfw/lib/win32/win32_dllmain.c
@@ -0,0 +1,60 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        win32_dllmain.c

+// Platform:    Windows

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

+#if defined(GLFW_BUILD_DLL)

+

+//========================================================================

+// DllMain()

+//========================================================================

+

+int WINAPI DllMain( HINSTANCE hinst, unsigned long reason, void *x )

+{

+    // NOTE: Some compilers complains about hinst and x never being used -

+    // never mind that (we don't want to use them)!

+

+    switch( reason )

+    {

+    case DLL_PROCESS_ATTACH:

+        // Initializations

+        //glfwInit();   // We don't want to do that now!

+        break;

+    case DLL_PROCESS_DETACH:

+        // Do some cleanup

+        glfwTerminate();

+        break;

+    };

+

+    return 1;

+}

+

+#endif // GLFW_BUILD_DLL

diff --git a/src/engine/external/glfw/lib/win32/win32_enable.c b/src/engine/external/glfw/lib/win32/win32_enable.c
new file mode 100644
index 00000000..5b0d3294
--- /dev/null
+++ b/src/engine/external/glfw/lib/win32/win32_enable.c
@@ -0,0 +1,155 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        win32_enable.c

+// Platform:    Windows

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

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

+//****                  GLFW internal functions                       ****

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

+

+//========================================================================

+// _glfwLLKeyboardProc() - Low level keyboard callback function (used to

+// disable system keys under Windows NT).

+//========================================================================

+

+LRESULT CALLBACK _glfwLLKeyboardProc( int nCode, WPARAM wParam,

+    LPARAM lParam )

+{

+    BOOL syskeys = 0;

+    PKBDLLHOOKSTRUCT p;

+

+    // We are only looking for keyboard events - interpret lParam as a

+    // pointer to a KBDLLHOOKSTRUCT

+    p = (PKBDLLHOOKSTRUCT) lParam;

+

+    // If nCode == HC_ACTION, then we have a keyboard event

+    if( nCode == HC_ACTION )

+    {

+        switch( wParam )

+        {

+            case WM_KEYDOWN:

+            case WM_SYSKEYDOWN:

+            case WM_KEYUP:

+            case WM_SYSKEYUP:

+                // Detect: ALT+TAB, ALT+ESC, ALT+F4, CTRL+ESC,

+                // LWIN, RWIN, APPS (mysterious menu key)

+                syskeys = ( p->vkCode == VK_TAB &&

+                            p->flags & LLKHF_ALTDOWN ) ||

+                          ( p->vkCode == VK_ESCAPE &&

+                            p->flags & LLKHF_ALTDOWN ) ||

+                          ( p->vkCode == VK_F4 &&

+                            p->flags & LLKHF_ALTDOWN ) ||

+                          ( p->vkCode == VK_ESCAPE &&

+                            (GetKeyState(VK_CONTROL) & 0x8000)) ||

+                          p->vkCode == VK_LWIN ||

+                          p->vkCode == VK_RWIN ||

+                          p->vkCode == VK_APPS;

+                break;

+

+            default:

+                break;

+        }

+    }

+

+    // Was it a system key combination (e.g. ALT+TAB)?

+    if( syskeys )

+    {

+        // Pass the key event to our window message loop

+        if( _glfwWin.Opened )

+        {

+            PostMessage( _glfwWin.Wnd, (UINT) wParam, p->vkCode, 0 );

+        }

+

+        // We've taken care of it - don't let the system know about this

+        // key event

+        return 1;

+    }

+    else

+    {

+        // It's a harmless key press, let the system deal with it

+        return CallNextHookEx( _glfwWin.KeyboardHook, nCode, wParam,

+                               lParam );

+    }

+}

+

+

+

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

+//****               Platform implementation functions                ****

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

+

+//========================================================================

+// _glfwPlatformEnableSystemKeys() - Enable system keys

+// _glfwPlatformDisableSystemKeys() - Disable system keys

+//========================================================================

+

+void _glfwPlatformEnableSystemKeys( void )

+{

+    BOOL bOld;

+

+    // Use different methods depending on operating system version

+    if( _glfwLibrary.Sys.WinVer >= _GLFW_WIN_NT4 )

+    {

+        if( _glfwWin.KeyboardHook != NULL )

+        {

+            UnhookWindowsHookEx( _glfwWin.KeyboardHook );

+            _glfwWin.KeyboardHook = NULL;

+        }

+    }

+    else

+    {

+        (void) SystemParametersInfo( SPI_SETSCREENSAVERRUNNING, FALSE,

+                                     &bOld, 0 );

+    }

+}

+

+void _glfwPlatformDisableSystemKeys( void )

+{

+    BOOL bOld;

+

+    // Use different methods depending on operating system version

+    if( _glfwLibrary.Sys.WinVer >= _GLFW_WIN_NT4 )

+    {

+        // Under Windows NT, install a low level keyboard hook

+        _glfwWin.KeyboardHook = SetWindowsHookEx( WH_KEYBOARD_LL,

+                                    _glfwLLKeyboardProc,

+                                    _glfwLibrary.Instance,

+                                    0 );

+    }

+    else

+    {

+        // Under Windows 95/98/ME, fool Windows that a screensaver

+        // is running => prevents ALT+TAB, CTRL+ESC and CTRL+ALT+DEL

+        (void) SystemParametersInfo( SPI_SETSCREENSAVERRUNNING, TRUE,

+                                     &bOld, 0 );

+    }

+}

+

diff --git a/src/engine/external/glfw/lib/win32/win32_fullscreen.c b/src/engine/external/glfw/lib/win32/win32_fullscreen.c
new file mode 100644
index 00000000..fcecee67
--- /dev/null
+++ b/src/engine/external/glfw/lib/win32/win32_fullscreen.c
@@ -0,0 +1,317 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        win32_fullscreen.c

+// Platform:    Windows

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

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

+//****                  GLFW internal functions                       ****

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

+

+//========================================================================

+// _glfwBPP2RGB() - Convert BPP to RGB bits (based on "best guess")

+//========================================================================

+

+static void _glfwBPP2RGB( int bpp, int *r, int *g, int *b )

+{

+    int delta;

+

+    // Special case: BPP = 32

+    if( bpp == 32 ) bpp = 24;

+

+    // Convert "bits per pixel" to red, green & blue sizes

+    *r = *g = *b = bpp / 3;

+    delta = bpp - (*r * 3);

+    if( delta >= 1 )

+    {

+        *g = *g + 1;

+    }

+    if( delta == 2 )

+    {

+        *r = *r + 1;

+    }

+}

+

+

+//========================================================================

+// _glfwGetClosestVideoModeBPP()

+//========================================================================

+

+int _glfwGetClosestVideoModeBPP( int *w, int *h, int *bpp, int *refresh )

+{

+    int     mode, bestmode, match, bestmatch, rr, bestrr, success;

+    DEVMODE dm;

+

+    // Find best match

+    bestmatch = 0x7fffffff;

+    bestrr    = 0x7fffffff;

+    mode = bestmode = 0;

+    do

+    {

+        dm.dmSize = sizeof( DEVMODE );

+        success = EnumDisplaySettings( NULL, mode, &dm );

+        if( success )

+        {

+            match = dm.dmBitsPerPel - *bpp;

+            if( match < 0 ) match = -match;

+            match = ( match << 25 ) |

+                    ( (dm.dmPelsWidth - *w) *

+                      (dm.dmPelsWidth - *w) +

+                      (dm.dmPelsHeight - *h) *

+                      (dm.dmPelsHeight - *h) );

+            if( match < bestmatch )

+            {

+                bestmatch = match;

+                bestmode  = mode;

+                bestrr = (dm.dmDisplayFrequency - *refresh) *

+                         (dm.dmDisplayFrequency - *refresh);

+            }

+            else if( match == bestmatch && *refresh > 0 )

+            {

+                rr = (dm.dmDisplayFrequency - *refresh) *

+                     (dm.dmDisplayFrequency - *refresh);

+                if( rr < bestrr )

+                {

+                    bestmatch = match;

+                    bestmode  = mode;

+                    bestrr    = rr;

+                }

+            }

+        }

+        mode ++;

+    }

+    while( success );

+

+    // Get the parameters for the best matching display mode

+    dm.dmSize = sizeof( DEVMODE );

+    (void) EnumDisplaySettings( NULL, bestmode, &dm );

+

+    // Fill out actual width and height

+    *w = dm.dmPelsWidth;

+    *h = dm.dmPelsHeight;

+

+    // Return bits per pixel

+    *bpp = dm.dmBitsPerPel;

+

+    // Return vertical refresh rate

+    *refresh = dm.dmDisplayFrequency;

+

+    return bestmode;

+}

+

+

+//========================================================================

+// _glfwGetClosestVideoMode()

+//========================================================================

+

+int _glfwGetClosestVideoMode( int *w, int *h, int *r, int *g, int *b,

+    int *refresh )

+{

+    int     bpp, bestmode;

+

+    // Colorbits = sum of red/green/blue bits

+    bpp = *r + *g + *b;

+

+    // If colorbits < 15 (e.g. 0) or >= 24, default to 32 bpp

+    if( bpp < 15 || bpp >= 24 )

+    {

+        bpp = 32;

+    }

+

+    // Find best match

+    bestmode = _glfwGetClosestVideoModeBPP( w, h, &bpp, refresh );

+

+    // Convert "bits per pixel" to red, green & blue sizes

+    _glfwBPP2RGB( bpp, r, g, b );

+

+    return bestmode;

+}

+

+

+//========================================================================

+// Change the current video mode

+//========================================================================

+

+void _glfwSetVideoModeMODE( int mode )

+{

+    DEVMODE dm;

+    int     success;

+

+    // Get the parameters for the best matching display mode

+    dm.dmSize = sizeof( DEVMODE );

+    (void) EnumDisplaySettings( NULL, mode, &dm );

+

+    // Set which fields we want to specify

+    dm.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL;

+

+    // Do we have a prefered refresh rate?

+    if( _glfwWin.DesiredRefreshRate > 0 )

+    {

+        dm.dmFields = dm.dmFields | DM_DISPLAYFREQUENCY;

+	dm.dmDisplayFrequency = _glfwWin.DesiredRefreshRate;

+    }

+

+    // Change display setting

+    dm.dmSize = sizeof( DEVMODE );

+    success = ChangeDisplaySettings( &dm, CDS_FULLSCREEN );

+

+    // If the mode change was not possible, query the current display

+    // settings (we'll use the desktop resolution for fullscreen mode)

+    if( success == DISP_CHANGE_SUCCESSFUL )

+    {

+        _glfwWin.ModeID = mode;

+    }

+    else

+    {

+        _glfwWin.ModeID = ENUM_REGISTRY_SETTINGS;

+        EnumDisplaySettings( NULL, ENUM_REGISTRY_SETTINGS, &dm );

+    }

+

+    // Set the window size to that of the display mode

+    _glfwWin.Width  = dm.dmPelsWidth;

+    _glfwWin.Height = dm.dmPelsHeight;

+}

+

+

+//========================================================================

+// _glfwSetVideoMode() - Change the current video mode

+//========================================================================

+

+void _glfwSetVideoMode( int *w, int *h, int r, int g, int b, int refresh )

+{

+    int     bestmode;

+

+    // Find a best match mode

+    bestmode = _glfwGetClosestVideoMode( w, h, &r, &g, &b, &refresh );

+

+    // Change mode

+    _glfwSetVideoModeMODE( bestmode );

+}

+

+

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

+//****                    GLFW user functions                         ****

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

+

+//========================================================================

+// _glfwPlatformGetVideoModes() - Get a list of available video modes

+//========================================================================

+

+int _glfwPlatformGetVideoModes( GLFWvidmode *list, int maxcount )

+{

+    int count, success, mode, i, j;

+    int m1, m2, bpp, r, g, b;

+    DEVMODE dm;

+

+    // Loop through all video modes and extract all the UNIQUE modes

+    count = 0;

+    mode  = 0;

+    do

+    {

+        // Get video mode properties

+        dm.dmSize = sizeof( DEVMODE );

+        success = EnumDisplaySettings( NULL, mode, &dm );

+

+        // Is it a valid mode? (only list depths >= 15 bpp)

+        if( success && dm.dmBitsPerPel >= 15 )

+        {

+            // Convert to RGB, and back to bpp ("mask out" alpha bits etc)

+            _glfwBPP2RGB( dm.dmBitsPerPel, &r, &g, &b );

+            bpp = r + g + b;

+

+            // Mode "code" for this mode

+            m1 = (bpp << 25) | (dm.dmPelsWidth * dm.dmPelsHeight);

+

+            // Insert mode in list (sorted), and avoid duplicates

+            for( i = 0; i < count; i ++ )

+            {

+                // Mode "code" for already listed mode

+                bpp = list[i].RedBits + list[i].GreenBits +

+                      list[i].BlueBits;

+                m2 = (bpp << 25) | (list[i].Width * list[i].Height);

+                if( m1 <= m2 )

+                {

+                    break;

+                }

+            }

+

+            // New entry at the end of the list?

+            if( i >= count )

+            {

+                list[count].Width     = dm.dmPelsWidth;

+                list[count].Height    = dm.dmPelsHeight;

+                list[count].RedBits   = r;

+                list[count].GreenBits = g;

+                list[count].BlueBits  = b;

+                count ++;

+            }

+            // Insert new entry in the list?

+            else if( m1 < m2 )

+            {

+                for( j = count; j > i; j -- )

+                {

+                    list[j] = list[j-1];

+                }

+                list[i].Width     = dm.dmPelsWidth;

+                list[i].Height    = dm.dmPelsHeight;

+                list[i].RedBits   = r;

+                list[i].GreenBits = g;

+                list[i].BlueBits  = b;

+                count ++;

+            }

+        }

+        mode ++;

+    }

+    while( success && (count < maxcount) );

+

+    return count;

+}

+

+

+//========================================================================

+// _glfwPlatformGetDesktopMode() - Get the desktop video mode

+//========================================================================

+

+void _glfwPlatformGetDesktopMode( GLFWvidmode *mode )

+{

+    DEVMODE dm;

+

+    // Get desktop display mode

+    dm.dmSize = sizeof( DEVMODE );

+    (void) EnumDisplaySettings( NULL, ENUM_REGISTRY_SETTINGS, &dm );

+

+    // Return desktop mode parameters

+    mode->Width  = dm.dmPelsWidth;

+    mode->Height = dm.dmPelsHeight;

+    _glfwBPP2RGB( dm.dmBitsPerPel, &mode->RedBits, &mode->GreenBits,

+                  &mode->BlueBits );

+}

+

+

diff --git a/src/engine/external/glfw/lib/win32/win32_glext.c b/src/engine/external/glfw/lib/win32/win32_glext.c
new file mode 100644
index 00000000..00d2767d
--- /dev/null
+++ b/src/engine/external/glfw/lib/win32/win32_glext.c
@@ -0,0 +1,101 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        win32_glext.c

+// Platform:    Windows

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

+//========================================================================

+// We use the WGL_EXT_extensions_string if it is available, or

+// WGL_ARB_extensions_string if it is available.

+//========================================================================

+

+typedef const char *(APIENTRY * WGLGETEXTENSIONSSTRINGEXT_T)( void );

+typedef const char *(APIENTRY * WGLGETEXTENSIONSSTRINGARB_T)( HDC hdc );

+

+

+

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

+//****               Platform implementation functions                ****

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

+

+//========================================================================

+// Check if an OpenGL extension is available at runtime (Windows version checks

+// for WGL extensions)

+//========================================================================

+

+int _glfwPlatformExtensionSupported( const char *extension )

+{

+    const GLubyte *extensions;

+    WGLGETEXTENSIONSSTRINGEXT_T _wglGetExtensionsStringEXT;

+    WGLGETEXTENSIONSSTRINGARB_T _wglGetExtensionsStringARB;

+

+    // Try wglGetExtensionsStringEXT

+    _wglGetExtensionsStringEXT = (WGLGETEXTENSIONSSTRINGEXT_T)

+        wglGetProcAddress( "wglGetExtensionsStringEXT" );

+    if( _wglGetExtensionsStringEXT != NULL )

+    {

+        extensions = (GLubyte *) _wglGetExtensionsStringEXT();

+        if( extensions != NULL )

+        {

+            if( _glfwStringInExtensionString( extension, extensions ) )

+            {

+                return GL_TRUE;

+            }

+        }

+    }

+

+    // Try wglGetExtensionsStringARB

+    _wglGetExtensionsStringARB = (WGLGETEXTENSIONSSTRINGARB_T)

+        wglGetProcAddress( "wglGetExtensionsStringARB" );

+    if( _wglGetExtensionsStringARB != NULL )

+    {

+        extensions = (GLubyte *) _wglGetExtensionsStringARB(_glfwWin.DC);

+        if( extensions != NULL )

+        {

+            if( _glfwStringInExtensionString( extension, extensions ) )

+            {

+                return GL_TRUE;

+            }

+        }

+    }

+

+    return GL_FALSE;

+}

+

+

+//========================================================================

+// Get the function pointer to an OpenGL function

+//========================================================================

+

+void * _glfwPlatformGetProcAddress( const char *procname )

+{

+    return (void *) wglGetProcAddress( procname );

+}

+

diff --git a/src/engine/external/glfw/lib/win32/win32_init.c b/src/engine/external/glfw/lib/win32/win32_init.c
new file mode 100644
index 00000000..41d7150a
--- /dev/null
+++ b/src/engine/external/glfw/lib/win32/win32_init.c
@@ -0,0 +1,356 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        win32_init.c

+// Platform:    Windows

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+// With the Borland C++ compiler, we want to disable FPU exceptions

+#ifdef __BORLANDC__

+#include <float.h>

+#endif // __BORLANDC__

+

+

+

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

+//****                  GLFW internal functions                       ****

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

+

+//========================================================================

+// _glfwInitLibraries() - Load necessary libraries (DLLs)

+//========================================================================

+

+static int _glfwInitLibraries( void )

+{

+    // gdi32.dll (OpenGL pixel format functions & SwapBuffers)

+#ifndef _GLFW_NO_DLOAD_GDI32

+    _glfwLibrary.Libs.gdi32 = LoadLibrary( "gdi32.dll" );

+    if( _glfwLibrary.Libs.gdi32 != NULL )

+    {

+        _glfwLibrary.Libs.ChoosePixelFormat   = (CHOOSEPIXELFORMAT_T)

+            GetProcAddress( _glfwLibrary.Libs.gdi32, "ChoosePixelFormat" );

+        _glfwLibrary.Libs.DescribePixelFormat = (DESCRIBEPIXELFORMAT_T)

+            GetProcAddress( _glfwLibrary.Libs.gdi32, "DescribePixelFormat" );

+        _glfwLibrary.Libs.GetPixelFormat      = (GETPIXELFORMAT_T)

+            GetProcAddress( _glfwLibrary.Libs.gdi32, "GetPixelFormat" );

+        _glfwLibrary.Libs.SetPixelFormat      = (SETPIXELFORMAT_T)

+            GetProcAddress( _glfwLibrary.Libs.gdi32, "SetPixelFormat" );

+        _glfwLibrary.Libs.SwapBuffers         = (SWAPBUFFERS_T)

+            GetProcAddress( _glfwLibrary.Libs.gdi32, "SwapBuffers" );

+        if( _glfwLibrary.Libs.ChoosePixelFormat   == NULL ||

+            _glfwLibrary.Libs.DescribePixelFormat == NULL ||

+            _glfwLibrary.Libs.GetPixelFormat      == NULL ||

+            _glfwLibrary.Libs.SetPixelFormat      == NULL ||

+            _glfwLibrary.Libs.SwapBuffers         == NULL )

+        {

+            FreeLibrary( _glfwLibrary.Libs.gdi32 );

+            _glfwLibrary.Libs.gdi32 = NULL;

+            return GL_FALSE;

+        }

+    }

+    else

+    {

+        return GL_FALSE;

+    }

+#endif // _GLFW_NO_DLOAD_GDI32

+

+    // winmm.dll (for joystick and timer support)

+#ifndef _GLFW_NO_DLOAD_WINMM

+    _glfwLibrary.Libs.winmm = LoadLibrary( "winmm.dll" );

+    if( _glfwLibrary.Libs.winmm != NULL )

+    {

+        _glfwLibrary.Libs.joyGetDevCapsA = (JOYGETDEVCAPSA_T)

+            GetProcAddress( _glfwLibrary.Libs.winmm, "joyGetDevCapsA" );

+        _glfwLibrary.Libs.joyGetPos      = (JOYGETPOS_T)

+            GetProcAddress( _glfwLibrary.Libs.winmm, "joyGetPos" );

+        _glfwLibrary.Libs.joyGetPosEx    = (JOYGETPOSEX_T)

+            GetProcAddress( _glfwLibrary.Libs.winmm, "joyGetPosEx" );

+        _glfwLibrary.Libs.timeGetTime    = (TIMEGETTIME_T)

+            GetProcAddress( _glfwLibrary.Libs.winmm, "timeGetTime" );

+        if( _glfwLibrary.Libs.joyGetDevCapsA == NULL ||

+            _glfwLibrary.Libs.joyGetPos      == NULL ||

+            _glfwLibrary.Libs.joyGetPosEx    == NULL ||

+            _glfwLibrary.Libs.timeGetTime    == NULL )

+        {

+            FreeLibrary( _glfwLibrary.Libs.winmm );

+            _glfwLibrary.Libs.winmm = NULL;

+            return GL_FALSE;

+        }

+    }

+    else

+    {

+        return GL_FALSE;

+    }

+#endif // _GLFW_NO_DLOAD_WINMM

+

+    return GL_TRUE;

+}

+

+

+//========================================================================

+// _glfwFreeLibraries() - Unload used libraries (DLLs)

+//========================================================================

+

+static void _glfwFreeLibraries( void )

+{

+    // gdi32.dll

+#ifndef _GLFW_NO_DLOAD_GDI32

+    if( _glfwLibrary.Libs.gdi32 != NULL )

+    {

+        FreeLibrary( _glfwLibrary.Libs.gdi32 );

+        _glfwLibrary.Libs.gdi32 = NULL;

+    }

+#endif // _GLFW_NO_DLOAD_GDI32

+

+    // winmm.dll

+#ifndef _GLFW_NO_DLOAD_WINMM

+    if( _glfwLibrary.Libs.winmm != NULL )

+    {

+        FreeLibrary( _glfwLibrary.Libs.winmm );

+        _glfwLibrary.Libs.winmm = NULL;

+    }

+#endif // _GLFW_NO_DLOAD_WINMM

+}

+

+

+//========================================================================

+// _glfwInitThreads() - Initialize GLFW thread package

+//========================================================================

+

+static void _glfwInitThreads( void )

+{

+    // Initialize critical section handle

+    InitializeCriticalSection( &_glfwThrd.CriticalSection );

+

+    // The first thread (the main thread) has ID 0

+    _glfwThrd.NextID = 0;

+

+    // Fill out information about the main thread (this thread)

+    _glfwThrd.First.ID       = _glfwThrd.NextID ++;

+    _glfwThrd.First.Function = NULL;

+    _glfwThrd.First.Handle   = GetCurrentThread();

+    _glfwThrd.First.WinID    = GetCurrentThreadId();

+    _glfwThrd.First.Previous = NULL;

+    _glfwThrd.First.Next     = NULL;

+}

+

+

+//========================================================================

+// _glfwTerminateThreads() - Terminate GLFW thread package

+//========================================================================

+

+static void _glfwTerminateThreads( void )

+{

+    _GLFWthread *t, *t_next;

+

+    // Enter critical section

+    ENTER_THREAD_CRITICAL_SECTION

+

+    // Kill all threads (NOTE: THE USER SHOULD WAIT FOR ALL THREADS TO

+    // DIE, _BEFORE_ CALLING glfwTerminate()!!!)

+    t = _glfwThrd.First.Next;

+    while( t != NULL )

+    {

+        // Get pointer to next thread

+        t_next = t->Next;

+

+        // Simply murder the process, no mercy!

+        if( TerminateThread( t->Handle, 0 ) )

+        {

+            // Close thread handle

+            CloseHandle( t->Handle );

+

+            // Free memory allocated for this thread

+            free( (void *) t );

+        }

+

+        // Select next thread in list

+        t = t_next;

+    }

+

+    // Leave critical section

+    LEAVE_THREAD_CRITICAL_SECTION

+

+    // Delete critical section handle

+    DeleteCriticalSection( &_glfwThrd.CriticalSection );

+}

+

+

+//========================================================================

+// _glfwTerminate_atexit() - Terminate GLFW when exiting application

+//========================================================================

+

+void _glfwTerminate_atexit( void )

+{

+    glfwTerminate();

+}

+

+

+

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

+//****               Platform implementation functions                ****

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

+

+//========================================================================

+// _glfwPlatformInit() - Initialize various GLFW state

+//========================================================================

+

+int _glfwPlatformInit( void )

+{

+    OSVERSIONINFO osi;

+

+    // To make SetForegroundWindow() work as we want, we need to fiddle

+    // with the FOREGROUNDLOCKTIMEOUT system setting (we do this as early

+    // as possible in the hope of still being the foreground process)

+    SystemParametersInfo( SPI_GETFOREGROUNDLOCKTIMEOUT, 0,

+                          &_glfwLibrary.Sys.ForegroundLockTimeout, 0 );

+    SystemParametersInfo( SPI_SETFOREGROUNDLOCKTIMEOUT, 0, (LPVOID)0,

+                          SPIF_SENDCHANGE );

+

+    // Check which OS version we are running

+    osi.dwOSVersionInfoSize = sizeof( OSVERSIONINFO );

+    GetVersionEx( &osi );

+    _glfwLibrary.Sys.WinVer = _GLFW_WIN_UNKNOWN;

+    if( osi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS )

+    {

+        if( osi.dwMajorVersion == 4 && osi.dwMinorVersion < 10 )

+        {

+            _glfwLibrary.Sys.WinVer = _GLFW_WIN_95;

+        }

+        else if( osi.dwMajorVersion == 4 && osi.dwMinorVersion < 90 )

+        {

+            _glfwLibrary.Sys.WinVer = _GLFW_WIN_98;

+        }

+        else if( osi.dwMajorVersion == 4 && osi.dwMinorVersion == 90 )

+        {

+            _glfwLibrary.Sys.WinVer = _GLFW_WIN_ME;

+        }

+        else if( osi.dwMajorVersion >= 4 )

+        {

+            _glfwLibrary.Sys.WinVer = _GLFW_WIN_UNKNOWN_9x;

+        }

+    }

+    else if( osi.dwPlatformId == VER_PLATFORM_WIN32_NT )

+    {

+        if( osi.dwMajorVersion == 4 && osi.dwMinorVersion == 0 )

+        {

+            _glfwLibrary.Sys.WinVer = _GLFW_WIN_NT4;

+        }

+        else if( osi.dwMajorVersion == 5 && osi.dwMinorVersion == 0 )

+        {

+            _glfwLibrary.Sys.WinVer = _GLFW_WIN_2K;

+        }

+        else if( osi.dwMajorVersion == 5 && osi.dwMinorVersion == 1 )

+        {

+            _glfwLibrary.Sys.WinVer = _GLFW_WIN_XP;

+        }

+        else if( osi.dwMajorVersion == 5 && osi.dwMinorVersion == 2 )

+        {

+            _glfwLibrary.Sys.WinVer = _GLFW_WIN_NET_SERVER;

+        }

+        else if( osi.dwMajorVersion >= 5 )

+        {

+            _glfwLibrary.Sys.WinVer = _GLFW_WIN_UNKNOWN_NT;

+        }

+    }

+

+    // Do we have Unicode support?

+    if( _glfwLibrary.Sys.WinVer >= _GLFW_WIN_NT4 )

+    {

+        // Windows NT/2000/XP/.NET has Unicode support

+        _glfwLibrary.Sys.HasUnicode = GL_TRUE;

+    }

+    else

+    {

+        // Windows 9x/ME does not have Unicode support

+        _glfwLibrary.Sys.HasUnicode = GL_FALSE;

+    }

+

+    // Load libraries (DLLs)

+    if( !_glfwInitLibraries() )

+    {

+        return GL_FALSE;

+    }

+

+    // With the Borland C++ compiler, we want to disable FPU exceptions

+    // (this is recommended for OpenGL applications under Windows)

+#ifdef __BORLANDC__

+    _control87( MCW_EM, MCW_EM );

+#endif

+

+    // Retrieve GLFW instance handle

+    _glfwLibrary.Instance = GetModuleHandle( NULL );

+

+    // System keys are not disabled

+    _glfwWin.KeyboardHook = NULL;

+

+    // Initialise thread package

+    _glfwInitThreads();

+

+    // Install atexit() routine

+    atexit( _glfwTerminate_atexit );

+

+    // Start the timer

+    _glfwInitTimer();

+

+    return GL_TRUE;

+}

+

+

+//========================================================================

+// _glfwPlatformTerminate() - Close window and kill all threads

+//========================================================================

+

+int _glfwPlatformTerminate( void )

+{

+    // Only the main thread is allowed to do this...

+    if( GetCurrentThreadId() != _glfwThrd.First.WinID )

+    {

+        return GL_FALSE;

+    }

+

+    // Close OpenGL window

+    glfwCloseWindow();

+

+    // Kill thread package

+    _glfwTerminateThreads();

+

+    // Enable system keys again (if they were disabled)

+    glfwEnable( GLFW_SYSTEM_KEYS );

+

+    // Unload libraries (DLLs)

+    _glfwFreeLibraries();

+

+    // Restore FOREGROUNDLOCKTIMEOUT system setting

+    SystemParametersInfo( SPI_SETFOREGROUNDLOCKTIMEOUT, 0,

+                          (LPVOID)_glfwLibrary.Sys.ForegroundLockTimeout,

+                          SPIF_SENDCHANGE );

+

+    return GL_TRUE;

+}

+

diff --git a/src/engine/external/glfw/lib/win32/win32_joystick.c b/src/engine/external/glfw/lib/win32/win32_joystick.c
new file mode 100644
index 00000000..5ab00319
--- /dev/null
+++ b/src/engine/external/glfw/lib/win32/win32_joystick.c
@@ -0,0 +1,234 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        win32_joystick.c

+// Platform:    Windows

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

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

+//****                  GLFW internal functions                       ****

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

+

+//========================================================================

+// _glfwJoystickPresent() - Return GL_TRUE if joystick is present,

+// else return GL_FALSE.

+//========================================================================

+

+static int _glfwJoystickPresent( int joy )

+{

+    JOYINFO ji;

+

+    // Windows NT 4.0 MMSYSTEM only supports 2 sticks (other Windows

+    // versions support 16 sticks)

+    if( _glfwLibrary.Sys.WinVer == _GLFW_WIN_NT4 && joy > GLFW_JOYSTICK_2 )

+    {

+        return GL_FALSE;

+    }

+

+    // Is it a valid stick ID (Windows don't support more than 16 sticks)?

+    if( joy < GLFW_JOYSTICK_1 || joy > GLFW_JOYSTICK_16 )

+    {

+        return GL_FALSE;

+    }

+

+    // Is the joystick present?

+    if( _glfw_joyGetPos( joy - GLFW_JOYSTICK_1, &ji ) != JOYERR_NOERROR )

+    {

+        return GL_FALSE;

+    }

+

+    return GL_TRUE;

+}

+

+

+//========================================================================

+// _glfwCalcJoystickPos() - Calculate joystick position

+//========================================================================

+

+static float _glfwCalcJoystickPos( DWORD pos, DWORD min, DWORD max )

+{

+    float fpos = (float) pos;

+    float fmin = (float) min;

+    float fmax = (float) max;

+    return (2.0f*(fpos - fmin) / (fmax - fmin)) - 1.0f;

+}

+

+

+

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

+//****               Platform implementation functions                ****

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

+

+//========================================================================

+// _glfwPlatformGetJoystickParam() - Determine joystick capabilities

+//========================================================================

+

+int _glfwPlatformGetJoystickParam( int joy, int param )

+{

+    JOYCAPS jc;

+

+//  return 0;

+

+    // Is joystick present?

+    if( !_glfwJoystickPresent( joy ) )

+    {

+        return 0;

+    }

+

+    // We got this far, the joystick is present

+    if( param == GLFW_PRESENT )

+    {

+        return GL_TRUE;

+    }

+

+    // Get joystick capabilities

+    _glfw_joyGetDevCaps( joy - GLFW_JOYSTICK_1, &jc, sizeof(JOYCAPS) );

+

+    switch( param )

+    {

+    case GLFW_AXES:

+        // Return number of joystick axes

+        return jc.wNumAxes;

+

+    case GLFW_BUTTONS:

+        // Return number of joystick axes

+        return jc.wNumButtons;

+

+    default:

+        break;

+    }

+

+    return 0;

+}

+

+

+//========================================================================

+// _glfwPlatformGetJoystickPos() - Get joystick axis positions

+//========================================================================

+

+int _glfwPlatformGetJoystickPos( int joy, float *pos, int numaxes )

+{

+    JOYCAPS   jc;

+    JOYINFOEX ji;

+    int       axis;

+

+//  return 0;

+

+    // Is joystick present?

+    if( !_glfwJoystickPresent( joy ) )

+    {

+        return 0;

+    }

+

+    // Get joystick capabilities

+    _glfw_joyGetDevCaps( joy - GLFW_JOYSTICK_1, &jc, sizeof(JOYCAPS) );

+

+    // Get joystick state

+    ji.dwSize = sizeof( JOYINFOEX );

+    ji.dwFlags = JOY_RETURNX | JOY_RETURNY | JOY_RETURNZ |

+                 JOY_RETURNR | JOY_RETURNU | JOY_RETURNV;

+    _glfw_joyGetPosEx( joy - GLFW_JOYSTICK_1, &ji );

+

+    // Get position values for all axes

+    axis = 0;

+    if( axis < numaxes )

+    {

+        pos[ axis++ ] = _glfwCalcJoystickPos( ji.dwXpos, jc.wXmin,

+                                              jc.wXmax );

+    }

+    if( axis < numaxes )

+    {

+        pos[ axis++ ] = -_glfwCalcJoystickPos( ji.dwYpos, jc.wYmin,

+                                               jc.wYmax );

+    }

+    if( axis < numaxes && jc.wCaps & JOYCAPS_HASZ )

+    {

+        pos[ axis++ ] = _glfwCalcJoystickPos( ji.dwZpos, jc.wZmin,

+                                              jc.wZmax );

+    }

+    if( axis < numaxes && jc.wCaps & JOYCAPS_HASR )

+    {

+        pos[ axis++ ] = _glfwCalcJoystickPos( ji.dwRpos, jc.wRmin,

+                                              jc.wRmax );

+    }

+    if( axis < numaxes && jc.wCaps & JOYCAPS_HASU )

+    {

+        pos[ axis++ ] = _glfwCalcJoystickPos( ji.dwUpos, jc.wUmin,

+                                              jc.wUmax );

+    }

+    if( axis < numaxes && jc.wCaps & JOYCAPS_HASV )

+    {

+        pos[ axis++ ] = -_glfwCalcJoystickPos( ji.dwVpos, jc.wVmin,

+                                               jc.wVmax );

+    }

+

+    // Return number of returned axes

+    return axis;

+}

+

+

+//========================================================================

+// _glfwPlatformGetJoystickButtons() - Get joystick button states

+//========================================================================

+

+int _glfwPlatformGetJoystickButtons( int joy, unsigned char *buttons,

+    int numbuttons )

+{

+    JOYCAPS   jc;

+    JOYINFOEX ji;

+    int       button;

+

+//  return 0;

+

+    // Is joystick present?

+    if( !_glfwJoystickPresent( joy ) )

+    {

+        return 0;

+    }

+

+    // Get joystick capabilities

+    _glfw_joyGetDevCaps( joy - GLFW_JOYSTICK_1, &jc, sizeof(JOYCAPS) );

+

+    // Get joystick state

+    ji.dwSize = sizeof( JOYINFOEX );

+    ji.dwFlags = JOY_RETURNBUTTONS;

+    _glfw_joyGetPosEx( joy - GLFW_JOYSTICK_1, &ji );

+

+    // Get states of all requested buttons

+    button = 0;

+    while( button < numbuttons && button < (int) jc.wNumButtons )

+    {

+        buttons[ button ] = (unsigned char)

+            (ji.dwButtons & (1UL << button) ? GLFW_PRESS : GLFW_RELEASE);

+        button ++;

+    }

+

+    return button;

+}

+

diff --git a/src/engine/external/glfw/lib/win32/win32_thread.c b/src/engine/external/glfw/lib/win32/win32_thread.c
new file mode 100644
index 00000000..159347a7
--- /dev/null
+++ b/src/engine/external/glfw/lib/win32/win32_thread.c
@@ -0,0 +1,511 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        win32_thread.c

+// Platform:    Windows

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

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

+// This is an implementation of POSIX "compatible" condition variables for

+// Win32, as described by Douglas C. Schmidt and Irfan Pyarali:

+// http://www.cs.wustl.edu/~schmidt/win32-cv-1.html

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

+

+enum {

+    _GLFW_COND_SIGNAL     = 0,

+    _GLFW_COND_BROADCAST  = 1

+};

+

+typedef struct {

+    // Signal and broadcast event HANDLEs

+    HANDLE events[ 2 ];

+

+    // Count of the number of waiters

+    unsigned int waiters_count;

+

+    // Serialize access to <waiters_count>

+    CRITICAL_SECTION waiters_count_lock;

+} _GLFWcond;

+

+

+

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

+//****                  GLFW internal functions                       ****

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

+

+//========================================================================

+// _glfwNewThread() - This is simply a "wrapper" for calling the user

+// thread function.

+//========================================================================

+

+DWORD WINAPI _glfwNewThread( LPVOID lpParam )

+{

+    GLFWthreadfun threadfun;

+    _GLFWthread   *t;

+

+    // Get pointer to thread information for current thread

+    t = _glfwGetThreadPointer( _glfwPlatformGetThreadID() );

+    if( t == NULL )

+    {

+        return 0;

+    }

+

+    // Get user thread function pointer

+    threadfun = t->Function;

+

+    // Call the user thread function

+    threadfun( (void *) lpParam );

+

+    // Remove thread from thread list

+    ENTER_THREAD_CRITICAL_SECTION

+    _glfwRemoveThread( t );

+    LEAVE_THREAD_CRITICAL_SECTION

+

+    // When the thread function returns, the thread will die...

+    return 0;

+}

+

+

+

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

+//****                     GLFW user functions                        ****

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

+

+//========================================================================

+// _glfwPlatformCreateThread() - Create a new thread

+//========================================================================

+

+GLFWthread _glfwPlatformCreateThread( GLFWthreadfun fun, void *arg )

+{

+    GLFWthread  ID;

+    _GLFWthread *t, *t_tmp;

+    HANDLE      hThread;

+    DWORD       dwThreadId;

+

+    // Enter critical section

+    ENTER_THREAD_CRITICAL_SECTION

+

+    // Create a new thread information memory area

+    t = (_GLFWthread *) malloc( sizeof(_GLFWthread) );

+    if( t == NULL )

+    {

+        // Leave critical section

+        LEAVE_THREAD_CRITICAL_SECTION

+        return -1;

+    }

+

+    // Get a new unique thread id

+    ID = _glfwThrd.NextID ++;

+

+    // Store thread information in the thread list

+    t->Function = fun;

+    t->ID       = ID;

+

+    // Create thread

+    hThread = CreateThread(

+        NULL,              // Default security attributes

+        0,                 // Default stack size (1 MB)

+        _glfwNewThread,    // Thread function (a wrapper function)

+        (LPVOID)arg,       // Argument to thread is the user argument

+        0,                 // Default creation flags

+        &dwThreadId        // Returned thread identifier

+    );

+

+    // Did the thread creation fail?

+    if( hThread == NULL )

+    {

+        free( (void *) t );

+        LEAVE_THREAD_CRITICAL_SECTION

+        return -1;

+    }

+

+    // Store more thread information in the thread list

+    t->Handle = hThread;

+    t->WinID  = dwThreadId;

+

+    // Append thread to thread list

+    t_tmp = &_glfwThrd.First;

+    while( t_tmp->Next != NULL )

+    {

+        t_tmp = t_tmp->Next;

+    }

+    t_tmp->Next = t;

+    t->Previous = t_tmp;

+    t->Next     = NULL;

+

+    // Leave critical section

+    LEAVE_THREAD_CRITICAL_SECTION

+

+    // Return the GLFW thread ID

+    return ID;

+}

+

+

+//========================================================================

+// _glfwPlatformDestroyThread() - Kill a thread. NOTE: THIS IS A VERY

+// DANGEROUS OPERATION, AND SHOULD NOT BE USED EXCEPT IN EXTREME

+// SITUATIONS!

+//========================================================================

+

+void _glfwPlatformDestroyThread( GLFWthread ID )

+{

+    _GLFWthread *t;

+

+    // Enter critical section

+    ENTER_THREAD_CRITICAL_SECTION

+

+    // Get thread information pointer

+    t = _glfwGetThreadPointer( ID );

+    if( t == NULL )

+    {

+        LEAVE_THREAD_CRITICAL_SECTION

+        return;

+    }

+

+    // Simply murder the process, no mercy!

+    if( TerminateThread( t->Handle, 0 ) )

+    {

+        // Close thread handle

+        CloseHandle( t->Handle );

+

+        // Remove thread from thread list

+        _glfwRemoveThread( t );

+    }

+

+    // Leave critical section

+    LEAVE_THREAD_CRITICAL_SECTION

+}

+

+

+//========================================================================

+// _glfwPlatformWaitThread() - Wait for a thread to die

+//========================================================================

+

+int _glfwPlatformWaitThread( GLFWthread ID, int waitmode )

+{

+    DWORD       result;

+    HANDLE      hThread;

+    _GLFWthread *t;

+

+    // Enter critical section

+    ENTER_THREAD_CRITICAL_SECTION

+

+    // Get thread information pointer

+    t = _glfwGetThreadPointer( ID );

+

+    // Is the thread already dead?

+    if( t == NULL )

+    {

+        LEAVE_THREAD_CRITICAL_SECTION

+        return GL_TRUE;

+    }

+

+    // Get thread handle

+    hThread = t->Handle;

+

+    // Leave critical section

+    LEAVE_THREAD_CRITICAL_SECTION

+

+    // Wait for thread to die

+    if( waitmode == GLFW_WAIT )

+    {

+        result = WaitForSingleObject( hThread, INFINITE );

+    }

+    else if( waitmode == GLFW_NOWAIT )

+    {

+        result = WaitForSingleObject( hThread, 0 );

+    }

+    else

+    {

+        return GL_FALSE;

+    }

+

+    // Did we have a time-out?

+    if( result == WAIT_TIMEOUT )

+    {

+        return GL_FALSE;

+    }

+    return GL_TRUE;

+}

+

+

+//========================================================================

+// _glfwPlatformGetThreadID() - Return the thread ID for the current

+// thread

+//========================================================================

+

+GLFWthread _glfwPlatformGetThreadID( void )

+{

+    _GLFWthread *t;

+    GLFWthread  ID = -1;

+    DWORD       WinID;

+

+    // Get Windows thread ID

+    WinID = GetCurrentThreadId();

+

+    // Enter critical section (to avoid an inconsistent thread list)

+    ENTER_THREAD_CRITICAL_SECTION

+

+    // Loop through entire list of threads to find the matching Windows

+    // thread ID

+    for( t = &_glfwThrd.First; t != NULL; t = t->Next )

+    {

+        if( t->WinID == WinID )

+        {

+            ID = t->ID;

+            break;

+        }

+    }

+

+    // Leave critical section

+    LEAVE_THREAD_CRITICAL_SECTION

+

+    // Return the found GLFW thread identifier

+    return ID;

+}

+

+

+//========================================================================

+// _glfwPlatformCreateMutex() - Create a mutual exclusion object

+//========================================================================

+

+GLFWmutex _glfwPlatformCreateMutex( void )

+{

+    CRITICAL_SECTION *mutex;

+

+    // Allocate memory for mutex

+    mutex = (CRITICAL_SECTION *) malloc( sizeof(CRITICAL_SECTION) );

+    if( !mutex )

+    {

+        return NULL;

+    }

+

+    // Initialize mutex

+    InitializeCriticalSection( mutex );

+

+    // Cast to GLFWmutex and return

+    return (GLFWmutex) mutex;

+}

+

+

+//========================================================================

+// glfwDestroyMutex() - Destroy a mutual exclusion object

+//========================================================================

+

+void _glfwPlatformDestroyMutex( GLFWmutex mutex )

+{

+    // Destroy mutex

+    DeleteCriticalSection( (CRITICAL_SECTION *) mutex );

+    free( mutex );

+}

+

+

+//========================================================================

+// _glfwPlatformLockMutex() - Request access to a mutex

+//========================================================================

+

+void _glfwPlatformLockMutex( GLFWmutex mutex )

+{

+    // Wait for mutex to be released

+    EnterCriticalSection( (CRITICAL_SECTION *) mutex );

+}

+

+

+//========================================================================

+// _glfwPlatformUnlockMutex() - Release a mutex

+//========================================================================

+

+void _glfwPlatformUnlockMutex( GLFWmutex mutex )

+{

+    // Release mutex

+    LeaveCriticalSection( (CRITICAL_SECTION *) mutex );

+}

+

+

+//========================================================================

+// _glfwPlatformCreateCond() - Create a new condition variable object

+//========================================================================

+

+GLFWcond _glfwPlatformCreateCond( void )

+{

+    _GLFWcond   *cond;

+

+    // Allocate memory for condition variable

+    cond = (_GLFWcond *) malloc( sizeof(_GLFWcond) );

+    if( !cond )

+    {

+        return NULL;

+    }

+

+    // Initialize condition variable

+    cond->waiters_count = 0;

+    cond->events[ _GLFW_COND_SIGNAL ]    = CreateEvent( NULL, FALSE,

+                                                        FALSE, NULL );

+    cond->events[ _GLFW_COND_BROADCAST ] = CreateEvent( NULL, TRUE,

+                                                        FALSE, NULL );

+    InitializeCriticalSection( &cond->waiters_count_lock );

+

+    // Cast to GLFWcond and return

+    return (GLFWcond) cond;

+}

+

+

+//========================================================================

+// _glfwPlatformDestroyCond() - Destroy a condition variable object

+//========================================================================

+

+void _glfwPlatformDestroyCond( GLFWcond cond )

+{

+    // Close the condition variable handles

+    CloseHandle( ((_GLFWcond *)cond)->events[ _GLFW_COND_SIGNAL ] );

+    CloseHandle( ((_GLFWcond *)cond)->events[ _GLFW_COND_BROADCAST ] );

+

+    // Delete critical section

+    DeleteCriticalSection( &((_GLFWcond *)cond)->waiters_count_lock );

+

+    // Free memory for condition variable

+    free( (void *) cond );

+}

+

+

+//========================================================================

+// _glfwPlatformWaitCond() - Wait for a condition to be raised

+//========================================================================

+

+void _glfwPlatformWaitCond( GLFWcond cond, GLFWmutex mutex,

+    double timeout )

+{

+    _GLFWcond *cv = (_GLFWcond *) cond;

+    int       result, last_waiter;

+    DWORD     timeout_ms;

+

+    // Avoid race conditions

+    EnterCriticalSection( &cv->waiters_count_lock );

+    cv->waiters_count ++;

+    LeaveCriticalSection( &cv->waiters_count_lock );

+

+    // It's ok to release the mutex here since Win32 manual-reset events

+    // maintain state when used with SetEvent()

+    LeaveCriticalSection( (CRITICAL_SECTION *) mutex );

+

+    // Translate timeout into milliseconds

+    if( timeout >= GLFW_INFINITY )

+    {

+        timeout_ms = INFINITE;

+    }

+    else

+    {

+        timeout_ms = (DWORD) (1000.0 * timeout + 0.5);

+        if( timeout_ms <= 0 )

+        {

+            timeout_ms = 1;

+        }

+    }

+

+    // Wait for either event to become signaled due to glfwSignalCond or

+    // glfwBroadcastCond being called

+    result = WaitForMultipleObjects( 2, cv->events, FALSE, timeout_ms );

+

+    // Check if we are the last waiter

+    EnterCriticalSection( &cv->waiters_count_lock );

+    cv->waiters_count --;

+    last_waiter = (result == WAIT_OBJECT_0 + _GLFW_COND_BROADCAST) &&

+                  (cv->waiters_count == 0);

+    LeaveCriticalSection( &cv->waiters_count_lock );

+

+    // Some thread called glfwBroadcastCond

+    if( last_waiter )

+    {

+        // We're the last waiter to be notified or to stop waiting, so

+        // reset the manual event

+        ResetEvent( cv->events[ _GLFW_COND_BROADCAST ] );

+    }

+

+    // Reacquire the mutex

+    EnterCriticalSection( (CRITICAL_SECTION *) mutex );

+}

+

+

+//========================================================================

+// _glfwPlatformSignalCond() - Signal a condition to one waiting thread

+//========================================================================

+

+void _glfwPlatformSignalCond( GLFWcond cond )

+{

+    _GLFWcond *cv = (_GLFWcond *) cond;

+    int       have_waiters;

+

+    // Avoid race conditions

+    EnterCriticalSection( &cv->waiters_count_lock );

+    have_waiters = cv->waiters_count > 0;

+    LeaveCriticalSection( &cv->waiters_count_lock );

+

+    if( have_waiters )

+    {

+        SetEvent( cv->events[ _GLFW_COND_SIGNAL ] );

+    }

+}

+

+

+//========================================================================

+// _glfwPlatformBroadcastCond() - Broadcast a condition to all waiting

+// threads

+//========================================================================

+

+void _glfwPlatformBroadcastCond( GLFWcond cond )

+{

+    _GLFWcond *cv = (_GLFWcond *) cond;

+    int       have_waiters;

+

+    // Avoid race conditions

+    EnterCriticalSection( &cv->waiters_count_lock );

+    have_waiters = cv->waiters_count > 0;

+    LeaveCriticalSection( &cv->waiters_count_lock );

+

+    if( have_waiters )

+    {

+        SetEvent( cv->events[ _GLFW_COND_BROADCAST ] );

+    }

+}

+

+

+//========================================================================

+// _glfwPlatformGetNumberOfProcessors() - Return the number of processors

+// in the system.

+//========================================================================

+

+int _glfwPlatformGetNumberOfProcessors( void )

+{

+    SYSTEM_INFO si;

+

+    // Get hardware system information

+    GetSystemInfo( &si );

+

+    return (int) si.dwNumberOfProcessors;

+}

diff --git a/src/engine/external/glfw/lib/win32/win32_time.c b/src/engine/external/glfw/lib/win32/win32_time.c
new file mode 100644
index 00000000..ea35a8e5
--- /dev/null
+++ b/src/engine/external/glfw/lib/win32/win32_time.c
@@ -0,0 +1,146 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        win32_time.c

+// Platform:    Windows

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

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

+//****                  GLFW internal functions                       ****

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

+

+//========================================================================

+// _glfwInitTimer() - Initialise timer

+//========================================================================

+

+void _glfwInitTimer( void )

+{

+    __int64 freq;

+

+    // Check if we have a performance counter

+    if( QueryPerformanceFrequency( (LARGE_INTEGER *)&freq ) )

+    {

+        // Performance counter is available => use it!

+        _glfwLibrary.Timer.HasPerformanceCounter = GL_TRUE;

+

+        // Counter resolution is 1 / counter frequency

+        _glfwLibrary.Timer.Resolution = 1.0 / (double)freq;

+

+        // Set start time for timer

+        QueryPerformanceCounter( (LARGE_INTEGER *)&_glfwLibrary.Timer.t0_64 );

+    }

+    else

+    {

+        // No performace counter available => use the tick counter

+        _glfwLibrary.Timer.HasPerformanceCounter = GL_FALSE;

+

+        // Counter resolution is 1 ms

+        _glfwLibrary.Timer.Resolution = 0.001;

+

+        // Set start time for timer

+        _glfwLibrary.Timer.t0_32 = _glfw_timeGetTime();

+    }

+}

+

+

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

+//****               Platform implementation functions                ****

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

+

+//========================================================================

+// Return timer value in seconds

+//========================================================================

+

+double _glfwPlatformGetTime( void )

+{

+    double  t;

+    __int64 t_64;

+

+    if( _glfwLibrary.Timer.HasPerformanceCounter )

+    {

+        QueryPerformanceCounter( (LARGE_INTEGER *)&t_64 );

+        t =  (double)(t_64 - _glfwLibrary.Timer.t0_64);

+    }

+    else

+    {

+        t = (double)(_glfw_timeGetTime() - _glfwLibrary.Timer.t0_32);

+    }

+

+    // Calculate the current time in seconds

+    return t * _glfwLibrary.Timer.Resolution;

+}

+

+

+//========================================================================

+// Set timer value in seconds

+//========================================================================

+

+void _glfwPlatformSetTime( double t )

+{

+    __int64 t_64;

+

+    if( _glfwLibrary.Timer.HasPerformanceCounter )

+    {

+        QueryPerformanceCounter( (LARGE_INTEGER *)&t_64 );

+        _glfwLibrary.Timer.t0_64 = t_64 - (__int64)(t/_glfwLibrary.Timer.Resolution);

+    }

+    else

+    {

+        _glfwLibrary.Timer.t0_32 = _glfw_timeGetTime() - (int)(t*1000.0);

+    }

+}

+

+

+//========================================================================

+// Put a thread to sleep for a specified amount of time

+//========================================================================

+

+void _glfwPlatformSleep( double time )

+{

+    DWORD t;

+

+    if( time == 0.0 )

+    {

+	t = 0;

+    }

+    else if( time < 0.001 )

+    {

+        t = 1;

+    }

+    else if( time > 2147483647.0 )

+    {

+        t = 2147483647;

+    }

+    else

+    {

+        t = (DWORD)(time*1000.0 + 0.5);

+    }

+    Sleep( t );

+}

+

diff --git a/src/engine/external/glfw/lib/win32/win32_window.c b/src/engine/external/glfw/lib/win32/win32_window.c
new file mode 100644
index 00000000..83c0eeae
--- /dev/null
+++ b/src/engine/external/glfw/lib/win32/win32_window.c
@@ -0,0 +1,1697 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        win32_window.c

+// Platform:    Windows

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

+

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

+//****                  GLFW internal functions                       ****

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

+

+#define _GLFW_WNDCLASSNAME "GLFW26"

+

+

+//========================================================================

+// Enable/disable minimize/restore animations

+//========================================================================

+

+static int _glfwMinMaxAnimations( int enable )

+{

+    ANIMATIONINFO AI;

+    int old_enable;

+

+    // Get old animation setting

+    AI.cbSize = sizeof( ANIMATIONINFO );

+    SystemParametersInfo( SPI_GETANIMATION, AI.cbSize, &AI, 0 );

+    old_enable = AI.iMinAnimate;

+

+    // If requested, change setting

+    if( old_enable != enable )

+    {

+        AI.iMinAnimate = enable;

+        SystemParametersInfo( SPI_SETANIMATION, AI.cbSize, &AI,

+                              SPIF_SENDCHANGE );

+    }

+

+    return old_enable;

+}

+

+

+//========================================================================

+// Function for bringing a window into focus and placing it on top of the

+// window z stack. Due to some nastiness with how Win98/ME/2k/XP handles

+// SetForegroundWindow, we have to go through some really bizarre measures to

+// achieve this (thanks again, MS, for making life so much easier)!

+//========================================================================

+

+static void _glfwSetForegroundWindow( HWND hWnd )

+{

+    int try_count = 0;

+    int old_animate;

+

+    // Try the standard approach first...

+    BringWindowToTop( hWnd );

+    SetForegroundWindow( hWnd );

+

+    // If it worked, return now

+    if( hWnd == GetForegroundWindow() )

+    {

+        // Try to modify the system settings (since this is the foreground

+        // process, we are allowed to do this)

+        SystemParametersInfo( SPI_SETFOREGROUNDLOCKTIMEOUT, 0, (LPVOID)0,

+                              SPIF_SENDCHANGE );

+        return;

+    }

+

+    // For other Windows versions than 95 & NT4.0, the standard approach

+    // may not work, so if we failed we have to "trick" Windows into

+    // making our window the foureground window: Iconify and restore

+    // again. It is ugly, but it seems to work (we turn off those annoying

+    // zoom animations to make it look a bit better at least).

+

+    // Turn off minimize/restore animations

+    old_animate = _glfwMinMaxAnimations( 0 );

+

+    // We try this a few times, just to be on the safe side of things...

+    do

+    {

+        // Iconify & restore

+        ShowWindow( hWnd, SW_HIDE );

+        ShowWindow( hWnd, SW_SHOWMINIMIZED );

+        ShowWindow( hWnd, SW_SHOWNORMAL );

+

+        // Try to get focus

+        BringWindowToTop( hWnd );

+        SetForegroundWindow( hWnd );

+

+        // We do not want to keep going on forever, so we keep track of

+        // how many times we tried

+        try_count ++;

+    }

+    while( hWnd != GetForegroundWindow() && try_count <= 3 );

+

+    // Restore the system minimize/restore animation setting

+    (void) _glfwMinMaxAnimations( old_animate );

+

+    // Try to modify the system settings (since this is now hopefully the

+    // foreground process, we are probably allowed to do this)

+    SystemParametersInfo( SPI_SETFOREGROUNDLOCKTIMEOUT, 0, (LPVOID)0,

+                          SPIF_SENDCHANGE );

+}

+

+

+//========================================================================

+// Sets the device context pixel format using a PFD

+//========================================================================

+

+static int _glfwSetPixelFormatPFD( int redbits, int greenbits, int bluebits,

+                                   int alphabits, int depthbits, int stencilbits,

+                                   int mode, _GLFWhints* hints )

+{

+    int PixelFormat;

+    PIXELFORMATDESCRIPTOR pfd;

+

+    // Set required pixel format

+    pfd.nSize           = sizeof(PIXELFORMATDESCRIPTOR);

+    pfd.nVersion        = 1;

+    pfd.dwFlags         = PFD_DRAW_TO_WINDOW | // Draw to window

+                          PFD_SUPPORT_OPENGL | // Support OpenGL

+                          PFD_DOUBLEBUFFER;    // Double buffered window

+    pfd.iPixelType      = PFD_TYPE_RGBA;       // Request an RGBA format

+    pfd.cColorBits      = (BYTE) (redbits +

+                                  greenbits +

+                                  bluebits);   // Color bits (ex. alpha)

+    pfd.cRedBits        = (BYTE) redbits;      // Red bits

+    pfd.cRedShift       = 0;                   // Red shift ignored

+    pfd.cGreenBits      = (BYTE) greenbits;    // Green bits

+    pfd.cGreenShift     = 0;                   // Green shift ignored

+    pfd.cBlueBits       = (BYTE) bluebits;     // Blue bits

+    pfd.cBlueShift      = 0;                   // Blue shift ignored

+    pfd.cAlphaBits      = (BYTE) alphabits;    // Alpha bits

+    pfd.cAlphaShift     = 0;                   // Alpha shift ignored

+    pfd.cAccumBits      = (BYTE) (hints->AccumRedBits +

+                                  hints->AccumGreenBits +

+                                  hints->AccumBlueBits +

+                                  hints->AccumAlphaBits); // Accum. bits

+    pfd.cAccumRedBits   = (BYTE) hints->AccumRedBits;   // Accum. red bits

+    pfd.cAccumGreenBits = (BYTE) hints->AccumGreenBits; // Accum. green bits

+    pfd.cAccumBlueBits  = (BYTE) hints->AccumBlueBits;  // Accum. blue bits

+    pfd.cAccumAlphaBits = (BYTE) hints->AccumAlphaBits; // Accum. alpha bits

+    pfd.cDepthBits      = (BYTE) depthbits;    // Depth buffer bits

+    pfd.cStencilBits    = (BYTE) stencilbits;  // Stencil buffer bits

+    pfd.cAuxBuffers     = (BYTE) hints->AuxBuffers;   // No. of aux buffers

+    pfd.iLayerType      = PFD_MAIN_PLANE;      // Drawing layer: main

+    pfd.bReserved       = 0;                   // (reserved)

+    pfd.dwLayerMask     = 0;                   // Ignored

+    pfd.dwVisibleMask   = 0;                   // "

+    pfd.dwDamageMask    = 0;                   // "

+

+    if( depthbits <= 0 )

+    {

+        // We do not need a depth buffer

+        pfd.dwFlags |= PFD_DEPTH_DONTCARE;

+    }

+

+    if( hints->Stereo )

+    {

+        // Request a stereo mode

+        pfd.dwFlags |= PFD_STEREO;

+    }

+

+    // Find a matching pixel format

+    PixelFormat = _glfw_ChoosePixelFormat( _glfwWin.DC, &pfd );

+    if( !PixelFormat )

+    {

+        return GL_FALSE;

+    }

+

+    // Get actual pixel format description

+    if( !_glfw_DescribePixelFormat( _glfwWin.DC, PixelFormat, sizeof(pfd), &pfd ) )

+    {

+        return GL_FALSE;

+    }

+

+    // "stereo" is a strict requirement

+    if( hints->Stereo && !(pfd.dwFlags & PFD_STEREO) )

+    {

+        return GL_FALSE;

+    }

+

+    // Set the pixel-format

+    if( !_glfw_SetPixelFormat( _glfwWin.DC, PixelFormat, &pfd ) )

+    {

+        return GL_FALSE;

+    }

+

+    return GL_TRUE;

+}

+

+

+//========================================================================

+// Sets the device context pixel format using attributes

+//========================================================================

+

+#define _glfwSetWGLAttribute( _glfwName, _glfwValue ) \

+    attribs[ count++ ] = _glfwName; \

+    attribs[ count++ ] = _glfwValue;

+

+static int _glfwSetPixelFormatAttrib( int redbits, int greenbits, int bluebits,

+                                      int alphabits, int depthbits, int stencilbits,

+                                      int mode, _GLFWhints* hints )

+{

+    int PixelFormat, dummy, count = 0;

+    int attribs[128];

+    PIXELFORMATDESCRIPTOR pfd;

+

+    int accumredbits = hints->AccumRedBits;

+    int accumgreenbits = hints->AccumGreenBits;

+    int accumbluebits = hints->AccumBlueBits;

+    int accumalphabits = hints->AccumAlphaBits;

+    

+    _glfwSetWGLAttribute( WGL_DRAW_TO_WINDOW_ARB, GL_TRUE );

+    _glfwSetWGLAttribute( WGL_ACCELERATION_ARB,   WGL_FULL_ACCELERATION_ARB );

+    _glfwSetWGLAttribute( WGL_SUPPORT_OPENGL_ARB, GL_TRUE );

+    _glfwSetWGLAttribute( WGL_DOUBLE_BUFFER_ARB,  GL_TRUE );

+    _glfwSetWGLAttribute( WGL_COLOR_BITS_ARB,     redbits + greenbits + bluebits );

+    _glfwSetWGLAttribute( WGL_RED_BITS_ARB,       redbits );

+    _glfwSetWGLAttribute( WGL_GREEN_BITS_ARB,     greenbits );

+    _glfwSetWGLAttribute( WGL_BLUE_BITS_ARB,      bluebits );

+    _glfwSetWGLAttribute( WGL_ALPHA_BITS_ARB,     alphabits );

+    _glfwSetWGLAttribute( WGL_DEPTH_BITS_ARB,     depthbits );

+    _glfwSetWGLAttribute( WGL_STENCIL_BITS_ARB,   stencilbits );

+    _glfwSetWGLAttribute( WGL_AUX_BUFFERS_ARB,    hints->AuxBuffers );

+

+    if( accumredbits || accumgreenbits || accumbluebits || accumalphabits )

+    {

+        _glfwSetWGLAttribute( WGL_ACCUM_BITS_ARB, accumredbits +

+                                                  accumgreenbits +

+                                                  accumbluebits +

+                                                  accumalphabits );

+

+        _glfwSetWGLAttribute( WGL_ACCUM_RED_BITS_ARB, accumredbits );

+        _glfwSetWGLAttribute( WGL_ACCUM_GREEN_BITS_ARB, accumgreenbits );

+        _glfwSetWGLAttribute( WGL_ACCUM_BLUE_BITS_ARB, accumbluebits );

+        _glfwSetWGLAttribute( WGL_ACCUM_ALPHA_BITS_ARB, accumalphabits );

+    }

+

+    if( hints->Stereo )

+    {

+        _glfwSetWGLAttribute( WGL_STEREO_ARB, GL_TRUE );

+    }

+

+    if( hints->Samples > 0 )

+    {

+        _glfwSetWGLAttribute( WGL_SAMPLE_BUFFERS_ARB, 1 );

+        _glfwSetWGLAttribute( WGL_SAMPLES_ARB, hints->Samples );

+    }

+

+    _glfwSetWGLAttribute( 0, 0 );

+

+    if( !_glfwWin.ChoosePixelFormat( _glfwWin.DC, attribs, NULL, 1, &PixelFormat, &dummy ) )

+    {

+        return GL_FALSE;

+    }

+

+    if( !_glfw_DescribePixelFormat( _glfwWin.DC, PixelFormat, sizeof(pfd), &pfd ) )

+    {

+        return GL_FALSE;

+    }

+

+    // Set the pixel-format

+    if( !_glfw_SetPixelFormat( _glfwWin.DC, PixelFormat, &pfd ) )

+    {

+        return GL_FALSE;

+    }

+

+    return GL_TRUE; 

+}

+

+#undef _glfwSetWGLAttribute

+

+

+//========================================================================

+// Translates a Windows key to the corresponding GLFW key

+//========================================================================

+

+static int _glfwTranslateKey( WPARAM wParam, LPARAM lParam )

+{

+    MSG next_msg;

+    DWORD msg_time;

+    DWORD scan_code;

+

+    // Check which key was pressed or released

+    switch( wParam )

+    {

+        // The SHIFT keys require special handling

+        case VK_SHIFT:

+            // Compare scan code for this key with that of VK_RSHIFT in

+            // order to determine which shift key was pressed (left or

+            // right)

+            scan_code = MapVirtualKey( VK_RSHIFT, 0 );

+            if( ((lParam & 0x01ff0000) >> 16) == scan_code )

+            {

+                return GLFW_KEY_RSHIFT;

+            }

+            return GLFW_KEY_LSHIFT;

+

+        // The CTRL keys require special handling

+        case VK_CONTROL:

+            // Is this an extended key (i.e. right key)?

+            if( lParam & 0x01000000 )

+            {

+                return GLFW_KEY_RCTRL;

+            }

+            // Here is a trick: "Alt Gr" sends LCTRL, then RALT. We only

+            // want the RALT message, so we try to see if the next message

+            // is a RALT message. In that case, this is a false LCTRL!

+            msg_time = GetMessageTime();

+            if( PeekMessage( &next_msg, NULL, 0, 0, PM_NOREMOVE ) )

+            {

+                if( next_msg.message == WM_KEYDOWN ||

+                    next_msg.message == WM_SYSKEYDOWN )

+                {

+                    if( next_msg.wParam == VK_MENU &&

+                        (next_msg.lParam & 0x01000000) &&

+                        next_msg.time == msg_time )

+                    {

+                        // Next message is a RALT down message, which

+                        // means that this is NOT a proper LCTRL message!

+                        return GLFW_KEY_UNKNOWN;

+                    }

+                }

+            }

+            return GLFW_KEY_LCTRL;

+

+        // The ALT keys require special handling

+        case VK_MENU:

+            // Is this an extended key (i.e. right key)?

+            if( lParam & 0x01000000 )

+            {

+                return GLFW_KEY_RALT;

+            }

+            return GLFW_KEY_LALT;

+

+        // The ENTER keys require special handling

+        case VK_RETURN:

+            // Is this an extended key (i.e. right key)?

+            if( lParam & 0x01000000 )

+            {

+                return GLFW_KEY_KP_ENTER;

+            }

+            return GLFW_KEY_ENTER;

+

+        // Special keys (non character keys)

+        case VK_ESCAPE:        return GLFW_KEY_ESC;

+        case VK_TAB:           return GLFW_KEY_TAB;

+        case VK_BACK:          return GLFW_KEY_BACKSPACE;

+        case VK_HOME:          return GLFW_KEY_HOME;

+        case VK_END:           return GLFW_KEY_END;

+        case VK_PRIOR:         return GLFW_KEY_PAGEUP;

+        case VK_NEXT:          return GLFW_KEY_PAGEDOWN;

+        case VK_INSERT:        return GLFW_KEY_INSERT;

+        case VK_DELETE:        return GLFW_KEY_DEL;

+        case VK_LEFT:          return GLFW_KEY_LEFT;

+        case VK_UP:            return GLFW_KEY_UP;

+        case VK_RIGHT:         return GLFW_KEY_RIGHT;

+        case VK_DOWN:          return GLFW_KEY_DOWN;

+        case VK_F1:            return GLFW_KEY_F1;

+        case VK_F2:            return GLFW_KEY_F2;

+        case VK_F3:            return GLFW_KEY_F3;

+        case VK_F4:            return GLFW_KEY_F4;

+        case VK_F5:            return GLFW_KEY_F5;

+        case VK_F6:            return GLFW_KEY_F6;

+        case VK_F7:            return GLFW_KEY_F7;

+        case VK_F8:            return GLFW_KEY_F8;

+        case VK_F9:            return GLFW_KEY_F9;

+        case VK_F10:           return GLFW_KEY_F10;

+        case VK_F11:           return GLFW_KEY_F11;

+        case VK_F12:           return GLFW_KEY_F12;

+        case VK_F13:           return GLFW_KEY_F13;

+        case VK_F14:           return GLFW_KEY_F14;

+        case VK_F15:           return GLFW_KEY_F15;

+        case VK_F16:           return GLFW_KEY_F16;

+        case VK_F17:           return GLFW_KEY_F17;

+        case VK_F18:           return GLFW_KEY_F18;

+        case VK_F19:           return GLFW_KEY_F19;

+        case VK_F20:           return GLFW_KEY_F20;

+        case VK_F21:           return GLFW_KEY_F21;

+        case VK_F22:           return GLFW_KEY_F22;

+        case VK_F23:           return GLFW_KEY_F23;

+        case VK_F24:           return GLFW_KEY_F24;

+        case VK_SPACE:         return GLFW_KEY_SPACE;

+

+        // Numeric keypad

+        case VK_NUMPAD0:       return GLFW_KEY_KP_0;

+        case VK_NUMPAD1:       return GLFW_KEY_KP_1;

+        case VK_NUMPAD2:       return GLFW_KEY_KP_2;

+        case VK_NUMPAD3:       return GLFW_KEY_KP_3;

+        case VK_NUMPAD4:       return GLFW_KEY_KP_4;

+        case VK_NUMPAD5:       return GLFW_KEY_KP_5;

+        case VK_NUMPAD6:       return GLFW_KEY_KP_6;

+        case VK_NUMPAD7:       return GLFW_KEY_KP_7;

+        case VK_NUMPAD8:       return GLFW_KEY_KP_8;

+        case VK_NUMPAD9:       return GLFW_KEY_KP_9;

+        case VK_DIVIDE:        return GLFW_KEY_KP_DIVIDE;

+        case VK_MULTIPLY:      return GLFW_KEY_KP_MULTIPLY;

+        case VK_SUBTRACT:      return GLFW_KEY_KP_SUBTRACT;

+        case VK_ADD:           return GLFW_KEY_KP_ADD;

+        case VK_DECIMAL:       return GLFW_KEY_KP_DECIMAL;

+

+        // The rest (should be printable keys)

+        default:

+            // Convert to printable character (ISO-8859-1 or Unicode)

+            wParam = MapVirtualKey( (UINT) wParam, 2 ) & 0x0000FFFF;

+

+            // Make sure that the character is uppercase

+            if( _glfwLibrary.Sys.HasUnicode )

+            {

+                wParam = (WPARAM) CharUpperW( (LPWSTR) wParam );

+            }

+            else

+            {

+                wParam = (WPARAM) CharUpperA( (LPSTR) wParam );

+            }

+

+            // Valid ISO-8859-1 character?

+            if( (wParam >=  32 && wParam <= 126) ||

+                (wParam >= 160 && wParam <= 255) )

+            {

+                return (int) wParam;

+            }

+            return GLFW_KEY_UNKNOWN;

+    }

+}

+

+

+//========================================================================

+// Translates a windows key to Unicode

+//========================================================================

+

+static void _glfwTranslateChar( DWORD wParam, DWORD lParam, int action )

+{

+    BYTE  keyboard_state[ 256 ];

+    UCHAR char_buf[ 10 ];

+    WCHAR unicode_buf[ 10 ];

+    UINT  scan_code;

+    int   i, num_chars, unicode;

+

+    // Get keyboard state

+    GetKeyboardState( keyboard_state );

+

+    // Derive scan code from lParam and action

+    scan_code = (lParam & 0x01ff0000) >> 16;

+    if( action == GLFW_RELEASE )

+    {

+        scan_code |= 0x8000000;

+    }

+

+    // Do we have Unicode support?

+    if( _glfwLibrary.Sys.HasUnicode )

+    {

+        // Convert to Unicode

+        num_chars = ToUnicode(

+            wParam,          // virtual-key code

+            scan_code,       // scan code

+            keyboard_state,  // key-state array

+            unicode_buf,     // buffer for translated key

+            10,              // size of translated key buffer

+            0                // active-menu flag

+        );

+        unicode = 1;

+    }

+    else

+    {

+        // Convert to ISO-8859-1

+        num_chars = ToAscii(

+            wParam,            // virtual-key code

+            scan_code,         // scan code

+            keyboard_state,    // key-state array

+            (LPWORD) char_buf, // buffer for translated key

+            0                  // active-menu flag

+        );

+        unicode = 0;

+    }

+

+    // Report characters

+    for( i = 0;  i < num_chars;  i++ )

+    {

+        // Get next character from buffer

+        if( unicode )

+        {

+            _glfwInputChar( (int) unicode_buf[ i ], action );

+        }

+        else

+        {

+            _glfwInputChar( (int) char_buf[ i ], action );

+        }

+    }

+}

+

+

+//========================================================================

+// Window callback function (handles window events)

+//========================================================================

+

+static LRESULT CALLBACK _glfwWindowCallback( HWND hWnd, UINT uMsg,

+                                             WPARAM wParam, LPARAM lParam )

+{

+    int WheelDelta, Iconified;

+

+    // Handle certain window messages

+    switch( uMsg )

+    {

+        // Window activate message? (iconification?)

+        case WM_ACTIVATE:

+        {

+            _glfwWin.Active = LOWORD(wParam) != WA_INACTIVE ? GL_TRUE : GL_FALSE;

+

+            Iconified = HIWORD(wParam) ? GL_TRUE : GL_FALSE;

+

+            // Were we deactivated/iconified?

+            if( (!_glfwWin.Active || Iconified) && !_glfwWin.Iconified )

+            {

+                _glfwInputDeactivation();

+

+                // If we are in fullscreen mode we need to iconify

+                if( _glfwWin.Opened && _glfwWin.Fullscreen )

+                {

+                    // Do we need to manually iconify?

+                    if( !Iconified )

+                    {

+                        // Minimize window

+                        CloseWindow( _glfwWin.Wnd );

+

+                        // The window is now iconified

+                        Iconified = GL_TRUE;

+                    }

+

+                    // Change display settings to the desktop resolution

+                    ChangeDisplaySettings( NULL, CDS_FULLSCREEN );

+                }

+

+                // Unlock mouse

+                if( !_glfwWin.OldMouseLockValid )

+                {

+                    _glfwWin.OldMouseLock = _glfwWin.MouseLock;

+                    _glfwWin.OldMouseLockValid = GL_TRUE;

+                    glfwEnable( GLFW_MOUSE_CURSOR );

+                }

+            }

+            else if( _glfwWin.Active || !Iconified )

+            {

+                // If we are in fullscreen mode we need to maximize

+                if( _glfwWin.Opened && _glfwWin.Fullscreen && _glfwWin.Iconified )

+                {

+                    // Change display settings to the user selected mode

+                    _glfwSetVideoModeMODE( _glfwWin.ModeID );

+

+                    // Do we need to manually restore window?

+                    if( Iconified )

+                    {

+                        // Restore window

+                        OpenIcon( _glfwWin.Wnd );

+

+                        // The window is no longer iconified

+                        Iconified = GL_FALSE;

+

+                        // Activate window

+                        ShowWindow( hWnd, SW_SHOW );

+                        _glfwSetForegroundWindow( _glfwWin.Wnd );

+                        SetFocus( _glfwWin.Wnd );

+                    }

+                }

+

+                // Lock mouse, if necessary

+                if( _glfwWin.OldMouseLockValid && _glfwWin.OldMouseLock )

+                {

+                    glfwDisable( GLFW_MOUSE_CURSOR );

+                }

+                _glfwWin.OldMouseLockValid = GL_FALSE;

+            }

+

+            _glfwWin.Iconified = Iconified;

+            return 0;

+        }

+

+        // Intercept system commands (forbid certain actions/events)

+        case WM_SYSCOMMAND:

+        {

+            switch( wParam )

+            {

+                // Screensaver trying to start or monitor trying to enter

+                // powersave?

+                case SC_SCREENSAVE:

+                case SC_MONITORPOWER:

+                    if( _glfwWin.Fullscreen )

+                    {

+                        return 0;

+                    }

+                    else

+                    {

+                        break;

+                    }

+

+                // User trying to access application menu using ALT?

+                case SC_KEYMENU:

+                    return 0;

+            }

+            break;

+        }

+

+        // Did we receive a close message?

+        case WM_CLOSE:

+            PostQuitMessage( 0 );

+            return 0;

+

+        // Is a key being pressed?

+        case WM_KEYDOWN:

+        case WM_SYSKEYDOWN:

+        {

+            // Translate and report key press

+            _glfwInputKey( _glfwTranslateKey( wParam, lParam ),

+                           GLFW_PRESS );

+

+            // Translate and report character input

+            if( _glfwWin.CharCallback )

+            {

+                _glfwTranslateChar( (DWORD) wParam, (DWORD) lParam, GLFW_PRESS );

+            }

+            return 0;

+          }  

+

+        // Is a key being released?

+        case WM_KEYUP:

+        case WM_SYSKEYUP:

+        {

+            // Special trick: release both shift keys on SHIFT up event

+            if( wParam == VK_SHIFT )

+            {

+                _glfwInputKey( GLFW_KEY_LSHIFT, GLFW_RELEASE );

+                _glfwInputKey( GLFW_KEY_RSHIFT, GLFW_RELEASE );

+            }

+            else

+            {

+                // Translate and report key release

+                _glfwInputKey( _glfwTranslateKey( wParam, lParam ),

+                               GLFW_RELEASE );

+            }

+

+            // Translate and report character input

+            if( _glfwWin.CharCallback )

+            {

+                _glfwTranslateChar( (DWORD) wParam, (DWORD) lParam, GLFW_RELEASE );

+            }

+

+            return 0;

+        }

+

+        // Were any of the mouse-buttons pressed?

+        case WM_LBUTTONDOWN:

+            SetCapture(hWnd);

+            _glfwInputMouseClick( GLFW_MOUSE_BUTTON_LEFT, GLFW_PRESS );

+            return 0;

+        case WM_RBUTTONDOWN:

+            SetCapture(hWnd);

+            _glfwInputMouseClick( GLFW_MOUSE_BUTTON_RIGHT, GLFW_PRESS );

+            return 0;

+        case WM_MBUTTONDOWN:

+            SetCapture(hWnd);

+            _glfwInputMouseClick( GLFW_MOUSE_BUTTON_MIDDLE, GLFW_PRESS );

+            return 0;

+        case WM_XBUTTONDOWN:

+        {

+            if( HIWORD(wParam) == XBUTTON1 )

+            {

+                SetCapture(hWnd);

+                _glfwInputMouseClick( GLFW_MOUSE_BUTTON_4, GLFW_PRESS );

+            }

+            else if( HIWORD(wParam) == XBUTTON2 )

+            {

+                SetCapture(hWnd);

+                _glfwInputMouseClick( GLFW_MOUSE_BUTTON_5, GLFW_PRESS );

+            }

+            return 1;

+        }

+

+        // Were any of the mouse-buttons released?

+        case WM_LBUTTONUP:

+            ReleaseCapture();

+            _glfwInputMouseClick( GLFW_MOUSE_BUTTON_LEFT, GLFW_RELEASE );

+            return 0;

+        case WM_RBUTTONUP:

+            ReleaseCapture();

+            _glfwInputMouseClick( GLFW_MOUSE_BUTTON_RIGHT, GLFW_RELEASE );

+            return 0;

+        case WM_MBUTTONUP:

+            ReleaseCapture();

+            _glfwInputMouseClick( GLFW_MOUSE_BUTTON_MIDDLE, GLFW_RELEASE );

+            return 0;

+        case WM_XBUTTONUP:

+        {

+            if( HIWORD(wParam) == XBUTTON1 )

+            {

+                ReleaseCapture();

+                _glfwInputMouseClick( GLFW_MOUSE_BUTTON_4, GLFW_RELEASE );

+            }

+            else if( HIWORD(wParam) == XBUTTON2 )

+            {

+                ReleaseCapture();

+                _glfwInputMouseClick( GLFW_MOUSE_BUTTON_5, GLFW_RELEASE );

+            }

+            return 1;

+        }

+

+        // Did the mouse move?

+        case WM_MOUSEMOVE:

+        {

+            {

+                int NewMouseX, NewMouseY;

+

+                // Get signed (!) mouse position

+                NewMouseX = (int)((short)LOWORD(lParam));

+                NewMouseY = (int)((short)HIWORD(lParam));

+

+                if( NewMouseX != _glfwInput.OldMouseX ||

+                    NewMouseY != _glfwInput.OldMouseY )

+                {

+                    if( _glfwWin.MouseLock )

+                    {

+                        _glfwInput.MousePosX += NewMouseX -

+                                                _glfwInput.OldMouseX;

+                        _glfwInput.MousePosY += NewMouseY -

+                                                _glfwInput.OldMouseY;

+                    }

+                    else

+                    {

+                        _glfwInput.MousePosX = NewMouseX;

+                        _glfwInput.MousePosY = NewMouseY;

+                    }

+                    _glfwInput.OldMouseX = NewMouseX;

+                    _glfwInput.OldMouseY = NewMouseY;

+                    _glfwInput.MouseMoved = GL_TRUE;

+    

+                    // Call user callback function

+                    if( _glfwWin.MousePosCallback )

+                    {

+                        _glfwWin.MousePosCallback( _glfwInput.MousePosX,

+                                                   _glfwInput.MousePosY );

+                    }

+                }

+            }

+            return 0;

+        }

+

+        // Mouse wheel action?

+        case WM_MOUSEWHEEL:

+        {

+            // WM_MOUSEWHEEL is not supported under Windows 95

+            if( _glfwLibrary.Sys.WinVer != _GLFW_WIN_95 )

+            {

+                WheelDelta = (((int)wParam) >> 16) / WHEEL_DELTA;

+                _glfwInput.WheelPos += WheelDelta;

+                if( _glfwWin.MouseWheelCallback )

+                {

+                    _glfwWin.MouseWheelCallback( _glfwInput.WheelPos );

+                }

+                return 0;

+            }

+            break;

+        }

+

+        // Resize the window?

+        case WM_SIZE:

+        {

+            // get the new size

+            _glfwWin.Width  = LOWORD(lParam);

+            _glfwWin.Height = HIWORD(lParam);

+

+            // If the mouse is locked, update the clipping rect

+            if( _glfwWin.MouseLock )

+            {

+                RECT ClipWindowRect;

+                if( GetWindowRect( _glfwWin.Wnd, &ClipWindowRect ) )

+                {

+                    ClipCursor( &ClipWindowRect );

+                }

+            }

+

+            // Call the user-supplied callback, if it exists

+            if( _glfwWin.WindowSizeCallback )

+            {

+                _glfwWin.WindowSizeCallback( LOWORD(lParam),

+                                             HIWORD(lParam) );

+            }

+            return 0;

+        }

+

+        // Move the window?

+        case WM_MOVE:

+        {

+            // If the mouse is locked, update the clipping rect

+            if( _glfwWin.MouseLock )

+            {

+                RECT ClipWindowRect;

+                if( GetWindowRect( _glfwWin.Wnd, &ClipWindowRect ) )

+                {

+                    ClipCursor( &ClipWindowRect );

+                }

+            }

+            return 0;

+        }

+

+        // Was the window contents damaged?

+        case WM_PAINT:

+        {

+            // Call user callback function

+            if( _glfwWin.WindowRefreshCallback )

+            {

+                _glfwWin.WindowRefreshCallback();

+            }

+            break;

+        }

+

+	case WM_DISPLAYCHANGE:

+	{

+	    // TODO: Do stuff here.

+

+	    break;

+	}

+    }

+

+    // Pass all unhandled messages to DefWindowProc

+    return DefWindowProc( hWnd, uMsg, wParam, lParam );

+}

+

+

+//========================================================================

+// Translate client window size to full window size (including window borders)

+//========================================================================

+

+static void _glfwGetFullWindowSize( int w, int h, int *w2, int *h2 )

+{

+    RECT rect;

+

+    // Create a window rectangle

+    rect.left   = (long)0;

+    rect.right  = (long)w-1;

+    rect.top    = (long)0;

+    rect.bottom = (long)h-1;

+

+    // Adjust according to window styles

+    AdjustWindowRectEx( &rect, _glfwWin.dwStyle, FALSE,

+                        _glfwWin.dwExStyle );

+

+    // Calculate width and height of full window

+    *w2 = rect.right-rect.left+1;

+    *h2 = rect.bottom-rect.top+1;

+}

+

+

+//========================================================================

+// Initialize WGL-specific extensions

+//========================================================================

+

+static void _glfwInitWGLExtensions( void )

+{

+    GLubyte *extensions;

+    int     has_swap_control, has_pixel_format;

+

+    // Initialize OpenGL extension: WGL_EXT_swap_control

+    has_swap_control = GL_FALSE;

+    has_pixel_format = GL_FALSE;

+    extensions = (GLubyte *) glGetString( GL_EXTENSIONS );

+

+    if( extensions != NULL )

+    {

+        has_swap_control = _glfwStringInExtensionString(

+                               "WGL_EXT_swap_control",

+                               extensions

+                           );

+        has_pixel_format = _glfwStringInExtensionString(

+                               "WGL_ARB_pixel_format",

+                               extensions

+                           );

+    }

+

+    if( !has_swap_control )

+    {

+        has_swap_control = _glfwPlatformExtensionSupported(

+                               "WGL_EXT_swap_control"

+                           );

+    }

+

+    if( !has_pixel_format )

+    {

+        has_pixel_format = _glfwPlatformExtensionSupported(

+                               "WGL_ARB_pixel_format"

+                           );

+    }

+

+    if( has_swap_control )

+    {

+        _glfwWin.SwapInterval = (WGLSWAPINTERVALEXT_T)

+            wglGetProcAddress( "wglSwapIntervalEXT" );

+    }

+    else

+    {

+        _glfwWin.SwapInterval = NULL;

+    }

+    

+    if( has_pixel_format )

+    {

+        _glfwWin.ChoosePixelFormat = (WGLCHOOSEPIXELFORMATARB_T)

+            wglGetProcAddress( "wglChoosePixelFormatARB" );

+        _glfwWin.GetPixelFormatAttribiv = (WGLGETPIXELFORMATATTRIBIVARB_T)

+            wglGetProcAddress( "wglGetPixelFormatAttribivARB" );

+    }

+    else

+    {

+        _glfwWin.ChoosePixelFormat = NULL;

+        _glfwWin.GetPixelFormatAttribiv = NULL;

+    }  

+}

+

+

+//========================================================================

+// Creates the GLFW window and rendering context

+//========================================================================

+

+static int _glfwCreateWindow( int redbits, int greenbits, int bluebits,

+                              int alphabits, int depthbits, int stencilbits,

+                              int mode, _GLFWhints* hints )

+{

+    int    full_width, full_height;

+    RECT   wa;

+

+    _glfwWin.DC  = NULL;

+    _glfwWin.RC  = NULL;

+    _glfwWin.Wnd = NULL;

+

+    // Set window size to true requested size (adjust for window borders)

+    _glfwGetFullWindowSize( _glfwWin.Width, _glfwWin.Height, &full_width,

+                            &full_height );

+

+    // Adjust window position to working area (e.g. if the task bar is at

+    // the top of the display). Fullscreen windows are always opened in

+    // the upper left corner regardless of the desktop working area. 

+    if( _glfwWin.Fullscreen )

+    {

+        wa.left = wa.top = 0;

+    }

+    else

+    {

+        SystemParametersInfo( SPI_GETWORKAREA, 0, &wa, 0 );

+    }

+

+    // Create window

+    _glfwWin.Wnd = CreateWindowEx(

+               _glfwWin.dwExStyle,        // Extended style

+               _GLFW_WNDCLASSNAME,        // Class name

+               "GLFW Window",             // Window title

+               _glfwWin.dwStyle,          // Defined window style

+               wa.left, wa.top,           // Window position

+               full_width,                // Decorated window width

+               full_height,               // Decorated window height

+               NULL,                      // No parent window

+               NULL,                      // No menu

+               _glfwLibrary.Instance,     // Instance

+               NULL );                    // Nothing to WM_CREATE

+

+    if( !_glfwWin.Wnd )

+    {

+        return GL_FALSE;

+    }

+

+    // Get a device context

+    _glfwWin.DC = GetDC( _glfwWin.Wnd );

+    if( !_glfwWin.DC )

+    {

+        return GL_FALSE;

+    }

+

+    if( _glfwWin.ChoosePixelFormat )

+    {

+        if( !_glfwSetPixelFormatAttrib( redbits, greenbits, bluebits, alphabits,

+                                        depthbits, stencilbits, mode, hints ) )

+        {

+            return GL_FALSE;

+        }

+    }

+    else

+    {

+        if( !_glfwSetPixelFormatPFD( redbits, greenbits, bluebits, alphabits,

+                                     depthbits, stencilbits, mode, hints ) )

+        {

+            return GL_FALSE;

+        }

+    }

+

+    // Get a rendering context

+    _glfwWin.RC = wglCreateContext( _glfwWin.DC );

+    if( !_glfwWin.RC )

+    {

+        return GL_FALSE;

+    }

+

+    // Activate the OpenGL rendering context

+    if( !wglMakeCurrent( _glfwWin.DC, _glfwWin.RC ) )

+    {

+        return GL_FALSE;

+    }

+

+    // Initialize WGL-specific OpenGL extensions

+    _glfwInitWGLExtensions();

+

+    return GL_TRUE;

+}

+

+

+//========================================================================

+// Destroys the GLFW window and rendering context

+//========================================================================

+

+static void _glfwDestroyWindow( void )

+{

+    // Do we have a rendering context?

+    if( _glfwWin.RC )

+    {

+        // Release the DC and RC contexts

+        wglMakeCurrent( NULL, NULL );

+

+        // Delete the rendering context

+        wglDeleteContext( _glfwWin.RC );

+        _glfwWin.RC = NULL;

+    }

+

+    // Do we have a device context?

+    if( _glfwWin.DC )

+    {

+        // Release the device context

+        ReleaseDC( _glfwWin.Wnd, _glfwWin.DC );

+        _glfwWin.DC = NULL;

+    }

+

+    // Do we have a window?

+    if( _glfwWin.Wnd )

+    {

+        // Destroy the window

+        if( _glfwLibrary.Sys.WinVer <= _GLFW_WIN_NT4 )

+        {

+            // Note: Hiding the window first fixes an annoying W98/NT4

+            // remaining icon bug for fullscreen displays

+            ShowWindow( _glfwWin.Wnd, SW_HIDE );

+        }

+

+        DestroyWindow( _glfwWin.Wnd );

+        _glfwWin.Wnd = NULL;

+    }

+}

+

+

+

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

+//****               Platform implementation functions                ****

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

+

+//========================================================================

+// Here is where the window is created, and the OpenGL rendering context is

+// created

+//========================================================================

+

+int _glfwPlatformOpenWindow( int width, int height,

+                             int redbits, int greenbits, int bluebits,

+                             int alphabits, int depthbits, int stencilbits,

+                             int mode, _GLFWhints* hints )

+{

+    WNDCLASS    wc;

+    DWORD  dwStyle, dwExStyle;

+

+    // Clear platform specific GLFW window state

+    _glfwWin.ClassAtom         = 0;

+    _glfwWin.OldMouseLockValid = GL_FALSE;

+    _glfwWin.ChoosePixelFormat = NULL;

+    _glfwWin.GetPixelFormatAttribiv = NULL;

+

+    // Remember desired refresh rate for this window (used only in

+    // fullscreen mode)

+    _glfwWin.DesiredRefreshRate = hints->RefreshRate;

+

+    // Set window class parameters

+    wc.style         = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw on...

+    wc.lpfnWndProc   = (WNDPROC)_glfwWindowCallback;  // Message handler

+    wc.cbClsExtra    = 0;                             // No extra class data

+    wc.cbWndExtra    = 0;                             // No extra window data

+    wc.hInstance     = _glfwLibrary.Instance;         // Set instance

+    wc.hCursor       = LoadCursor( NULL, IDC_ARROW ); // Load arrow pointer

+    wc.hbrBackground = NULL;                          // No background

+    wc.lpszMenuName  = NULL;                          // No menu

+    wc.lpszClassName = _GLFW_WNDCLASSNAME;            // Set class name

+

+    // Load user-provided icon if available

+    wc.hIcon = LoadIcon( _glfwLibrary.Instance, "GLFW_ICON" );

+    if( !wc.hIcon )

+    {

+        // Load default icon

+        wc.hIcon = LoadIcon( NULL, IDI_WINLOGO ); 

+    }

+

+    // Register the window class

+    _glfwWin.ClassAtom = RegisterClass( &wc );

+    if( !_glfwWin.ClassAtom )

+    {

+        _glfwPlatformCloseWindow();

+        return GL_FALSE;

+    }

+

+    // Do we want full-screen mode?

+    if( _glfwWin.Fullscreen )

+    {

+        _glfwSetVideoMode( &_glfwWin.Width, &_glfwWin.Height,

+                           redbits, greenbits, bluebits,

+                           hints->RefreshRate );

+    }

+

+    // Set common window styles

+    dwStyle   = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VISIBLE;

+    dwExStyle = WS_EX_APPWINDOW;

+

+    // Set window style, depending on fullscreen mode

+    if( _glfwWin.Fullscreen )

+    {

+        dwStyle |= WS_POPUP;

+

+        // Here's a trick for helping us getting window focus

+        // (SetForegroundWindow doesn't work properly under

+        // Win98/ME/2K/XP/.NET/+)

+		

+		/*

+        if( _glfwLibrary.Sys.WinVer == _GLFW_WIN_95 ||

+            _glfwLibrary.Sys.WinVer == _GLFW_WIN_NT4 || 

+            _glfwLibrary.Sys.WinVer == _GLFW_WIN_XP )

+        {

+            dwStyle |= WS_VISIBLE;

+        }

+        else

+        {

+            dwStyle |= WS_MINIMIZE;

+        }

+		*/

+    }

+    else

+    {

+        dwStyle |= WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;

+

+        if( !hints->WindowNoResize )

+        {

+            dwStyle |= ( WS_MAXIMIZEBOX | WS_SIZEBOX );

+            dwExStyle |= WS_EX_WINDOWEDGE;

+        }

+    }

+

+    // Remember window styles (used by _glfwGetFullWindowSize)

+    _glfwWin.dwStyle   = dwStyle;

+    _glfwWin.dwExStyle = dwExStyle;

+

+    if( !_glfwCreateWindow( redbits, greenbits, bluebits, alphabits,

+                            depthbits, stencilbits, mode, hints ) )

+    {

+        _glfwPlatformCloseWindow();

+        return GL_FALSE;

+    }

+

+    if( _glfwWin.ChoosePixelFormat && hints->Samples > 0 )

+    {

+        for (;;)

+        {

+            _glfwDestroyWindow();

+

+            if( _glfwCreateWindow( redbits, greenbits, bluebits, alphabits,

+                                   depthbits, stencilbits, mode, hints ) )

+            {

+                break;

+            }

+

+            if( hints->Samples > 0 )

+            {

+                hints->Samples--;

+            }

+            else

+            {

+                _glfwPlatformCloseWindow();

+                return GL_FALSE;

+            }

+        }

+    }

+

+    // Make sure that our window ends up on top of things

+    if( _glfwWin.Fullscreen )

+    {

+        // Place the window above all topmost windows

+        SetWindowPos( _glfwWin.Wnd, HWND_TOPMOST, 0,0,0,0,

+                      SWP_NOMOVE | SWP_NOSIZE );

+    }

+    _glfwSetForegroundWindow( _glfwWin.Wnd );

+    SetFocus( _glfwWin.Wnd );

+

+    // Start by clearing the front buffer to black (avoid ugly desktop

+    // remains in our OpenGL window)

+    glClear( GL_COLOR_BUFFER_BIT );

+    _glfw_SwapBuffers( _glfwWin.DC );

+

+    return GL_TRUE;

+}

+

+

+//========================================================================

+// Properly kill the window / video display

+//========================================================================

+

+void _glfwPlatformCloseWindow( void )

+{

+    _glfwDestroyWindow();

+

+    // Do we have an instance?

+    if( _glfwWin.ClassAtom )

+    {

+        // Unregister class

+        UnregisterClass( _GLFW_WNDCLASSNAME, _glfwLibrary.Instance );

+        _glfwWin.ClassAtom = 0;

+    }

+

+    // Are we in fullscreen mode?

+    if( _glfwWin.Fullscreen )

+    {

+        // Switch back to desktop resolution

+        ChangeDisplaySettings( NULL, CDS_FULLSCREEN );

+    }

+

+}

+

+

+//========================================================================

+// Set the window title

+//========================================================================

+

+void _glfwPlatformSetWindowTitle( const char *title )

+{

+    // Set window title

+    (void) SetWindowText( _glfwWin.Wnd, title );

+}

+

+

+//========================================================================

+// Set the window size.

+//========================================================================

+

+void _glfwPlatformSetWindowSize( int width, int height )

+{

+    int     bpp, mode = 0, refresh;

+    int     sizechanged = GL_FALSE;

+    GLint   drawbuffer;

+    GLfloat clearcolor[4];

+

+    // If we are in fullscreen mode, get some info about the current mode

+    if( _glfwWin.Fullscreen )

+    {

+        DEVMODE dm;

+

+        // Get current BPP settings

+        dm.dmSize = sizeof( DEVMODE );

+        if( EnumDisplaySettings( NULL, _glfwWin.ModeID, &dm ) )

+        {

+            // Get bpp

+            bpp = dm.dmBitsPerPel;

+

+            // Get closest match for target video mode

+            refresh = _glfwWin.DesiredRefreshRate;

+            mode = _glfwGetClosestVideoModeBPP( &width, &height, &bpp,

+                                                &refresh );

+        }

+        else

+        {

+            mode = _glfwWin.ModeID;

+        }

+    }

+    else

+    {

+        // If we are in windowed mode, adjust the window size to

+        // compensate for window decorations

+        _glfwGetFullWindowSize( width, height, &width, &height );

+    }

+

+    // Change window size before changing fullscreen mode?

+    if( _glfwWin.Fullscreen && (width > _glfwWin.Width) )

+    {

+        SetWindowPos( _glfwWin.Wnd, HWND_TOP, 0, 0, width, height,

+                      SWP_NOOWNERZORDER | SWP_NOMOVE | SWP_NOZORDER );

+        sizechanged = GL_TRUE;

+    }

+

+    // Change fullscreen video mode?

+    if( _glfwWin.Fullscreen && mode != _glfwWin.ModeID )

+    {

+        // Change video mode

+        _glfwSetVideoModeMODE( mode );

+

+        // Clear the front buffer to black (avoid ugly desktop remains in

+        // our OpenGL window)

+        glGetIntegerv( GL_DRAW_BUFFER, &drawbuffer );

+        glGetFloatv( GL_COLOR_CLEAR_VALUE, clearcolor );

+        glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );

+        glClear( GL_COLOR_BUFFER_BIT );

+        if( drawbuffer == GL_BACK )

+        {

+            _glfw_SwapBuffers( _glfwWin.DC );

+        }

+        glClearColor( clearcolor[0], clearcolor[1], clearcolor[2],

+                      clearcolor[3] );

+    }

+

+    // Set window size (if not already changed)

+    if( !sizechanged )

+    {

+        SetWindowPos( _glfwWin.Wnd, HWND_TOP, 0, 0, width, height,

+                      SWP_NOOWNERZORDER | SWP_NOMOVE | SWP_NOZORDER );

+    }

+}

+

+

+//========================================================================

+// Set the window position

+//========================================================================

+

+void _glfwPlatformSetWindowPos( int x, int y )

+{

+    // Set window position

+    (void) SetWindowPos( _glfwWin.Wnd, HWND_TOP, x, y, 0, 0,

+                         SWP_NOOWNERZORDER | SWP_NOSIZE | SWP_NOZORDER );

+}

+

+

+//========================================================================

+// Window iconification

+//========================================================================

+

+void _glfwPlatformIconifyWindow( void )

+{

+    // Iconify window

+    CloseWindow( _glfwWin.Wnd );

+

+    // Window is now iconified

+    _glfwWin.Iconified = GL_TRUE;

+

+    // If we are in fullscreen mode we need to change video modes

+    if( _glfwWin.Fullscreen )

+    {

+        // Change display settings to the desktop resolution

+        ChangeDisplaySettings( NULL, CDS_FULLSCREEN );

+    }

+

+    // Unlock mouse

+    if( !_glfwWin.OldMouseLockValid )

+    {

+        _glfwWin.OldMouseLock = _glfwWin.MouseLock;

+        _glfwWin.OldMouseLockValid = GL_TRUE;

+        glfwEnable( GLFW_MOUSE_CURSOR );

+    }

+}

+

+

+//========================================================================

+// Window un-iconification

+//========================================================================

+

+void _glfwPlatformRestoreWindow( void )

+{

+    // If we are in fullscreen mode we need to change video modes

+    if( _glfwWin.Fullscreen )

+    {

+        // Change display settings to the user selected mode

+        _glfwSetVideoModeMODE( _glfwWin.ModeID );

+    }

+

+    // Un-iconify window

+    OpenIcon( _glfwWin.Wnd );

+

+    // Make sure that our window ends up on top of things

+    ShowWindow( _glfwWin.Wnd, SW_SHOW );

+    _glfwSetForegroundWindow( _glfwWin.Wnd );

+    SetFocus( _glfwWin.Wnd );

+

+    // Window is no longer iconified

+    _glfwWin.Iconified = GL_FALSE;

+

+    // Lock mouse, if necessary

+    if( _glfwWin.OldMouseLockValid && _glfwWin.OldMouseLock )

+    {

+        glfwDisable( GLFW_MOUSE_CURSOR );

+    }

+    _glfwWin.OldMouseLockValid = GL_FALSE;

+}

+

+

+//========================================================================

+// Swap buffers (double-buffering)

+//========================================================================

+

+void _glfwPlatformSwapBuffers( void )

+{

+    _glfw_SwapBuffers( _glfwWin.DC );

+}

+

+

+//========================================================================

+// Set double buffering swap interval

+//========================================================================

+

+void _glfwPlatformSwapInterval( int interval )

+{

+    if( _glfwWin.SwapInterval )

+    {

+        _glfwWin.SwapInterval( interval );

+    }

+}

+

+

+//========================================================================

+// Write back window parameters into GLFW window structure

+//========================================================================

+

+void _glfwPlatformRefreshWindowParams( void )

+{

+    PIXELFORMATDESCRIPTOR pfd;

+    DEVMODE dm;

+    int     PixelFormat, mode;

+

+    // Obtain a detailed description of current pixel format

+    PixelFormat = _glfw_GetPixelFormat( _glfwWin.DC );

+

+    if( !_glfwWin.GetPixelFormatAttribiv )

+    {

+        _glfw_DescribePixelFormat( _glfwWin.DC, PixelFormat,

+                                   sizeof(PIXELFORMATDESCRIPTOR), &pfd );

+

+        // Is current OpenGL context accelerated?

+        _glfwWin.Accelerated = (pfd.dwFlags & PFD_GENERIC_ACCELERATED) ||

+                               !(pfd.dwFlags & PFD_GENERIC_FORMAT) ? 1 : 0;

+

+        // "Standard" window parameters

+        _glfwWin.RedBits        = pfd.cRedBits;

+        _glfwWin.GreenBits      = pfd.cGreenBits;

+        _glfwWin.BlueBits       = pfd.cBlueBits;

+        _glfwWin.AlphaBits      = pfd.cAlphaBits;

+        _glfwWin.DepthBits      = pfd.cDepthBits;

+        _glfwWin.StencilBits    = pfd.cStencilBits;

+        _glfwWin.AccumRedBits   = pfd.cAccumRedBits;

+        _glfwWin.AccumGreenBits = pfd.cAccumGreenBits;

+        _glfwWin.AccumBlueBits  = pfd.cAccumBlueBits;

+        _glfwWin.AccumAlphaBits = pfd.cAccumAlphaBits;

+        _glfwWin.AuxBuffers     = pfd.cAuxBuffers;

+        _glfwWin.Stereo         = pfd.dwFlags & PFD_STEREO ? 1 : 0;

+        _glfwWin.Samples        = 0;

+    }

+    else

+    {

+        const int attribs[] = {

+            WGL_ACCELERATION_ARB,

+            WGL_RED_BITS_ARB,

+            WGL_GREEN_BITS_ARB,

+            WGL_BLUE_BITS_ARB,

+            WGL_ALPHA_BITS_ARB,

+            WGL_DEPTH_BITS_ARB,

+            WGL_STENCIL_BITS_ARB,

+            WGL_ACCUM_RED_BITS_ARB,

+            WGL_ACCUM_GREEN_BITS_ARB,

+            WGL_ACCUM_BLUE_BITS_ARB,

+            WGL_ACCUM_ALPHA_BITS_ARB,

+            WGL_AUX_BUFFERS_ARB,

+            WGL_STEREO_ARB,

+            WGL_SAMPLES_ARB

+        };

+

+        int values[sizeof(attribs) / sizeof(attribs[0])];

+

+        _glfwWin.GetPixelFormatAttribiv( _glfwWin.DC, PixelFormat, 0, 

+                                         sizeof(attribs) / sizeof(attribs[0]), 

+                                         attribs, values);

+

+        // Is current OpenGL context accelerated?

+        _glfwWin.Accelerated = (values[0] == WGL_FULL_ACCELERATION_ARB);

+

+        // "Standard" window parameters

+        _glfwWin.RedBits        = values[1];

+        _glfwWin.GreenBits      = values[2];

+        _glfwWin.BlueBits       = values[3];

+        _glfwWin.AlphaBits      = values[4];

+        _glfwWin.DepthBits      = values[5];

+        _glfwWin.StencilBits    = values[6];

+        _glfwWin.AccumRedBits   = values[7];

+        _glfwWin.AccumGreenBits = values[8]; 

+        _glfwWin.AccumBlueBits  = values[9];

+        _glfwWin.AccumAlphaBits = values[10];

+        _glfwWin.AuxBuffers     = values[11];

+        _glfwWin.Stereo         = values[12];

+        _glfwWin.Samples        = values[13];

+    }

+

+    // Get refresh rate

+    mode = _glfwWin.Fullscreen ? _glfwWin.ModeID : ENUM_CURRENT_SETTINGS;

+    dm.dmSize = sizeof( DEVMODE );

+

+    if( EnumDisplaySettings( NULL, mode, &dm ) )

+    {

+        _glfwWin.RefreshRate = dm.dmDisplayFrequency;

+        if( _glfwWin.RefreshRate <= 1 )

+        {

+            _glfwWin.RefreshRate = 0;

+        }

+    }

+    else

+    {

+        _glfwWin.RefreshRate = 0;

+    }

+}

+

+

+//========================================================================

+// Poll for new window and input events

+//========================================================================

+

+void _glfwPlatformPollEvents( void )

+{

+    MSG msg;

+    int winclosed = GL_FALSE;

+

+    // Flag: mouse was not moved (will be changed by _glfwGetNextEvent if

+    // there was a mouse move event)

+    _glfwInput.MouseMoved = GL_FALSE;

+    if( _glfwWin.MouseLock )

+    {

+        _glfwInput.OldMouseX = _glfwWin.Width/2;

+        _glfwInput.OldMouseY = _glfwWin.Height/2;

+    }

+    else

+    {

+        _glfwInput.OldMouseX = _glfwInput.MousePosX;

+        _glfwInput.OldMouseY = _glfwInput.MousePosY;

+    }

+

+    // Check for new window messages

+    while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )

+    {

+        switch( msg.message )

+        {

+            // QUIT-message (from close window)?

+            case WM_QUIT:

+                winclosed = GL_TRUE;

+                break;

+

+            // Ok, send it to the window message handler

+            default:

+                DispatchMessage( &msg );

+                break;

+        }

+    }

+

+    // LSHIFT/RSHIFT fixup (keys tend to "stick" without this fix)

+    // This is the only async event handling in GLFW, but it solves some

+    // nasty problems.

+    // Caveat: Does not work under Win 9x/ME.

+    if( _glfwLibrary.Sys.WinVer >= _GLFW_WIN_NT4 )

+    {

+        int lshift_down, rshift_down;

+

+        // Get current state of left and right shift keys

+        lshift_down = (GetAsyncKeyState( VK_LSHIFT ) >> 15) & 1;

+        rshift_down = (GetAsyncKeyState( VK_RSHIFT ) >> 15) & 1;

+

+        // See if this differs from our belief of what has happened

+        // (we only have to check for lost key up events)

+        if( !lshift_down && _glfwInput.Key[ GLFW_KEY_LSHIFT ] == 1 )

+        {

+            _glfwInputKey( GLFW_KEY_LSHIFT, GLFW_RELEASE );

+        }

+        if( !rshift_down && _glfwInput.Key[ GLFW_KEY_RSHIFT ] == 1 )

+        {

+            _glfwInputKey( GLFW_KEY_RSHIFT, GLFW_RELEASE );

+        }

+    }

+

+    // Did we have mouse movement in locked cursor mode?

+    if( _glfwInput.MouseMoved && _glfwWin.MouseLock )

+    {

+        _glfwPlatformSetMouseCursorPos( _glfwWin.Width / 2,

+                                        _glfwWin.Height / 2 );

+    }

+

+    // Was there a window close request?

+    if( winclosed && _glfwWin.WindowCloseCallback )

+    {

+        // Check if the program wants us to close the window

+        winclosed = _glfwWin.WindowCloseCallback();

+    }

+    if( winclosed )

+    {

+        glfwCloseWindow();

+    }

+}

+

+

+//========================================================================

+// _glfwPlatformWaitEvents() - Wait for new window and input events

+//========================================================================

+

+void _glfwPlatformWaitEvents( void )

+{

+    // Wait for new events

+    WaitMessage();

+

+    // Poll new events

+    _glfwPlatformPollEvents();

+}

+

+

+//========================================================================

+// Hide mouse cursor (lock it)

+//========================================================================

+

+void _glfwPlatformHideMouseCursor( void )

+{

+    RECT ClipWindowRect;

+

+    // Hide cursor

+    ShowCursor( FALSE );

+

+    // Clip cursor to the window

+    if( GetWindowRect( _glfwWin.Wnd, &ClipWindowRect ) )

+    {

+        ClipCursor( &ClipWindowRect );

+    }

+

+    // Capture cursor to user window

+    SetCapture( _glfwWin.Wnd );

+}

+

+

+//========================================================================

+// Show mouse cursor (unlock it)

+//========================================================================

+

+void _glfwPlatformShowMouseCursor( void )

+{

+    // Un-capture cursor

+    ReleaseCapture();

+

+    // Disable cursor clipping

+    ClipCursor( NULL );

+

+    // Show cursor

+    ShowCursor( TRUE );

+}

+

+

+//========================================================================

+// Set physical mouse cursor position

+//========================================================================

+

+void _glfwPlatformSetMouseCursorPos( int x, int y )

+{

+    POINT pos;

+

+    // Convert client coordinates to screen coordinates

+    pos.x = x;

+    pos.y = y;

+    ClientToScreen( _glfwWin.Wnd, &pos );

+

+    // Change cursor position

+    SetCursorPos( pos.x, pos.y );

+}

+

diff --git a/src/engine/external/glfw/lib/window.c b/src/engine/external/glfw/lib/window.c
new file mode 100644
index 00000000..a878c5f7
--- /dev/null
+++ b/src/engine/external/glfw/lib/window.c
@@ -0,0 +1,727 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        window.c

+// Platform:    Any

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

+

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

+//****                  GLFW internal functions                       ****

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

+

+//========================================================================

+// Clear all open window hints

+//========================================================================

+

+void _glfwClearWindowHints( void )

+{

+    _glfwWinHints.RefreshRate    = 0;

+    _glfwWinHints.AccumRedBits   = 0;

+    _glfwWinHints.AccumGreenBits = 0;

+    _glfwWinHints.AccumBlueBits  = 0;

+    _glfwWinHints.AccumAlphaBits = 0;

+    _glfwWinHints.AuxBuffers     = 0;

+    _glfwWinHints.Stereo         = 0;

+    _glfwWinHints.WindowNoResize = 0;

+    _glfwWinHints.Samples        = 0;

+}

+

+

+//========================================================================

+// Handle the input tracking part of window deactivation

+//========================================================================

+

+void _glfwInputDeactivation( void )

+{

+    int i;

+

+    // Release all keyboard keys

+    for( i = 0; i <= GLFW_KEY_LAST; i ++ )

+    {

+        if( _glfwInput.Key[ i ] == GLFW_PRESS )

+	{

+	    _glfwInputKey( i, GLFW_RELEASE );

+	}

+    }

+

+    // Release all mouse buttons

+    for( i = 0; i <= GLFW_MOUSE_BUTTON_LAST; i ++ )

+    {

+        if( _glfwInput.MouseButton[ i ] == GLFW_PRESS )

+	{

+	    _glfwInputMouseClick( i, GLFW_RELEASE );

+	}

+    }

+}

+

+

+//========================================================================

+// _glfwClearInput() - Clear all input state

+//========================================================================

+

+void _glfwClearInput( void )

+{

+    int i;

+

+    // Release all keyboard keys

+    for( i = 0; i <= GLFW_KEY_LAST; i ++ )

+    {

+        _glfwInput.Key[ i ] = GLFW_RELEASE;

+    }

+

+    // Clear last character

+    _glfwInput.LastChar = 0;

+

+    // Release all mouse buttons

+    for( i = 0; i <= GLFW_MOUSE_BUTTON_LAST; i ++ )

+    {

+        _glfwInput.MouseButton[ i ] = GLFW_RELEASE;

+    }

+

+    // Set mouse position to (0,0)

+    _glfwInput.MousePosX = 0;

+    _glfwInput.MousePosY = 0;

+

+    // Set mouse wheel position to 0

+    _glfwInput.WheelPos = 0;

+

+    // The default is to use non sticky keys and mouse buttons

+    _glfwInput.StickyKeys = GL_FALSE;

+    _glfwInput.StickyMouseButtons = GL_FALSE;

+

+    // The default is to disable key repeat

+    _glfwInput.KeyRepeat = GL_FALSE;

+}

+

+

+//========================================================================

+// _glfwInputKey() - Register keyboard activity

+//========================================================================

+

+void _glfwInputKey( int key, int action )

+{

+    int keyrepeat = 0;

+

+    if( key < 0 || key > GLFW_KEY_LAST )

+    {

+	return;

+    }

+

+    // Are we trying to release an already released key?

+    if( action == GLFW_RELEASE && _glfwInput.Key[ key ] != GLFW_PRESS )

+    {

+	return;

+    }

+

+    // Register key action

+    if( action == GLFW_RELEASE && _glfwInput.StickyKeys )

+    {

+	_glfwInput.Key[ key ] = GLFW_STICK;

+    }

+    else

+    {

+	keyrepeat = (_glfwInput.Key[ key ] == GLFW_PRESS) &&

+		    (action == GLFW_PRESS);

+	_glfwInput.Key[ key ] = (char) action;

+    }

+

+    // Call user callback function

+    if( _glfwWin.KeyCallback && (_glfwInput.KeyRepeat || !keyrepeat) )

+    {

+	_glfwWin.KeyCallback( key, action );

+    }

+}

+

+

+//========================================================================

+// _glfwInputChar() - Register (keyboard) character activity

+//========================================================================

+

+void _glfwInputChar( int character, int action )

+{

+    int keyrepeat = 0;

+

+    // Valid Unicode (ISO 10646) character?

+    if( !( (character >= 32 && character <= 126) || character >= 160 ) )

+    {

+        return;

+    }

+

+    // Is this a key repeat?

+    if( action == GLFW_PRESS && _glfwInput.LastChar == character )

+    {

+        keyrepeat = 1;

+    }

+

+    // Store this character as last character (or clear it, if released)

+    if( action == GLFW_PRESS )

+    {

+        _glfwInput.LastChar = character;

+    }

+    else

+    {

+        _glfwInput.LastChar = 0;

+    }

+

+    // Call user callback function

+    if( _glfwWin.CharCallback && (_glfwInput.KeyRepeat || !keyrepeat) )

+    {

+        _glfwWin.CharCallback( character, action );

+    }

+}

+

+

+//========================================================================

+// _glfwInputMouseClick() - Register mouse button clicks

+//========================================================================

+

+void _glfwInputMouseClick( int button, int action )

+{

+    if( button >= 0 && button <= GLFW_MOUSE_BUTTON_LAST )

+    {

+        // Register mouse button action

+        if( action == GLFW_RELEASE && _glfwInput.StickyMouseButtons )

+        {

+            _glfwInput.MouseButton[ button ] = GLFW_STICK;

+        }

+        else

+        {

+            _glfwInput.MouseButton[ button ] = (char) action;

+        }

+

+        // Call user callback function

+        if( _glfwWin.MouseButtonCallback )

+        {

+            _glfwWin.MouseButtonCallback( button, action );

+        }

+    }

+}

+

+

+

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

+//****                    GLFW user functions                         ****

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

+

+//========================================================================

+// glfwOpenWindow() - Here is where the window is created, and the OpenGL

+// rendering context is created

+//========================================================================

+

+GLFWAPI int GLFWAPIENTRY glfwOpenWindow( int width, int height,

+    int redbits, int greenbits, int bluebits, int alphabits,

+    int depthbits, int stencilbits, int mode )

+{

+    int x;

+    _GLFWhints hints;

+

+    // Is GLFW initialized?

+    if( !_glfwInitialized || _glfwWin.Opened )

+    {

+        return GL_FALSE;

+    }

+

+    // Copy and clear window hints

+    hints = _glfwWinHints;

+    _glfwClearWindowHints();

+

+    // Check input arguments

+    if( mode != GLFW_WINDOW && mode != GLFW_FULLSCREEN )

+    {

+        return GL_FALSE;

+    }

+

+    // Clear GLFW window state

+    _glfwWin.Active            = GL_TRUE;

+    _glfwWin.Iconified         = GL_FALSE;

+    _glfwWin.MouseLock         = GL_FALSE;

+    _glfwWin.AutoPollEvents    = GL_TRUE;

+    _glfwClearInput();

+

+    // Unregister all callback functions

+    _glfwWin.WindowSizeCallback    = NULL;

+    _glfwWin.WindowCloseCallback   = NULL;

+    _glfwWin.WindowRefreshCallback = NULL;

+    _glfwWin.KeyCallback           = NULL;

+    _glfwWin.CharCallback          = NULL;

+    _glfwWin.MousePosCallback      = NULL;

+    _glfwWin.MouseButtonCallback   = NULL;

+    _glfwWin.MouseWheelCallback    = NULL;

+

+    // Check width & height

+    if( width > 0 && height <= 0 )

+    {

+        // Set the window aspect ratio to 4:3

+        height = (width * 3) / 4;

+    }

+    else if( width <= 0 && height > 0 )

+    {

+        // Set the window aspect ratio to 4:3

+        width = (height * 4) / 3;

+    }

+    else if( width <= 0 && height <= 0 )

+    {

+        // Default window size

+        width  = 640;

+        height = 480;

+    }

+

+    // Remember window settings

+    _glfwWin.Width          = width;

+    _glfwWin.Height         = height;

+    _glfwWin.Fullscreen     = (mode == GLFW_FULLSCREEN ? 1 : 0);

+

+    // Platform specific window opening routine

+    if( !_glfwPlatformOpenWindow( width, height, redbits, greenbits,

+            bluebits, alphabits, depthbits, stencilbits, mode, &hints ) )

+    {

+        return GL_FALSE;

+    }

+

+    // Flag that window is now opened

+    _glfwWin.Opened = GL_TRUE;

+

+    // Get window parameters (such as color buffer bits etc)

+    _glfwPlatformRefreshWindowParams();

+

+    // Get OpenGL version

+    glfwGetGLVersion( &_glfwWin.GLVerMajor, &_glfwWin.GLVerMinor, &x );

+

+    // Do we have non-power-of-two textures?

+    _glfwWin.Has_GL_ARB_texture_non_power_of_two =

+        glfwExtensionSupported( "GL_ARB_texture_non_power_of_two" );

+

+    // Do we have automatic mipmap generation?

+    _glfwWin.Has_GL_SGIS_generate_mipmap =

+        (_glfwWin.GLVerMajor >= 2) || (_glfwWin.GLVerMinor >= 4) ||

+        glfwExtensionSupported( "GL_SGIS_generate_mipmap" );

+

+    // If full-screen mode was requested, disable mouse cursor

+    if( mode == GLFW_FULLSCREEN )

+    {

+        glfwDisable( GLFW_MOUSE_CURSOR );

+    }

+

+    return GL_TRUE;

+}

+

+

+//========================================================================

+// glfwOpenWindowHint() - Set hints for opening the window

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwOpenWindowHint( int target, int hint )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized )

+    {

+        return;

+    }

+

+    switch( target )

+    {

+        case GLFW_REFRESH_RATE:

+            _glfwWinHints.RefreshRate = hint;

+            break;

+        case GLFW_ACCUM_RED_BITS:

+            _glfwWinHints.AccumRedBits = hint;

+            break;

+        case GLFW_ACCUM_GREEN_BITS:

+            _glfwWinHints.AccumGreenBits = hint;

+            break;

+        case GLFW_ACCUM_BLUE_BITS:

+            _glfwWinHints.AccumBlueBits = hint;

+            break;

+        case GLFW_ACCUM_ALPHA_BITS:

+            _glfwWinHints.AccumAlphaBits = hint;

+            break;

+        case GLFW_AUX_BUFFERS:

+            _glfwWinHints.AuxBuffers = hint;

+            break;

+        case GLFW_STEREO:

+            _glfwWinHints.Stereo = hint;

+            break;

+        case GLFW_WINDOW_NO_RESIZE:

+            _glfwWinHints.WindowNoResize = hint;

+            break;

+	case GLFW_FSAA_SAMPLES:

+            _glfwWinHints.Samples = hint;

+            break;

+        default:

+            break;

+    }

+}

+

+

+//========================================================================

+// glfwCloseWindow() - Properly kill the window / video display

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwCloseWindow( void )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized )

+    {

+        return;

+    }

+

+    // Show mouse pointer again (if hidden)

+    glfwEnable( GLFW_MOUSE_CURSOR );

+

+    // Close window

+    _glfwPlatformCloseWindow();

+

+    // Window is no longer opened

+    _glfwWin.Opened = GL_FALSE;

+}

+

+

+//========================================================================

+// glfwSetWindowTitle() - Set the window title

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwSetWindowTitle( const char *title )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return;

+    }

+

+    // Set window title

+    _glfwPlatformSetWindowTitle( title );

+}

+

+

+//========================================================================

+// glfwGetWindowSize() - Get the window size

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwGetWindowSize( int *width, int *height )

+{

+    if( width != NULL )

+    {

+        *width = _glfwWin.Width;

+    }

+    if( height != NULL )

+    {

+        *height = _glfwWin.Height;

+    }

+}

+

+

+//========================================================================

+// glfwSetWindowSize() - Set the window size

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwSetWindowSize( int width, int height )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened || _glfwWin.Iconified )

+    {

+        return;

+    }

+

+    // Don't do anything if the window size did not change

+    if( width == _glfwWin.Width && height == _glfwWin.Height )

+    {

+        return;

+    }

+

+    // Change window size

+    _glfwPlatformSetWindowSize( width, height );

+

+    // Refresh window parameters (may have changed due to changed video

+    // modes)

+    _glfwPlatformRefreshWindowParams();

+}

+

+

+//========================================================================

+// glfwSetWindowPos() - Set the window position

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwSetWindowPos( int x, int y )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened || _glfwWin.Fullscreen ||

+        _glfwWin.Iconified )

+    {

+        return;

+    }

+

+    // Set window position

+    _glfwPlatformSetWindowPos( x, y );

+}

+

+

+//========================================================================

+// glfwIconfyWindow() - Window iconification

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwIconifyWindow( void )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened || _glfwWin.Iconified )

+    {

+        return;

+    }

+

+    // Iconify window

+    _glfwPlatformIconifyWindow();

+}

+

+

+//========================================================================

+// glfwRestoreWindow() - Window un-iconification

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwRestoreWindow( void )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened || !_glfwWin.Iconified )

+    {

+        return;

+    }

+

+    // Restore iconified window

+    _glfwPlatformRestoreWindow();

+

+    // Refresh window parameters

+    _glfwPlatformRefreshWindowParams();

+}

+

+

+//========================================================================

+// glfwSwapBuffers() - Swap buffers (double-buffering) and poll any new

+// events

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwSwapBuffers( void )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return;

+    }

+

+    // Check for window messages

+    if( _glfwWin.AutoPollEvents )

+    {

+        glfwPollEvents();

+    }

+

+    // Update display-buffer

+    if( _glfwWin.Opened )

+    {

+        _glfwPlatformSwapBuffers();

+    }

+}

+

+

+//========================================================================

+// glfwSwapInterval() - Set double buffering swap interval (0 = vsync off)

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwSwapInterval( int interval )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return;

+    }

+

+    // Set double buffering swap interval

+    _glfwPlatformSwapInterval( interval );

+}

+

+

+//========================================================================

+// glfwGetWindowParam() - Get window parameter

+//========================================================================

+

+GLFWAPI int GLFWAPIENTRY glfwGetWindowParam( int param )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized )

+    {

+        return 0;

+    }

+

+    // Is the window opened?

+    if( !_glfwWin.Opened )

+    {

+        if( param == GLFW_OPENED )

+        {

+            return GL_FALSE;

+        }

+        return 0;

+    }

+

+    // Window parameters

+    switch( param )

+    {

+        case GLFW_OPENED:

+            return GL_TRUE;

+        case GLFW_ACTIVE:

+            return _glfwWin.Active;

+        case GLFW_ICONIFIED:

+            return _glfwWin.Iconified;

+        case GLFW_ACCELERATED:

+            return _glfwWin.Accelerated;

+        case GLFW_RED_BITS:

+            return _glfwWin.RedBits;

+        case GLFW_GREEN_BITS:

+            return _glfwWin.GreenBits;

+        case GLFW_BLUE_BITS:

+            return _glfwWin.BlueBits;

+        case GLFW_ALPHA_BITS:

+            return _glfwWin.AlphaBits;

+        case GLFW_DEPTH_BITS:

+            return _glfwWin.DepthBits;

+        case GLFW_STENCIL_BITS:

+            return _glfwWin.StencilBits;

+        case GLFW_ACCUM_RED_BITS:

+            return _glfwWin.AccumRedBits;

+        case GLFW_ACCUM_GREEN_BITS:

+            return _glfwWin.AccumGreenBits;

+        case GLFW_ACCUM_BLUE_BITS:

+            return _glfwWin.AccumBlueBits;

+        case GLFW_ACCUM_ALPHA_BITS:

+            return _glfwWin.AccumAlphaBits;

+        case GLFW_AUX_BUFFERS:

+            return _glfwWin.AuxBuffers;

+        case GLFW_STEREO:

+            return _glfwWin.Stereo;

+        case GLFW_REFRESH_RATE:

+            return _glfwWin.RefreshRate;

+        case GLFW_WINDOW_NO_RESIZE:

+            return _glfwWin.WindowNoResize;

+	case GLFW_FSAA_SAMPLES:

+	    return _glfwWin.Samples;

+        default:

+            return 0;

+    }

+}

+

+

+//========================================================================

+// glfwSetWindowSizeCallback() - Set callback function for window size

+// changes

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwSetWindowSizeCallback( GLFWwindowsizefun cbfun )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return;

+    }

+

+    // Set callback function

+    _glfwWin.WindowSizeCallback = cbfun;

+

+    // Call the callback function to let the application know the current

+    // window size

+    if( cbfun )

+    {

+        cbfun( _glfwWin.Width, _glfwWin.Height );

+    }

+}

+

+//========================================================================

+// glfwSetWindowCloseCallback() - Set callback function for window close

+// events

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwSetWindowCloseCallback( GLFWwindowclosefun cbfun )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return;

+    }

+

+    // Set callback function

+    _glfwWin.WindowCloseCallback = cbfun;

+}

+

+

+//========================================================================

+// glfwSetWindowRefreshCallback() - Set callback function for window

+// refresh events

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwSetWindowRefreshCallback( GLFWwindowrefreshfun cbfun )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return;

+    }

+

+    // Set callback function

+    _glfwWin.WindowRefreshCallback = cbfun;

+}

+

+

+//========================================================================

+// glfwPollEvents() - Poll for new window and input events

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwPollEvents( void )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return;

+    }

+

+    // Poll for new events

+    _glfwPlatformPollEvents();

+}

+

+

+//========================================================================

+// glfwWaitEvents() - Wait for new window and input events

+//========================================================================

+

+GLFWAPI void GLFWAPIENTRY glfwWaitEvents( void )

+{

+    // Is GLFW initialized?

+    if( !_glfwInitialized || !_glfwWin.Opened )

+    {

+        return;

+    }

+

+    // Poll for new events

+    _glfwPlatformWaitEvents();

+}

+

diff --git a/src/engine/external/glfw/lib/x11/platform.h b/src/engine/external/glfw/lib/x11/platform.h
new file mode 100644
index 00000000..d03d3582
--- /dev/null
+++ b/src/engine/external/glfw/lib/x11/platform.h
@@ -0,0 +1,415 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        platform.h

+// Platform:    X11 (Unix)

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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 _platform_h_

+#define _platform_h_

+

+

+// This is the X11 version of GLFW

+#define _GLFW_X11

+

+

+// Include files

+#include <sys/time.h>

+#include <unistd.h>

+#include <signal.h>

+#include <X11/Xlib.h>

+#include <X11/keysym.h>

+#include <X11/Xatom.h>

+#include <GL/glx.h>

+#include "../../include/GL/glfw.h"

+

+// Do we have pthread support?

+#ifdef _GLFW_HAS_PTHREAD

+ #include <pthread.h>

+ #include <sched.h>

+#endif

+

+// With XFree86, we can use the XF86VidMode extension

+#if defined( _GLFW_HAS_XF86VIDMODE )

+ #include <X11/extensions/xf86vmode.h>

+#endif

+

+#if defined( _GLFW_HAS_XRANDR )

+ #include <X11/extensions/Xrandr.h>

+#endif

+

+// Do we have support for dlopen/dlsym?

+#if defined( _GLFW_HAS_DLOPEN )

+ #include <dlfcn.h>

+#endif

+

+// We support two different ways for getting the number of processors in

+// the system: sysconf (POSIX) and sysctl (BSD?)

+#if defined( _GLFW_HAS_SYSCONF )

+

+ // Use a single constant for querying number of online processors using

+ // the sysconf function (e.g. SGI defines _SC_NPROC_ONLN instead of

+ // _SC_NPROCESSORS_ONLN)

+ #ifndef _SC_NPROCESSORS_ONLN

+  #ifdef  _SC_NPROC_ONLN

+   #define _SC_NPROCESSORS_ONLN _SC_NPROC_ONLN

+  #else

+   #error POSIX constant _SC_NPROCESSORS_ONLN not defined!

+  #endif

+ #endif

+

+ // Macro for querying the number of processors

+ #define _glfw_numprocessors(n) n=(int)sysconf(_SC_NPROCESSORS_ONLN)

+

+#elif defined( _GLFW_HAS_SYSCTL )

+

+ #include <sys/types.h>

+ #include <sys/sysctl.h>

+

+ // Macro for querying the number of processors

+ #define _glfw_numprocessors(n) { \

+    int mib[2], ncpu; \

+    size_t len = 1; \

+    mib[0] = CTL_HW; \

+    mib[1] = HW_NCPU; \

+    n      = 1; \

+    if( sysctl( mib, 2, &ncpu, &len, NULL, 0 ) != -1 ) \

+    { \

+        if( len > 0 ) \

+        { \

+            n = ncpu; \

+        } \

+    } \

+ }

+

+#else

+

+ // If neither sysconf nor sysctl is supported, assume single processor

+ // system

+ #define _glfw_numprocessors(n) n=1

+

+#endif

+

+void (*glXGetProcAddress(const GLubyte *procName))();

+void (*glXGetProcAddressARB(const GLubyte *procName))();

+void (*glXGetProcAddressEXT(const GLubyte *procName))();

+

+// We support four different ways for getting addresses for GL/GLX

+// extension functions: glXGetProcAddress, glXGetProcAddressARB,

+// glXGetProcAddressEXT, and dlsym

+#if   defined( _GLFW_HAS_GLXGETPROCADDRESSARB )

+ #define _glfw_glXGetProcAddress(x) glXGetProcAddressARB(x)

+#elif defined( _GLFW_HAS_GLXGETPROCADDRESS )

+ #define _glfw_glXGetProcAddress(x) glXGetProcAddress(x)

+#elif defined( _GLFW_HAS_GLXGETPROCADDRESSEXT )

+ #define _glfw_glXGetProcAddress(x) glXGetProcAddressEXT(x)

+#elif defined( _GLFW_HAS_DLOPEN )

+ #define _glfw_glXGetProcAddress(x) dlsym(_glfwLibs.libGL,x)

+ #define _GLFW_DLOPEN_LIBGL

+#else

+#define _glfw_glXGetProcAddress(x) NULL

+#endif

+

+// glXSwapIntervalSGI typedef (X11 buffer-swap interval control)

+typedef int ( * GLXSWAPINTERVALSGI_T) (int interval);

+

+

+//========================================================================

+// Global variables (GLFW internals)

+//========================================================================

+

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

+// Window structure

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

+typedef struct _GLFWwin_struct _GLFWwin;

+

+struct _GLFWwin_struct {

+

+// ========= PLATFORM INDEPENDENT MANDATORY PART =========================

+

+    // User callback functions

+    GLFWwindowsizefun    WindowSizeCallback;

+    GLFWwindowclosefun   WindowCloseCallback;

+    GLFWwindowrefreshfun WindowRefreshCallback;

+    GLFWmousebuttonfun   MouseButtonCallback;

+    GLFWmouseposfun      MousePosCallback;

+    GLFWmousewheelfun    MouseWheelCallback;

+    GLFWkeyfun           KeyCallback;

+    GLFWcharfun          CharCallback;

+

+    // User selected window settings

+    int       Fullscreen;      // Fullscreen flag

+    int       MouseLock;       // Mouse-lock flag

+    int       AutoPollEvents;  // Auto polling flag

+    int       SysKeysDisabled; // System keys disabled flag

+    int       WindowNoResize;  // Resize- and maximize gadgets disabled flag

+

+    // Window status & parameters

+    int       Opened;          // Flag telling if window is opened or not

+    int       Active;          // Application active flag

+    int       Iconified;       // Window iconified flag

+    int       Width, Height;   // Window width and heigth

+    int       Accelerated;     // GL_TRUE if window is HW accelerated

+    int       RedBits;

+    int       GreenBits;

+    int       BlueBits;

+    int       AlphaBits;

+    int       DepthBits;

+    int       StencilBits;

+    int       AccumRedBits;

+    int       AccumGreenBits;

+    int       AccumBlueBits;

+    int       AccumAlphaBits;

+    int       AuxBuffers;

+    int       Stereo;

+    int       RefreshRate;     // Vertical monitor refresh rate

+    int       Samples;

+

+    // Extensions & OpenGL version

+    int       Has_GL_SGIS_generate_mipmap;

+    int       Has_GL_ARB_texture_non_power_of_two;

+    int       GLVerMajor,GLVerMinor;

+

+

+// ========= PLATFORM SPECIFIC PART ======================================

+

+    // Platform specific window resources

+    Window      Win;             // Window

+    int         Scrn;            // Screen ID

+    XVisualInfo *VI;             // Visual

+    GLXContext  CX;              // OpenGL rendering context

+    Atom        WMDeleteWindow;  // For WM close detection

+    Atom        WMPing;          // For WM ping response

+    XSizeHints  *Hints;          // WM size hints

+

+    // Platform specific extensions

+    GLXSWAPINTERVALSGI_T SwapInterval;

+

+    // Various platform specific internal variables

+    int         OverrideRedirect; // True if window is OverrideRedirect

+    int         KeyboardGrabbed; // True if keyboard is currently grabbed

+    int         PointerGrabbed;  // True if pointer is currently grabbed

+    int         PointerHidden;   // True if pointer is currently hidden

+    int         MapNotifyCount;  // Used for during processing

+    int         FocusInCount;    // Used for during processing

+

+    // Screensaver data

+    struct {

+	int     Changed;

+	int     Timeout;

+	int     Interval;

+	int     Blanking;

+	int     Exposure;

+    } Saver;

+

+    // Fullscreen data

+    struct {

+	int     ModeChanged;

+#if defined( _GLFW_HAS_XF86VIDMODE )

+	XF86VidModeModeInfo OldMode;

+#endif

+#if defined( _GLFW_HAS_XRANDR )

+        SizeID   OldSizeID;

+	int      OldWidth;

+	int      OldHeight;

+	Rotation OldRotation;

+#endif

+    } FS;

+};

+

+GLFWGLOBAL _GLFWwin _glfwWin;

+

+

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

+// User input status (most of this should go in _GLFWwin)

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

+GLFWGLOBAL struct {

+

+// ========= PLATFORM INDEPENDENT MANDATORY PART =========================

+

+    // Mouse status

+    int  MousePosX, MousePosY;

+    int  WheelPos;

+    char MouseButton[ GLFW_MOUSE_BUTTON_LAST+1 ];

+

+    // Keyboard status

+    char Key[ GLFW_KEY_LAST+1 ];

+    int  LastChar;

+

+    // User selected settings

+    int  StickyKeys;

+    int  StickyMouseButtons;

+    int  KeyRepeat;

+

+

+// ========= PLATFORM SPECIFIC PART ======================================

+

+    // Platform specific internal variables

+    int  MouseMoved, CursorPosX, CursorPosY;

+

+} _glfwInput;

+

+

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

+// Library global data

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

+GLFWGLOBAL struct {

+

+// ========= PLATFORM SPECIFIC PART ======================================

+

+    Display     *Dpy;

+    int         NumScreens;

+    int         DefaultScreen;

+

+    struct {

+	int	Available;

+	int     EventBase;

+	int     ErrorBase;

+    } XF86VidMode;

+

+    struct {

+	int	Available;

+	int     EventBase;

+	int     ErrorBase;

+    } XRandR;

+

+    // Timer data

+    struct {

+	double       Resolution;

+	long long    t0;

+    } Timer;

+

+#if defined(_GLFW_DLOPEN_LIBGL)

+    struct {

+	void        *libGL;          // dlopen handle for libGL.so

+    } Libs;

+#endif

+} _glfwLibrary;

+

+

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

+// Thread record (one for each thread)

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

+typedef struct _GLFWthread_struct _GLFWthread;

+

+struct _GLFWthread_struct {

+

+// ========= PLATFORM INDEPENDENT MANDATORY PART =========================

+

+    // Pointer to previous and next threads in linked list

+    _GLFWthread   *Previous, *Next;

+

+    // GLFW user side thread information

+    GLFWthread    ID;

+    GLFWthreadfun Function;

+

+// ========= PLATFORM SPECIFIC PART ======================================

+

+    // System side thread information

+#ifdef _GLFW_HAS_PTHREAD

+    pthread_t     PosixID;

+#endif

+

+};

+

+

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

+// General thread information

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

+GLFWGLOBAL struct {

+

+// ========= PLATFORM INDEPENDENT MANDATORY PART =========================

+

+    // Next thread ID to use (increments for every created thread)

+    GLFWthread       NextID;

+

+    // First thread in linked list (always the main thread)

+    _GLFWthread      First;

+

+// ========= PLATFORM SPECIFIC PART ======================================

+

+    // Critical section lock

+#ifdef _GLFW_HAS_PTHREAD

+    pthread_mutex_t  CriticalSection;

+#endif

+

+} _glfwThrd;

+

+

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

+// Joystick information & state

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

+GLFWGLOBAL struct {

+    int           Present;

+    int           fd;

+    int           NumAxes;

+    int           NumButtons;

+    float         *Axis;

+    unsigned char *Button;

+} _glfwJoy[ GLFW_JOYSTICK_LAST + 1 ];

+

+

+//========================================================================

+// Macros for encapsulating critical code sections (i.e. making parts

+// of GLFW thread safe)

+//========================================================================

+

+// Thread list management

+#ifdef _GLFW_HAS_PTHREAD

+ #define ENTER_THREAD_CRITICAL_SECTION \

+         pthread_mutex_lock( &_glfwThrd.CriticalSection );

+ #define LEAVE_THREAD_CRITICAL_SECTION \

+         pthread_mutex_unlock( &_glfwThrd.CriticalSection );

+#else

+ #define ENTER_THREAD_CRITICAL_SECTION

+ #define LEAVE_THREAD_CRITICAL_SECTION

+#endif

+

+

+//========================================================================

+// Prototypes for platform specific internal functions

+//========================================================================

+

+// Time

+void _glfwInitTimer( void );

+

+// Fullscreen support

+int  _glfwGetClosestVideoMode( int screen, int *width, int *height, int *rate );

+void _glfwSetVideoModeMODE( int screen, int mode, int rate );

+void _glfwSetVideoMode( int screen, int *width, int *height, int *rate );

+

+// Cursor handling

+Cursor _glfwCreateNULLCursor( Display *display, Window root );

+

+// Joystick input

+void _glfwInitJoysticks( void );

+void _glfwTerminateJoysticks( void );

+

+// Unicode support

+long _glfwKeySym2Unicode( KeySym keysym );

+

+

+#endif // _platform_h_

diff --git a/src/engine/external/glfw/lib/x11/x11_enable.c b/src/engine/external/glfw/lib/x11/x11_enable.c
new file mode 100644
index 00000000..486833f7
--- /dev/null
+++ b/src/engine/external/glfw/lib/x11/x11_enable.c
@@ -0,0 +1,51 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        x11_enable.c

+// Platform:    X11 (Unix)

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

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

+//****               Platform implementation functions                ****

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

+

+//========================================================================

+// _glfwPlatformEnableSystemKeys() - Enable system keys

+// _glfwPlatformDisableSystemKeys() - Disable system keys

+//========================================================================

+

+void _glfwPlatformEnableSystemKeys( void )

+{

+    // Not supported under X11 (yet)

+}

+

+void _glfwPlatformDisableSystemKeys( void )

+{

+    // Not supported under X11 (yet)

+}

diff --git a/src/engine/external/glfw/lib/x11/x11_fullscreen.c b/src/engine/external/glfw/lib/x11/x11_fullscreen.c
new file mode 100644
index 00000000..2eb3cf75
--- /dev/null
+++ b/src/engine/external/glfw/lib/x11/x11_fullscreen.c
@@ -0,0 +1,524 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        x11_fullscreen.c

+// Platform:    X11 (Unix)

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

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

+//****                  GLFW internal functions                       ****

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

+

+//========================================================================

+// _glfwBPP2RGB() - Convert BPP to RGB bits (based on "best guess")

+//========================================================================

+

+static void _glfwBPP2RGB( int bpp, int *r, int *g, int *b )

+{

+    int delta;

+

+    // Special case: BPP = 32 (I don't think this is necessary for X11??)

+    if( bpp == 32 )

+	bpp = 24;

+

+    // Convert "bits per pixel" to red, green & blue sizes

+    *r = *g = *b = bpp / 3;

+    delta = bpp - (*r * 3);

+    if( delta >= 1 )

+    {

+        *g = *g + 1;

+    }

+    if( delta == 2 )

+    {

+        *r = *r + 1;

+    }

+}

+

+

+//========================================================================

+// Finds the video mode closest in size to the specified desired size

+//========================================================================

+

+int _glfwGetClosestVideoMode( int screen, int *width, int *height, int *rate )

+{

+#if defined( _GLFW_HAS_XRANDR )

+    int i, match, bestmatch;

+    int sizecount, bestsize;

+    int ratecount, bestrate;

+    short *ratelist;

+    XRRScreenConfiguration *sc;

+    XRRScreenSize *sizelist;

+

+    if( _glfwLibrary.XRandR.Available )

+    {

+	sc = XRRGetScreenInfo( _glfwLibrary.Dpy,

+			       RootWindow( _glfwLibrary.Dpy, screen ) );

+

+	sizelist = XRRConfigSizes( sc, &sizecount );

+

+        // Find the best matching mode

+        bestsize  = -1;

+        bestmatch = 999999;

+        for( i = 0; i < sizecount; i++ )

+        {

+            match = (*width - sizelist[i].width) *

+                    (*width - sizelist[i].width) +

+                    (*height - sizelist[i].height) *

+                    (*height - sizelist[i].height);

+            if( match < bestmatch )

+            {

+                bestmatch = match;

+                bestsize  = i;

+            }

+        }

+

+	if( bestsize != -1 )

+	{

+	    // Report width & height of best matching mode

+	    *width = sizelist[bestsize].width;

+	    *height = sizelist[bestsize].height;

+

+	    if( *rate > 0 )

+	    {

+		ratelist = XRRConfigRates( sc, bestsize, &ratecount );

+

+		bestrate = -1;

+		bestmatch = 999999;

+		for( i = 0; i < ratecount; i++ )

+		{

+		    match = abs( ratelist[i] - *rate );

+		    if( match < bestmatch )

+		    {

+			bestmatch = match;

+			bestrate = ratelist[i];

+		    }

+		}

+		

+		if( bestrate != -1 )

+		{

+		    *rate = bestrate;

+		}

+	    }

+	}

+

+        // Free modelist

+	XRRFreeScreenConfigInfo( sc );

+

+	if( bestsize != -1 )

+	{

+	    return bestsize;

+	}

+    }

+#elif defined( _GLFW_HAS_XF86VIDMODE )

+    XF86VidModeModeInfo **modelist;

+    int modecount, i, bestmode, bestmatch, match;

+

+    // Use the XF86VidMode extension to control video resolution

+    if( _glfwLibrary.XF86VidMode.Available )

+    {

+        // Get a list of all available display modes

+        XF86VidModeGetAllModeLines( _glfwLibrary.Dpy, screen,

+                                    &modecount, &modelist );

+

+        // Find the best matching mode

+        bestmode  = -1;

+        bestmatch = 999999;

+        for( i = 0; i < modecount; i++ )

+        {

+            match = (*width - modelist[i]->hdisplay) *

+                    (*width - modelist[i]->hdisplay) +

+                    (*height - modelist[i]->vdisplay) *

+                    (*height - modelist[i]->vdisplay);

+            if( match < bestmatch )

+            {

+                bestmatch = match;

+                bestmode  = i;

+            }

+        }

+

+	if( bestmode != -1 )

+	{

+	    // Report width & height of best matching mode

+	    *width = modelist[ bestmode ]->hdisplay;

+	    *h = modelist[ bestmode ]->vdisplay;

+	}

+

+        // Free modelist

+        XFree( modelist );

+

+	if( bestmode != -1 )

+	{

+	    return bestmode;

+	}

+    }

+#endif

+

+    // Default: Simply use the screen resolution

+    *width = DisplayWidth( _glfwLibrary.Dpy, screen );

+    *height = DisplayHeight( _glfwLibrary.Dpy, screen );

+

+    return 0;

+}

+

+

+//========================================================================

+// Change the current video mode

+//========================================================================

+

+void _glfwSetVideoModeMODE( int screen, int mode, int rate )

+{

+#if defined( _GLFW_HAS_XRANDR )

+    XRRScreenConfiguration *sc;

+    Window root;

+

+    if( _glfwLibrary.XRandR.Available )

+    {

+	root = RootWindow( _glfwLibrary.Dpy, screen );

+	sc   = XRRGetScreenInfo( _glfwLibrary.Dpy, root );

+

+        // Remember old size and flag that we have changed the mode

+        if( !_glfwWin.FS.ModeChanged )

+        {

+	    _glfwWin.FS.OldSizeID = XRRConfigCurrentConfiguration( sc, &_glfwWin.FS.OldRotation );

+	    _glfwWin.FS.OldWidth  = DisplayWidth( _glfwLibrary.Dpy, screen );

+	    _glfwWin.FS.OldHeight = DisplayHeight( _glfwLibrary.Dpy, screen );

+

+            _glfwWin.FS.ModeChanged = GL_TRUE;

+        }

+

+	if( rate > 0 )

+	{

+	    // Set desired configuration

+	    XRRSetScreenConfigAndRate( _glfwLibrary.Dpy,

+				       sc,

+				       root,

+				       mode,

+				       RR_Rotate_0,

+				       (short) rate,

+				       CurrentTime );

+	}

+	else

+	{

+	    // Set desired configuration

+	    XRRSetScreenConfig( _glfwLibrary.Dpy,

+				sc,

+				root,

+				mode,

+				RR_Rotate_0,

+				CurrentTime );

+	}

+

+	XRRFreeScreenConfigInfo( sc );

+    }

+#elif defined( _GLFW_HAS_XF86VIDMODE )

+    XF86VidModeModeInfo **modelist;

+    int modecount;

+

+    // Use the XF86VidMode extension to control video resolution

+    if( _glfwLibrary.XF86VidMode.Available )

+    {

+        // Get a list of all available display modes

+        XF86VidModeGetAllModeLines( _glfwLibrary.Dpy, screen,

+                                    &modecount, &modelist );

+

+        // Unlock mode switch if necessary

+        if( _glfwWin.FS.ModeChanged )

+        {

+            XF86VidModeLockModeSwitch( _glfwLibrary.Dpy, screen, 0 );

+        }

+

+        // Change the video mode to the desired mode

+        XF86VidModeSwitchToMode(  _glfwLibrary.Dpy, screen,

+                                  modelist[ mode ] );

+

+        // Set viewport to upper left corner (where our window will be)

+        XF86VidModeSetViewPort( _glfwLibrary.Dpy, screen, 0, 0 );

+

+        // Lock mode switch

+        XF86VidModeLockModeSwitch( _glfwLibrary.Dpy, screen, 1 );

+

+        // Remember old mode and flag that we have changed the mode

+        if( !_glfwWin.FS.ModeChanged )

+        {

+            _glfwWin.FS.OldMode = *modelist[ 0 ];

+            _glfwWin.FS.ModeChanged = GL_TRUE;

+        }

+

+        // Free mode list

+        XFree( modelist );

+    }

+#endif

+}

+

+

+//========================================================================

+// Change the current video mode

+//========================================================================

+

+void _glfwSetVideoMode( int screen, int *width, int *height, int *rate )

+{

+    int     bestmode;

+

+    // Find a best match mode

+    bestmode = _glfwGetClosestVideoMode( screen, width, height, rate );

+

+    // Change mode

+    _glfwSetVideoModeMODE( screen, bestmode, *rate );

+}

+

+

+

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

+//****               Platform implementation functions                ****

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

+

+struct _glfwResolution {

+    int width;

+    int height;

+};

+

+//========================================================================

+// List available video modes

+//========================================================================

+

+int _glfwPlatformGetVideoModes( GLFWvidmode *list, int maxcount )

+{

+    int     count, k, l, r, g, b, rgba, gl;

+    int     depth, screen;

+    Display *dpy;

+    XVisualInfo *vislist, dummy;

+    int     viscount, rgbcount, rescount;

+    int     *rgbarray;

+    struct _glfwResolution *resarray;

+#if defined( _GLFW_HAS_XRANDR )

+    XRRScreenConfiguration *sc;

+    XRRScreenSize *sizelist;

+    int     sizecount;

+#elif defined( _GLFW_HAS_XF86VIDMODE )

+    XF86VidModeModeInfo **modelist;

+    int     modecount, width, height;

+#endif

+

+    // Get display and screen

+    dpy = _glfwLibrary.Dpy;

+    screen = DefaultScreen( dpy );

+

+    // Get list of visuals

+    vislist = XGetVisualInfo( dpy, 0, &dummy, &viscount );

+    if( vislist == NULL )

+    {

+	return 0;

+    }

+

+    rgbarray = (int*) malloc( sizeof(int) * viscount );

+    rgbcount = 0;

+

+    // Build RGB array

+    for( k = 0; k < viscount; k++ )

+    {

+        // Does the visual support OpenGL & true color?

+        glXGetConfig( dpy, &vislist[k], GLX_USE_GL, &gl );

+        glXGetConfig( dpy, &vislist[k], GLX_RGBA, &rgba );

+        if( gl && rgba )

+        {

+            // Get color depth for this visual

+            depth = vislist[k].depth;

+

+            // Convert to RGB

+            _glfwBPP2RGB( depth, &r, &g, &b );

+            depth = (r<<16) | (g<<8) | b;

+

+            // Is this mode unique?

+            for( l = 0; l < rgbcount; l++ )

+            {

+                if( depth == rgbarray[ l ] )

+                {

+                    break;

+                }

+            }

+            if( l >= rgbcount )

+            {

+                rgbarray[ rgbcount ] = depth;

+                rgbcount++;

+            }

+        }

+    }

+

+    rescount = 0;

+    resarray = NULL;

+

+    // Build resolution array

+#if defined( _GLFW_HAS_XRANDR )

+    if( _glfwLibrary.XRandR.Available )

+    {

+	sc = XRRGetScreenInfo( dpy, RootWindow( dpy, screen ) );

+	sizelist = XRRConfigSizes( sc, &sizecount );

+

+	resarray = (struct _glfwResolution*) malloc( sizeof(struct _glfwResolution) * sizecount );

+

+        for( k = 0; k < sizecount; k++ )

+        {

+	    resarray[ rescount ].width = sizelist[ k ].width;

+	    resarray[ rescount ].height = sizelist[ k ].height;

+	    rescount++;

+        }

+

+	XRRFreeScreenConfigInfo( sc );

+    }

+#elif defined( _GLFW_HAS_XF86VIDMODE )

+    if( _glfwLibrary.XF86VidMode.Available )

+    {

+        XF86VidModeGetAllModeLines( dpy, screen, &modecount, &modelist );

+

+	resarray = (struct _glfwResolution*) malloc( sizeof(struct _glfwResolution) * modecount );

+

+        for( k = 0; k < modecount; k++ )

+        {

+            width  = modelist[ k ]->hdisplay;

+            height = modelist[ k ]->vdisplay;

+

+            // Is this mode unique?

+            for( l = 0; l < rescount; l++ )

+            {

+                if( width == resarray[ l ].width && height == resarray[ l ].height )

+                {

+                    break;

+                }

+            }

+            if( l >= rescount )

+            {

+                resarray[ rescount ].width = width;

+                resarray[ rescount ].height = height;

+                rescount++;

+            }

+        }

+

+	XFree( modelist );

+    }

+#endif

+

+    if( !resarray )

+    {

+	rescount = 1;

+	resarray = (struct _glfwResolution*) malloc( sizeof(struct _glfwResolution) * rescount );

+

+	resarray[ 0 ].width = DisplayWidth( dpy, screen );

+	resarray[ 0 ].height = DisplayHeight( dpy, screen );

+    }

+

+    // Build permutations of colors and resolutions

+    count = 0;

+    for( k = 0; k < rgbcount && count < maxcount; k++ )

+    {

+        for( l = 0; l < rescount && count < maxcount; l++ )

+        {

+            list[count].Width     = resarray[ l ].width;

+            list[count].Height    = resarray[ l ].height;

+            list[count].RedBits   = (rgbarray[ k ] >> 16) & 255;

+            list[count].GreenBits = (rgbarray[ k ] >> 8) & 255;

+            list[count].BlueBits  = rgbarray[ k ] & 255;

+            count++;

+        }

+    }

+

+    // Free visuals list

+    XFree( vislist );

+

+    free( resarray );

+    free( rgbarray );

+

+    return count;

+}

+

+

+//========================================================================

+// Get the desktop video mode

+//========================================================================

+

+void _glfwPlatformGetDesktopMode( GLFWvidmode *mode )

+{

+    Display *dpy;

+    int     bpp, screen;

+#if defined( _GLFW_HAS_XF86VIDMODE )

+    XF86VidModeModeInfo **modelist;

+    int     modecount;

+#endif

+

+    // Get display and screen

+    dpy = _glfwLibrary.Dpy;

+    screen = DefaultScreen( dpy );

+

+    // Get display depth

+    bpp = DefaultDepth( dpy, screen );

+

+    // Convert BPP to RGB bits

+    _glfwBPP2RGB( bpp, &mode->RedBits, &mode->GreenBits, &mode->BlueBits );

+

+#if defined( _GLFW_HAS_XRANDR )

+    if( _glfwLibrary.XRandR.Available )

+    {

+        if( _glfwWin.FS.ModeChanged )

+        {

+	    mode->Width  = _glfwWin.FS.OldWidth;

+	    mode->Height = _glfwWin.FS.OldHeight;

+	    return;

+	}

+    }

+#elif defined( _GLFW_HAS_XF86VIDMODE )

+    if( _glfwLibrary.XF86VidMode.Available )

+    {

+        if( _glfwWin.FS.ModeChanged )

+        {

+            // The old (desktop) mode is stored in _glfwWin.FS.OldMode

+            mode->Width  = _glfwWin.FS.OldMode.hdisplay;

+            mode->Height = _glfwWin.FS.OldMode.vdisplay;

+        }

+        else

+        {

+            // Use the XF86VidMode extension to get list of video modes

+            XF86VidModeGetAllModeLines( dpy, screen, &modecount,

+                                        &modelist );

+

+            // The first mode in the list is the current (desktio) mode

+            mode->Width  = modelist[ 0 ]->hdisplay;

+            mode->Height = modelist[ 0 ]->vdisplay;

+

+            // Free list

+            XFree( modelist );

+        }

+

+	return;

+    }

+#endif

+

+    // Get current display width and height

+    mode->Width  = DisplayWidth( dpy, screen );

+    mode->Height = DisplayHeight( dpy, screen );

+}

+

diff --git a/src/engine/external/glfw/lib/x11/x11_glext.c b/src/engine/external/glfw/lib/x11/x11_glext.c
new file mode 100644
index 00000000..242c9eb1
--- /dev/null
+++ b/src/engine/external/glfw/lib/x11/x11_glext.c
@@ -0,0 +1,69 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        x11_glext.c

+// Platform:    X11 (Unix)

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

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

+//****               Platform implementation functions                ****

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

+

+//========================================================================

+// Check if an OpenGL extension is available at runtime

+//========================================================================

+

+int _glfwPlatformExtensionSupported( const char *extension )

+{

+    const GLubyte *extensions;

+

+    // Get list of GLX extensions

+    extensions = (const GLubyte*) glXQueryExtensionsString( _glfwLibrary.Dpy,

+                                                            _glfwWin.Scrn );

+    if( extensions != NULL )

+    {

+        if( _glfwStringInExtensionString( extension, extensions ) )

+        {

+            return GL_TRUE;

+        }

+    }

+

+    return GL_FALSE;

+}

+

+

+//========================================================================

+// Get the function pointer to an OpenGL function

+//========================================================================

+

+void * _glfwPlatformGetProcAddress( const char *procname )

+{

+    return (void *) _glfw_glXGetProcAddress( (const GLubyte *) procname );

+}

+

diff --git a/src/engine/external/glfw/lib/x11/x11_init.c b/src/engine/external/glfw/lib/x11/x11_init.c
new file mode 100644
index 00000000..9e406156
--- /dev/null
+++ b/src/engine/external/glfw/lib/x11/x11_init.c
@@ -0,0 +1,275 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        x11_init.c

+// Platform:    X11 (Unix)

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

+

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

+//****                  GLFW internal functions                       ****

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

+

+//========================================================================

+// Initialize GLFW thread package

+//========================================================================

+

+static void _glfwInitThreads( void )

+{

+    // Initialize critical section handle

+#ifdef _GLFW_HAS_PTHREAD

+    (void) pthread_mutex_init( &_glfwThrd.CriticalSection, NULL );

+#endif

+

+    // The first thread (the main thread) has ID 0

+    _glfwThrd.NextID = 0;

+

+    // Fill out information about the main thread (this thread)

+    _glfwThrd.First.ID       = _glfwThrd.NextID++;

+    _glfwThrd.First.Function = NULL;

+    _glfwThrd.First.Previous = NULL;

+    _glfwThrd.First.Next     = NULL;

+#ifdef _GLFW_HAS_PTHREAD

+    _glfwThrd.First.PosixID  = pthread_self();

+#endif

+}

+

+

+//========================================================================

+// Terminate GLFW thread package

+//========================================================================

+

+static void _glfwTerminateThreads( void )

+{

+#ifdef _GLFW_HAS_PTHREAD

+

+    _GLFWthread *t, *t_next;

+

+    // Enter critical section

+    ENTER_THREAD_CRITICAL_SECTION

+

+    // Kill all threads (NOTE: THE USER SHOULD WAIT FOR ALL THREADS TO

+    // DIE, _BEFORE_ CALLING glfwTerminate()!!!)

+    t = _glfwThrd.First.Next;

+    while( t != NULL )

+    {

+        // Get pointer to next thread

+        t_next = t->Next;

+

+        // Simply murder the process, no mercy!

+        pthread_kill( t->PosixID, SIGKILL );

+

+        // Free memory allocated for this thread

+        free( (void *) t );

+

+        // Select next thread in list

+        t = t_next;

+    }

+

+    // Leave critical section

+    LEAVE_THREAD_CRITICAL_SECTION

+

+    // Delete critical section handle

+    pthread_mutex_destroy( &_glfwThrd.CriticalSection );

+

+#endif // _GLFW_HAS_PTHREAD

+}

+

+

+//========================================================================

+// Dynamically load libraries

+//========================================================================

+

+#ifdef _GLFW_DLOPEN_LIBGL

+static char * _glfw_libGL_name[ ] =

+{

+    "libGL.so",

+    "libGL.so.1",

+    "/usr/lib/libGL.so",

+    "/usr/lib/libGL.so.1",

+    NULL

+};

+#endif

+

+static void _glfwInitLibraries( void )

+{

+#ifdef _GLFW_DLOPEN_LIBGL

+    int i;

+

+    _glfwLibrary.Libs.libGL = NULL;

+    for( i = 0; !_glfw_libGL_name[ i ] != NULL; i ++ )

+    {

+        _glfwLibrary.Libs.libGL = dlopen( _glfw_libGL_name[ i ],

+                                          RTLD_LAZY | RTLD_GLOBAL );

+	if( _glfwLibrary.Libs.libGL )

+	    break;

+    }

+#endif

+}

+

+

+//========================================================================

+// Terminate GLFW when exiting application

+//========================================================================

+

+void _glfwTerminate_atexit( void )

+{

+    glfwTerminate();

+}

+

+

+//========================================================================

+// Initialize X11 display

+//========================================================================

+

+static int _glfwInitDisplay( void )

+{

+    // Open display

+    _glfwLibrary.Dpy = XOpenDisplay( 0 );

+    if( !_glfwLibrary.Dpy )

+    {

+        return GL_FALSE;

+    }

+

+    // Check screens

+    _glfwLibrary.NumScreens = ScreenCount( _glfwLibrary.Dpy );

+    _glfwLibrary.DefaultScreen = DefaultScreen( _glfwLibrary.Dpy );

+

+    // Check for XF86VidMode extension

+#ifdef _GLFW_HAS_XF86VIDMODE

+    _glfwLibrary.XF86VidMode.Available =

+        XF86VidModeQueryExtension( _glfwLibrary.Dpy,

+	                           &_glfwLibrary.XF86VidMode.EventBase,

+	                           &_glfwLibrary.XF86VidMode.ErrorBase);

+#else

+    _glfwLibrary.XF86VidMode.Available = 0;

+#endif

+

+    // Check for XRandR extension

+#ifdef _GLFW_HAS_XRANDR

+    _glfwLibrary.XRandR.Available =

+        XRRQueryExtension( _glfwLibrary.Dpy,

+	                   &_glfwLibrary.XRandR.EventBase,

+			   &_glfwLibrary.XRandR.ErrorBase );

+#else

+    _glfwLibrary.XRandR.Available = 0;

+#endif

+

+     return GL_TRUE;

+}

+

+

+//========================================================================

+// Terminate X11 display

+//========================================================================

+

+static void _glfwTerminateDisplay( void )

+{

+    // Open display

+    if( _glfwLibrary.Dpy )

+    {

+        XCloseDisplay( _glfwLibrary.Dpy );

+        _glfwLibrary.Dpy = NULL;

+    }

+}

+

+

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

+//****               Platform implementation functions                ****

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

+

+//========================================================================

+// Initialize various GLFW state

+//========================================================================

+

+int _glfwPlatformInit( void )

+{

+    // Initialize display

+    if( !_glfwInitDisplay() )

+    {

+        return GL_FALSE;

+    }

+

+    // Initialize thread package

+    _glfwInitThreads();

+

+    // Try to load libGL.so if necessary

+    _glfwInitLibraries();

+

+    // Install atexit() routine

+    atexit( _glfwTerminate_atexit );

+

+    // Initialize joysticks

+    _glfwInitJoysticks();

+

+    // Start the timer

+    _glfwInitTimer();

+

+    return GL_TRUE;

+}

+

+

+//========================================================================

+// Close window and kill all threads

+//========================================================================

+

+int _glfwPlatformTerminate( void )

+{

+#ifdef _GLFW_HAS_PTHREAD

+    // Only the main thread is allowed to do this...

+    if( pthread_self() != _glfwThrd.First.PosixID )

+    {

+        return GL_FALSE;

+    }

+#endif // _GLFW_HAS_PTHREAD

+

+    // Close OpenGL window

+    glfwCloseWindow();

+

+    // Kill thread package

+    _glfwTerminateThreads();

+

+    // Terminate display

+    _glfwTerminateDisplay();

+

+    // Terminate joysticks

+    _glfwTerminateJoysticks();

+

+    // Unload libGL.so if necessary

+#ifdef _GLFW_DLOPEN_LIBGL

+    if( _glfwLibrary.Libs.libGL != NULL )

+    {

+        dlclose( _glfwLibrary.Libs.libGL );

+        _glfwLibrary.Libs.libGL = NULL;

+    }

+#endif

+

+    return GL_TRUE;

+}

+

diff --git a/src/engine/external/glfw/lib/x11/x11_joystick.c b/src/engine/external/glfw/lib/x11/x11_joystick.c
new file mode 100644
index 00000000..26d67d8c
--- /dev/null
+++ b/src/engine/external/glfw/lib/x11/x11_joystick.c
@@ -0,0 +1,371 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        x11_joystick.c

+// Platform:    X11 (Unix)

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

+//========================================================================

+// Note: Only Linux joystick input is supported at the moment. Other

+// systems will behave as if there are no joysticks connected.

+//========================================================================

+

+#ifdef linux

+#define _GLFW_USE_LINUX_JOYSTICKS

+#endif // linux

+

+

+

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

+//****                  GLFW internal functions                       ****

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

+

+#ifdef _GLFW_USE_LINUX_JOYSTICKS

+

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

+// Here are the Linux joystick driver v1.x interface definitions that we

+// use (we do not want to rely on <linux/joystick.h>):

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

+

+#include <sys/ioctl.h>

+#include <fcntl.h>

+#include <errno.h>

+

+// Joystick event types

+#define JS_EVENT_BUTTON     0x01    /* button pressed/released */

+#define JS_EVENT_AXIS       0x02    /* joystick moved */

+#define JS_EVENT_INIT       0x80    /* initial state of device */

+

+// Joystick event structure

+struct js_event {

+    unsigned int  time;    /* (u32) event timestamp in milliseconds */

+    signed short  value;   /* (s16) value */

+    unsigned char type;    /* (u8)  event type */

+    unsigned char number;  /* (u8)  axis/button number */

+};

+

+// Joystick IOCTL commands

+#define JSIOCGVERSION  _IOR('j', 0x01, int)   /* get driver version (u32) */

+#define JSIOCGAXES     _IOR('j', 0x11, char)  /* get number of axes (u8) */

+#define JSIOCGBUTTONS  _IOR('j', 0x12, char)  /* get number of buttons (u8) */

+

+#endif // _GLFW_USE_LINUX_JOYSTICKS

+

+

+//========================================================================

+// _glfwInitJoysticks() - Initialize joystick interface

+//========================================================================

+

+void _glfwInitJoysticks( void )

+{

+#ifdef _GLFW_USE_LINUX_JOYSTICKS

+    int  k, n, fd, joy_count;

+    char *joy_base_name, joy_dev_name[ 20 ];

+    int  driver_version = 0x000800;

+    char ret_data;

+#endif // _GLFW_USE_LINUX_JOYSTICKS

+    int  i;

+

+    // Start by saying that there are no sticks

+    for( i = 0; i <= GLFW_JOYSTICK_LAST; ++ i )

+    {

+        _glfwJoy[ i ].Present = GL_FALSE;

+    }

+

+#ifdef _GLFW_USE_LINUX_JOYSTICKS

+

+    // Try to open joysticks (nonblocking)

+    joy_count = 0;

+    for( k = 0; k <= 1 && joy_count <= GLFW_JOYSTICK_LAST; ++ k )

+    {

+        // Pick joystick base name

+        switch( k )

+        {

+        case 0:

+            joy_base_name = "/dev/input/js";  // USB sticks

+            break;

+        case 1:

+            joy_base_name = "/dev/js";        // "Legacy" sticks

+            break;

+        default:

+            continue;                         // (should never happen)

+        }

+

+        // Try to open a few of these sticks

+        for( i = 0; i <= 50 && joy_count <= GLFW_JOYSTICK_LAST; ++ i )

+        {

+            sprintf( joy_dev_name, "%s%d", joy_base_name, i );

+            fd = open( joy_dev_name, O_NONBLOCK );

+            if( fd != -1 )

+            {

+                // Remember fd

+                _glfwJoy[ joy_count ].fd = fd;

+    

+                // Check that the joystick driver version is 1.0+

+                ioctl( fd, JSIOCGVERSION, &driver_version );

+                if( driver_version < 0x010000 )

+                {

+                    // It's an old 0.x interface (we don't support it)

+                    close( fd );

+                    continue;

+                }

+    

+                // Get number of joystick axes

+                ioctl( fd, JSIOCGAXES, &ret_data );

+                _glfwJoy[ joy_count ].NumAxes = (int) ret_data;

+    

+                // Get number of joystick buttons

+                ioctl( fd, JSIOCGBUTTONS, &ret_data );

+                _glfwJoy[ joy_count ].NumButtons = (int) ret_data;

+    

+                // Allocate memory for joystick state

+                _glfwJoy[ joy_count ].Axis =

+                    (float *) malloc( sizeof(float) *

+                                      _glfwJoy[ joy_count ].NumAxes );

+                if( _glfwJoy[ joy_count ].Axis == NULL )

+                {

+                    close( fd );

+                    continue;

+                }

+                _glfwJoy[ joy_count ].Button =

+                    (char *) malloc( sizeof(char) *

+                                     _glfwJoy[ joy_count ].NumButtons );

+                if( _glfwJoy[ joy_count ].Button == NULL )

+                {

+                    free( _glfwJoy[ joy_count ].Axis );

+                    close( fd );

+                    continue;

+                }

+

+                // Clear joystick state

+                for( n = 0; n < _glfwJoy[ joy_count ].NumAxes; ++ n )

+                {

+                    _glfwJoy[ joy_count ].Axis[ n ] = 0.0f;

+                }

+                for( n = 0; n < _glfwJoy[ joy_count ].NumButtons; ++ n )

+                {

+                    _glfwJoy[ joy_count ].Button[ n ] = GLFW_RELEASE;

+                }

+    

+                // The joystick is supported and connected

+                _glfwJoy[ joy_count ].Present = GL_TRUE;

+                joy_count ++;

+            }

+        }

+    }

+

+#endif // _GLFW_USE_LINUX_JOYSTICKS

+

+}

+

+

+//========================================================================

+// _glfwTerminateJoysticks() - Close all opened joystick handles

+//========================================================================

+

+void _glfwTerminateJoysticks( void )

+{

+

+#ifdef _GLFW_USE_LINUX_JOYSTICKS

+

+    int i;

+

+    // Close any opened joysticks

+    for( i = 0; i <= GLFW_JOYSTICK_LAST; ++ i )

+    {

+        if( _glfwJoy[ i ].Present )

+        {

+            close( _glfwJoy[ i ].fd );

+            free( _glfwJoy[ i ].Axis );

+            free( _glfwJoy[ i ].Button );

+            _glfwJoy[ i ].Present = GL_FALSE;

+        }

+    }

+

+#endif // _GLFW_USE_LINUX_JOYSTICKS

+

+}

+

+

+//========================================================================

+// _glfwPollJoystickEvents() - Empty joystick event queue

+//========================================================================

+

+static void _glfwPollJoystickEvents( void )

+{

+

+#ifdef _GLFW_USE_LINUX_JOYSTICKS

+

+    struct js_event e;

+    int    i;

+

+    // Get joystick events for all GLFW joysticks

+    for( i = 0; i <= GLFW_JOYSTICK_LAST; ++ i )

+    {

+        // Is the stick present?

+        if( _glfwJoy[ i ].Present )

+        {

+            // Read all queued events (non-blocking)

+            while( read(_glfwJoy[i].fd, &e, sizeof(struct js_event)) > 0 )

+            {

+                // We don't care if it's an init event or not

+                e.type &= ~JS_EVENT_INIT;

+

+                // Check event type

+                switch( e.type )

+                {

+                case JS_EVENT_AXIS:

+                    _glfwJoy[ i ].Axis[ e.number ] = (float) e.value /

+                                                             32767.0f;

+                    // We need to change the sign for the Y axes, so that

+                    // positive = up/forward, according to the GLFW spec.

+                    if( e.number & 1 )

+                    {

+                        _glfwJoy[ i ].Axis[ e.number ] =

+                            -_glfwJoy[ i ].Axis[ e.number ];

+                    }

+                    break;

+

+                case JS_EVENT_BUTTON:

+                    _glfwJoy[ i ].Button[ e.number ] =

+                        e.value ? GLFW_PRESS : GLFW_RELEASE;

+                    break;

+

+                default:

+                    break;

+                }

+            }

+        }

+    }

+

+#endif // _GLFW_USE_LINUX_JOYSTICKS

+

+}

+

+

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

+//****               Platform implementation functions                ****

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

+

+//========================================================================

+// _glfwPlatformGetJoystickParam() - Determine joystick capabilities

+//========================================================================

+

+int _glfwPlatformGetJoystickParam( int joy, int param )

+{

+    // Is joystick present?

+    if( !_glfwJoy[ joy ].Present )

+    {

+        return 0;

+    }

+

+    switch( param )

+    {

+    case GLFW_PRESENT:

+        return GL_TRUE;

+

+    case GLFW_AXES:

+        return _glfwJoy[ joy ].NumAxes;

+

+    case GLFW_BUTTONS:

+        return _glfwJoy[ joy ].NumButtons;

+

+    default:

+        break;

+    }

+

+    return 0;

+}

+

+

+//========================================================================

+// _glfwPlatformGetJoystickPos() - Get joystick axis positions

+//========================================================================

+

+int _glfwPlatformGetJoystickPos( int joy, float *pos, int numaxes )

+{

+    int       i;

+

+    // Is joystick present?

+    if( !_glfwJoy[ joy ].Present )

+    {

+        return 0;

+    }

+

+    // Update joystick state

+    _glfwPollJoystickEvents();

+

+    // Does the joystick support less axes than requested?

+    if( _glfwJoy[ joy ].NumAxes < numaxes )

+    {

+        numaxes = _glfwJoy[ joy ].NumAxes;

+    }

+

+    // Copy axis positions from internal state

+    for( i = 0; i < numaxes; ++ i )

+    {

+        pos[ i ] = _glfwJoy[ joy ].Axis[ i ];

+    }

+

+    return numaxes;

+}

+

+

+//========================================================================

+// _glfwPlatformGetJoystickButtons() - Get joystick button states

+//========================================================================

+

+int _glfwPlatformGetJoystickButtons( int joy, unsigned char *buttons,

+    int numbuttons )

+{

+    int       i;

+

+    // Is joystick present?

+    if( !_glfwJoy[ joy ].Present )

+    {

+        return 0;

+    }

+

+    // Update joystick state

+    _glfwPollJoystickEvents();

+

+    // Does the joystick support less buttons than requested?

+    if( _glfwJoy[ joy ].NumButtons < numbuttons )

+    {

+        numbuttons = _glfwJoy[ joy ].NumButtons;

+    }

+

+    // Copy button states from internal state

+    for( i = 0; i < numbuttons; ++ i )

+    {

+        buttons[ i ] = _glfwJoy[ joy ].Button[ i ];

+    }

+

+    return numbuttons;

+}

diff --git a/src/engine/external/glfw/lib/x11/x11_keysym2unicode.c b/src/engine/external/glfw/lib/x11/x11_keysym2unicode.c
new file mode 100644
index 00000000..6a308734
--- /dev/null
+++ b/src/engine/external/glfw/lib/x11/x11_keysym2unicode.c
@@ -0,0 +1,902 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        x11_keysym2unicode.c

+// Platform:    X11 (Unix)

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

+/*

+ * Marcus: This code was originally written by Markus G. Kuhn.

+ * I have made some slight changes (trimmed it down a bit from >60 KB to

+ * 20 KB), but the functionality is the same.

+ */

+

+/*

+ * This module converts keysym values into the corresponding ISO 10646

+ * (UCS, Unicode) values.

+ *

+ * The array keysymtab[] contains pairs of X11 keysym values for graphical

+ * characters and the corresponding Unicode value. The function

+ * _glfwKeySym2Unicode() maps a keysym onto a Unicode value using a binary

+ * search, therefore keysymtab[] must remain SORTED by keysym value.

+ *

+ * We allow to represent any UCS character in the range U-00000000 to

+ * U-00FFFFFF by a keysym value in the range 0x01000000 to 0x01ffffff.

+ * This admittedly does not cover the entire 31-bit space of UCS, but

+ * it does cover all of the characters up to U-10FFFF, which can be

+ * represented by UTF-16, and more, and it is very unlikely that higher

+ * UCS codes will ever be assigned by ISO. So to get Unicode character

+ * U+ABCD you can directly use keysym 0x0100abcd.

+ *

+ * Original author: Markus G. Kuhn <mkuhn@acm.org>, University of

+ *                  Cambridge, April 2001

+ *

+ * Special thanks to Richard Verhoeven <river@win.tue.nl> for preparing

+ * an initial draft of the mapping table.

+ *

+ */

+

+

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

+//****                KeySym to Unicode mapping table                 ****

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

+

+static struct codepair {

+  unsigned short keysym;

+  unsigned short ucs;

+} keysymtab[] = {

+  { 0x01a1, 0x0104 },

+  { 0x01a2, 0x02d8 },

+  { 0x01a3, 0x0141 },

+  { 0x01a5, 0x013d },

+  { 0x01a6, 0x015a },

+  { 0x01a9, 0x0160 },

+  { 0x01aa, 0x015e },

+  { 0x01ab, 0x0164 },

+  { 0x01ac, 0x0179 },

+  { 0x01ae, 0x017d },

+  { 0x01af, 0x017b },

+  { 0x01b1, 0x0105 },

+  { 0x01b2, 0x02db },

+  { 0x01b3, 0x0142 },

+  { 0x01b5, 0x013e },

+  { 0x01b6, 0x015b },

+  { 0x01b7, 0x02c7 },

+  { 0x01b9, 0x0161 },

+  { 0x01ba, 0x015f },

+  { 0x01bb, 0x0165 },

+  { 0x01bc, 0x017a },

+  { 0x01bd, 0x02dd },

+  { 0x01be, 0x017e },

+  { 0x01bf, 0x017c },

+  { 0x01c0, 0x0154 },

+  { 0x01c3, 0x0102 },

+  { 0x01c5, 0x0139 },

+  { 0x01c6, 0x0106 },

+  { 0x01c8, 0x010c },

+  { 0x01ca, 0x0118 },

+  { 0x01cc, 0x011a },

+  { 0x01cf, 0x010e },

+  { 0x01d0, 0x0110 },

+  { 0x01d1, 0x0143 },

+  { 0x01d2, 0x0147 },

+  { 0x01d5, 0x0150 },

+  { 0x01d8, 0x0158 },

+  { 0x01d9, 0x016e },

+  { 0x01db, 0x0170 },

+  { 0x01de, 0x0162 },

+  { 0x01e0, 0x0155 },

+  { 0x01e3, 0x0103 },

+  { 0x01e5, 0x013a },

+  { 0x01e6, 0x0107 },

+  { 0x01e8, 0x010d },

+  { 0x01ea, 0x0119 },

+  { 0x01ec, 0x011b },

+  { 0x01ef, 0x010f },

+  { 0x01f0, 0x0111 },

+  { 0x01f1, 0x0144 },

+  { 0x01f2, 0x0148 },

+  { 0x01f5, 0x0151 },

+  { 0x01f8, 0x0159 },

+  { 0x01f9, 0x016f },

+  { 0x01fb, 0x0171 },

+  { 0x01fe, 0x0163 },

+  { 0x01ff, 0x02d9 },

+  { 0x02a1, 0x0126 },

+  { 0x02a6, 0x0124 },

+  { 0x02a9, 0x0130 },

+  { 0x02ab, 0x011e },

+  { 0x02ac, 0x0134 },

+  { 0x02b1, 0x0127 },

+  { 0x02b6, 0x0125 },

+  { 0x02b9, 0x0131 },

+  { 0x02bb, 0x011f },

+  { 0x02bc, 0x0135 },

+  { 0x02c5, 0x010a },

+  { 0x02c6, 0x0108 },

+  { 0x02d5, 0x0120 },

+  { 0x02d8, 0x011c },

+  { 0x02dd, 0x016c },

+  { 0x02de, 0x015c },

+  { 0x02e5, 0x010b },

+  { 0x02e6, 0x0109 },

+  { 0x02f5, 0x0121 },

+  { 0x02f8, 0x011d },

+  { 0x02fd, 0x016d },

+  { 0x02fe, 0x015d },

+  { 0x03a2, 0x0138 },

+  { 0x03a3, 0x0156 },

+  { 0x03a5, 0x0128 },

+  { 0x03a6, 0x013b },

+  { 0x03aa, 0x0112 },

+  { 0x03ab, 0x0122 },

+  { 0x03ac, 0x0166 },

+  { 0x03b3, 0x0157 },

+  { 0x03b5, 0x0129 },

+  { 0x03b6, 0x013c },

+  { 0x03ba, 0x0113 },

+  { 0x03bb, 0x0123 },

+  { 0x03bc, 0x0167 },

+  { 0x03bd, 0x014a },

+  { 0x03bf, 0x014b },

+  { 0x03c0, 0x0100 },

+  { 0x03c7, 0x012e },

+  { 0x03cc, 0x0116 },

+  { 0x03cf, 0x012a },

+  { 0x03d1, 0x0145 },

+  { 0x03d2, 0x014c },

+  { 0x03d3, 0x0136 },

+  { 0x03d9, 0x0172 },

+  { 0x03dd, 0x0168 },

+  { 0x03de, 0x016a },

+  { 0x03e0, 0x0101 },

+  { 0x03e7, 0x012f },

+  { 0x03ec, 0x0117 },

+  { 0x03ef, 0x012b },

+  { 0x03f1, 0x0146 },

+  { 0x03f2, 0x014d },

+  { 0x03f3, 0x0137 },

+  { 0x03f9, 0x0173 },

+  { 0x03fd, 0x0169 },

+  { 0x03fe, 0x016b },

+  { 0x047e, 0x203e },

+  { 0x04a1, 0x3002 },

+  { 0x04a2, 0x300c },

+  { 0x04a3, 0x300d },

+  { 0x04a4, 0x3001 },

+  { 0x04a5, 0x30fb },

+  { 0x04a6, 0x30f2 },

+  { 0x04a7, 0x30a1 },

+  { 0x04a8, 0x30a3 },

+  { 0x04a9, 0x30a5 },

+  { 0x04aa, 0x30a7 },

+  { 0x04ab, 0x30a9 },

+  { 0x04ac, 0x30e3 },

+  { 0x04ad, 0x30e5 },

+  { 0x04ae, 0x30e7 },

+  { 0x04af, 0x30c3 },

+  { 0x04b0, 0x30fc },

+  { 0x04b1, 0x30a2 },

+  { 0x04b2, 0x30a4 },

+  { 0x04b3, 0x30a6 },

+  { 0x04b4, 0x30a8 },

+  { 0x04b5, 0x30aa },

+  { 0x04b6, 0x30ab },

+  { 0x04b7, 0x30ad },

+  { 0x04b8, 0x30af },

+  { 0x04b9, 0x30b1 },

+  { 0x04ba, 0x30b3 },

+  { 0x04bb, 0x30b5 },

+  { 0x04bc, 0x30b7 },

+  { 0x04bd, 0x30b9 },

+  { 0x04be, 0x30bb },

+  { 0x04bf, 0x30bd },

+  { 0x04c0, 0x30bf },

+  { 0x04c1, 0x30c1 },

+  { 0x04c2, 0x30c4 },

+  { 0x04c3, 0x30c6 },

+  { 0x04c4, 0x30c8 },

+  { 0x04c5, 0x30ca },

+  { 0x04c6, 0x30cb },

+  { 0x04c7, 0x30cc },

+  { 0x04c8, 0x30cd },

+  { 0x04c9, 0x30ce },

+  { 0x04ca, 0x30cf },

+  { 0x04cb, 0x30d2 },

+  { 0x04cc, 0x30d5 },

+  { 0x04cd, 0x30d8 },

+  { 0x04ce, 0x30db },

+  { 0x04cf, 0x30de },

+  { 0x04d0, 0x30df },

+  { 0x04d1, 0x30e0 },

+  { 0x04d2, 0x30e1 },

+  { 0x04d3, 0x30e2 },

+  { 0x04d4, 0x30e4 },

+  { 0x04d5, 0x30e6 },

+  { 0x04d6, 0x30e8 },

+  { 0x04d7, 0x30e9 },

+  { 0x04d8, 0x30ea },

+  { 0x04d9, 0x30eb },

+  { 0x04da, 0x30ec },

+  { 0x04db, 0x30ed },

+  { 0x04dc, 0x30ef },

+  { 0x04dd, 0x30f3 },

+  { 0x04de, 0x309b },

+  { 0x04df, 0x309c },

+  { 0x05ac, 0x060c },

+  { 0x05bb, 0x061b },

+  { 0x05bf, 0x061f },

+  { 0x05c1, 0x0621 },

+  { 0x05c2, 0x0622 },

+  { 0x05c3, 0x0623 },

+  { 0x05c4, 0x0624 },

+  { 0x05c5, 0x0625 },

+  { 0x05c6, 0x0626 },

+  { 0x05c7, 0x0627 },

+  { 0x05c8, 0x0628 },

+  { 0x05c9, 0x0629 },

+  { 0x05ca, 0x062a },

+  { 0x05cb, 0x062b },

+  { 0x05cc, 0x062c },

+  { 0x05cd, 0x062d },

+  { 0x05ce, 0x062e },

+  { 0x05cf, 0x062f },

+  { 0x05d0, 0x0630 },

+  { 0x05d1, 0x0631 },

+  { 0x05d2, 0x0632 },

+  { 0x05d3, 0x0633 },

+  { 0x05d4, 0x0634 },

+  { 0x05d5, 0x0635 },

+  { 0x05d6, 0x0636 },

+  { 0x05d7, 0x0637 },

+  { 0x05d8, 0x0638 },

+  { 0x05d9, 0x0639 },

+  { 0x05da, 0x063a },

+  { 0x05e0, 0x0640 },

+  { 0x05e1, 0x0641 },

+  { 0x05e2, 0x0642 },

+  { 0x05e3, 0x0643 },

+  { 0x05e4, 0x0644 },

+  { 0x05e5, 0x0645 },

+  { 0x05e6, 0x0646 },

+  { 0x05e7, 0x0647 },

+  { 0x05e8, 0x0648 },

+  { 0x05e9, 0x0649 },

+  { 0x05ea, 0x064a },

+  { 0x05eb, 0x064b },

+  { 0x05ec, 0x064c },

+  { 0x05ed, 0x064d },

+  { 0x05ee, 0x064e },

+  { 0x05ef, 0x064f },

+  { 0x05f0, 0x0650 },

+  { 0x05f1, 0x0651 },

+  { 0x05f2, 0x0652 },

+  { 0x06a1, 0x0452 },

+  { 0x06a2, 0x0453 },

+  { 0x06a3, 0x0451 },

+  { 0x06a4, 0x0454 },

+  { 0x06a5, 0x0455 },

+  { 0x06a6, 0x0456 },

+  { 0x06a7, 0x0457 },

+  { 0x06a8, 0x0458 },

+  { 0x06a9, 0x0459 },

+  { 0x06aa, 0x045a },

+  { 0x06ab, 0x045b },

+  { 0x06ac, 0x045c },

+  { 0x06ae, 0x045e },

+  { 0x06af, 0x045f },

+  { 0x06b0, 0x2116 },

+  { 0x06b1, 0x0402 },

+  { 0x06b2, 0x0403 },

+  { 0x06b3, 0x0401 },

+  { 0x06b4, 0x0404 },

+  { 0x06b5, 0x0405 },

+  { 0x06b6, 0x0406 },

+  { 0x06b7, 0x0407 },

+  { 0x06b8, 0x0408 },

+  { 0x06b9, 0x0409 },

+  { 0x06ba, 0x040a },

+  { 0x06bb, 0x040b },

+  { 0x06bc, 0x040c },

+  { 0x06be, 0x040e },

+  { 0x06bf, 0x040f },

+  { 0x06c0, 0x044e },

+  { 0x06c1, 0x0430 },

+  { 0x06c2, 0x0431 },

+  { 0x06c3, 0x0446 },

+  { 0x06c4, 0x0434 },

+  { 0x06c5, 0x0435 },

+  { 0x06c6, 0x0444 },

+  { 0x06c7, 0x0433 },

+  { 0x06c8, 0x0445 },

+  { 0x06c9, 0x0438 },

+  { 0x06ca, 0x0439 },

+  { 0x06cb, 0x043a },

+  { 0x06cc, 0x043b },

+  { 0x06cd, 0x043c },

+  { 0x06ce, 0x043d },

+  { 0x06cf, 0x043e },

+  { 0x06d0, 0x043f },

+  { 0x06d1, 0x044f },

+  { 0x06d2, 0x0440 },

+  { 0x06d3, 0x0441 },

+  { 0x06d4, 0x0442 },

+  { 0x06d5, 0x0443 },

+  { 0x06d6, 0x0436 },

+  { 0x06d7, 0x0432 },

+  { 0x06d8, 0x044c },

+  { 0x06d9, 0x044b },

+  { 0x06da, 0x0437 },

+  { 0x06db, 0x0448 },

+  { 0x06dc, 0x044d },

+  { 0x06dd, 0x0449 },

+  { 0x06de, 0x0447 },

+  { 0x06df, 0x044a },

+  { 0x06e0, 0x042e },

+  { 0x06e1, 0x0410 },

+  { 0x06e2, 0x0411 },

+  { 0x06e3, 0x0426 },

+  { 0x06e4, 0x0414 },

+  { 0x06e5, 0x0415 },

+  { 0x06e6, 0x0424 },

+  { 0x06e7, 0x0413 },

+  { 0x06e8, 0x0425 },

+  { 0x06e9, 0x0418 },

+  { 0x06ea, 0x0419 },

+  { 0x06eb, 0x041a },

+  { 0x06ec, 0x041b },

+  { 0x06ed, 0x041c },

+  { 0x06ee, 0x041d },

+  { 0x06ef, 0x041e },

+  { 0x06f0, 0x041f },

+  { 0x06f1, 0x042f },

+  { 0x06f2, 0x0420 },

+  { 0x06f3, 0x0421 },

+  { 0x06f4, 0x0422 },

+  { 0x06f5, 0x0423 },

+  { 0x06f6, 0x0416 },

+  { 0x06f7, 0x0412 },

+  { 0x06f8, 0x042c },

+  { 0x06f9, 0x042b },

+  { 0x06fa, 0x0417 },

+  { 0x06fb, 0x0428 },

+  { 0x06fc, 0x042d },

+  { 0x06fd, 0x0429 },

+  { 0x06fe, 0x0427 },

+  { 0x06ff, 0x042a },

+  { 0x07a1, 0x0386 },

+  { 0x07a2, 0x0388 },

+  { 0x07a3, 0x0389 },

+  { 0x07a4, 0x038a },

+  { 0x07a5, 0x03aa },

+  { 0x07a7, 0x038c },

+  { 0x07a8, 0x038e },

+  { 0x07a9, 0x03ab },

+  { 0x07ab, 0x038f },

+  { 0x07ae, 0x0385 },

+  { 0x07af, 0x2015 },

+  { 0x07b1, 0x03ac },

+  { 0x07b2, 0x03ad },

+  { 0x07b3, 0x03ae },

+  { 0x07b4, 0x03af },

+  { 0x07b5, 0x03ca },

+  { 0x07b6, 0x0390 },

+  { 0x07b7, 0x03cc },

+  { 0x07b8, 0x03cd },

+  { 0x07b9, 0x03cb },

+  { 0x07ba, 0x03b0 },

+  { 0x07bb, 0x03ce },

+  { 0x07c1, 0x0391 },

+  { 0x07c2, 0x0392 },

+  { 0x07c3, 0x0393 },

+  { 0x07c4, 0x0394 },

+  { 0x07c5, 0x0395 },

+  { 0x07c6, 0x0396 },

+  { 0x07c7, 0x0397 },

+  { 0x07c8, 0x0398 },

+  { 0x07c9, 0x0399 },

+  { 0x07ca, 0x039a },

+  { 0x07cb, 0x039b },

+  { 0x07cc, 0x039c },

+  { 0x07cd, 0x039d },

+  { 0x07ce, 0x039e },

+  { 0x07cf, 0x039f },

+  { 0x07d0, 0x03a0 },

+  { 0x07d1, 0x03a1 },

+  { 0x07d2, 0x03a3 },

+  { 0x07d4, 0x03a4 },

+  { 0x07d5, 0x03a5 },

+  { 0x07d6, 0x03a6 },

+  { 0x07d7, 0x03a7 },

+  { 0x07d8, 0x03a8 },

+  { 0x07d9, 0x03a9 },

+  { 0x07e1, 0x03b1 },

+  { 0x07e2, 0x03b2 },

+  { 0x07e3, 0x03b3 },

+  { 0x07e4, 0x03b4 },

+  { 0x07e5, 0x03b5 },

+  { 0x07e6, 0x03b6 },

+  { 0x07e7, 0x03b7 },

+  { 0x07e8, 0x03b8 },

+  { 0x07e9, 0x03b9 },

+  { 0x07ea, 0x03ba },

+  { 0x07eb, 0x03bb },

+  { 0x07ec, 0x03bc },

+  { 0x07ed, 0x03bd },

+  { 0x07ee, 0x03be },

+  { 0x07ef, 0x03bf },

+  { 0x07f0, 0x03c0 },

+  { 0x07f1, 0x03c1 },

+  { 0x07f2, 0x03c3 },

+  { 0x07f3, 0x03c2 },

+  { 0x07f4, 0x03c4 },

+  { 0x07f5, 0x03c5 },

+  { 0x07f6, 0x03c6 },

+  { 0x07f7, 0x03c7 },

+  { 0x07f8, 0x03c8 },

+  { 0x07f9, 0x03c9 },

+  { 0x08a1, 0x23b7 },

+  { 0x08a2, 0x250c },

+  { 0x08a3, 0x2500 },

+  { 0x08a4, 0x2320 },

+  { 0x08a5, 0x2321 },

+  { 0x08a6, 0x2502 },

+  { 0x08a7, 0x23a1 },

+  { 0x08a8, 0x23a3 },

+  { 0x08a9, 0x23a4 },

+  { 0x08aa, 0x23a6 },

+  { 0x08ab, 0x239b },

+  { 0x08ac, 0x239d },

+  { 0x08ad, 0x239e },

+  { 0x08ae, 0x23a0 },

+  { 0x08af, 0x23a8 },

+  { 0x08b0, 0x23ac },

+  { 0x08bc, 0x2264 },

+  { 0x08bd, 0x2260 },

+  { 0x08be, 0x2265 },

+  { 0x08bf, 0x222b },

+  { 0x08c0, 0x2234 },

+  { 0x08c1, 0x221d },

+  { 0x08c2, 0x221e },

+  { 0x08c5, 0x2207 },

+  { 0x08c8, 0x223c },

+  { 0x08c9, 0x2243 },

+  { 0x08cd, 0x21d4 },

+  { 0x08ce, 0x21d2 },

+  { 0x08cf, 0x2261 },

+  { 0x08d6, 0x221a },

+  { 0x08da, 0x2282 },

+  { 0x08db, 0x2283 },

+  { 0x08dc, 0x2229 },

+  { 0x08dd, 0x222a },

+  { 0x08de, 0x2227 },

+  { 0x08df, 0x2228 },

+  { 0x08ef, 0x2202 },

+  { 0x08f6, 0x0192 },

+  { 0x08fb, 0x2190 },

+  { 0x08fc, 0x2191 },

+  { 0x08fd, 0x2192 },

+  { 0x08fe, 0x2193 },

+  { 0x09e0, 0x25c6 },

+  { 0x09e1, 0x2592 },

+  { 0x09e2, 0x2409 },

+  { 0x09e3, 0x240c },

+  { 0x09e4, 0x240d },

+  { 0x09e5, 0x240a },

+  { 0x09e8, 0x2424 },

+  { 0x09e9, 0x240b },

+  { 0x09ea, 0x2518 },

+  { 0x09eb, 0x2510 },

+  { 0x09ec, 0x250c },

+  { 0x09ed, 0x2514 },

+  { 0x09ee, 0x253c },

+  { 0x09ef, 0x23ba },

+  { 0x09f0, 0x23bb },

+  { 0x09f1, 0x2500 },

+  { 0x09f2, 0x23bc },

+  { 0x09f3, 0x23bd },

+  { 0x09f4, 0x251c },

+  { 0x09f5, 0x2524 },

+  { 0x09f6, 0x2534 },

+  { 0x09f7, 0x252c },

+  { 0x09f8, 0x2502 },

+  { 0x0aa1, 0x2003 },

+  { 0x0aa2, 0x2002 },

+  { 0x0aa3, 0x2004 },

+  { 0x0aa4, 0x2005 },

+  { 0x0aa5, 0x2007 },

+  { 0x0aa6, 0x2008 },

+  { 0x0aa7, 0x2009 },

+  { 0x0aa8, 0x200a },

+  { 0x0aa9, 0x2014 },

+  { 0x0aaa, 0x2013 },

+  { 0x0aae, 0x2026 },

+  { 0x0aaf, 0x2025 },

+  { 0x0ab0, 0x2153 },

+  { 0x0ab1, 0x2154 },

+  { 0x0ab2, 0x2155 },

+  { 0x0ab3, 0x2156 },

+  { 0x0ab4, 0x2157 },

+  { 0x0ab5, 0x2158 },

+  { 0x0ab6, 0x2159 },

+  { 0x0ab7, 0x215a },

+  { 0x0ab8, 0x2105 },

+  { 0x0abb, 0x2012 },

+  { 0x0abc, 0x2329 },

+  { 0x0abe, 0x232a },

+  { 0x0ac3, 0x215b },

+  { 0x0ac4, 0x215c },

+  { 0x0ac5, 0x215d },

+  { 0x0ac6, 0x215e },

+  { 0x0ac9, 0x2122 },

+  { 0x0aca, 0x2613 },

+  { 0x0acc, 0x25c1 },

+  { 0x0acd, 0x25b7 },

+  { 0x0ace, 0x25cb },

+  { 0x0acf, 0x25af },

+  { 0x0ad0, 0x2018 },

+  { 0x0ad1, 0x2019 },

+  { 0x0ad2, 0x201c },

+  { 0x0ad3, 0x201d },

+  { 0x0ad4, 0x211e },

+  { 0x0ad6, 0x2032 },

+  { 0x0ad7, 0x2033 },

+  { 0x0ad9, 0x271d },

+  { 0x0adb, 0x25ac },

+  { 0x0adc, 0x25c0 },

+  { 0x0add, 0x25b6 },

+  { 0x0ade, 0x25cf },

+  { 0x0adf, 0x25ae },

+  { 0x0ae0, 0x25e6 },

+  { 0x0ae1, 0x25ab },

+  { 0x0ae2, 0x25ad },

+  { 0x0ae3, 0x25b3 },

+  { 0x0ae4, 0x25bd },

+  { 0x0ae5, 0x2606 },

+  { 0x0ae6, 0x2022 },

+  { 0x0ae7, 0x25aa },

+  { 0x0ae8, 0x25b2 },

+  { 0x0ae9, 0x25bc },

+  { 0x0aea, 0x261c },

+  { 0x0aeb, 0x261e },

+  { 0x0aec, 0x2663 },

+  { 0x0aed, 0x2666 },

+  { 0x0aee, 0x2665 },

+  { 0x0af0, 0x2720 },

+  { 0x0af1, 0x2020 },

+  { 0x0af2, 0x2021 },

+  { 0x0af3, 0x2713 },

+  { 0x0af4, 0x2717 },

+  { 0x0af5, 0x266f },

+  { 0x0af6, 0x266d },

+  { 0x0af7, 0x2642 },

+  { 0x0af8, 0x2640 },

+  { 0x0af9, 0x260e },

+  { 0x0afa, 0x2315 },

+  { 0x0afb, 0x2117 },

+  { 0x0afc, 0x2038 },

+  { 0x0afd, 0x201a },

+  { 0x0afe, 0x201e },

+  { 0x0ba3, 0x003c },

+  { 0x0ba6, 0x003e },

+  { 0x0ba8, 0x2228 },

+  { 0x0ba9, 0x2227 },

+  { 0x0bc0, 0x00af },

+  { 0x0bc2, 0x22a5 },

+  { 0x0bc3, 0x2229 },

+  { 0x0bc4, 0x230a },

+  { 0x0bc6, 0x005f },

+  { 0x0bca, 0x2218 },

+  { 0x0bcc, 0x2395 },

+  { 0x0bce, 0x22a4 },

+  { 0x0bcf, 0x25cb },

+  { 0x0bd3, 0x2308 },

+  { 0x0bd6, 0x222a },

+  { 0x0bd8, 0x2283 },

+  { 0x0bda, 0x2282 },

+  { 0x0bdc, 0x22a2 },

+  { 0x0bfc, 0x22a3 },

+  { 0x0cdf, 0x2017 },

+  { 0x0ce0, 0x05d0 },

+  { 0x0ce1, 0x05d1 },

+  { 0x0ce2, 0x05d2 },

+  { 0x0ce3, 0x05d3 },

+  { 0x0ce4, 0x05d4 },

+  { 0x0ce5, 0x05d5 },

+  { 0x0ce6, 0x05d6 },

+  { 0x0ce7, 0x05d7 },

+  { 0x0ce8, 0x05d8 },

+  { 0x0ce9, 0x05d9 },

+  { 0x0cea, 0x05da },

+  { 0x0ceb, 0x05db },

+  { 0x0cec, 0x05dc },

+  { 0x0ced, 0x05dd },

+  { 0x0cee, 0x05de },

+  { 0x0cef, 0x05df },

+  { 0x0cf0, 0x05e0 },

+  { 0x0cf1, 0x05e1 },

+  { 0x0cf2, 0x05e2 },

+  { 0x0cf3, 0x05e3 },

+  { 0x0cf4, 0x05e4 },

+  { 0x0cf5, 0x05e5 },

+  { 0x0cf6, 0x05e6 },

+  { 0x0cf7, 0x05e7 },

+  { 0x0cf8, 0x05e8 },

+  { 0x0cf9, 0x05e9 },

+  { 0x0cfa, 0x05ea },

+  { 0x0da1, 0x0e01 },

+  { 0x0da2, 0x0e02 },

+  { 0x0da3, 0x0e03 },

+  { 0x0da4, 0x0e04 },

+  { 0x0da5, 0x0e05 },

+  { 0x0da6, 0x0e06 },

+  { 0x0da7, 0x0e07 },

+  { 0x0da8, 0x0e08 },

+  { 0x0da9, 0x0e09 },

+  { 0x0daa, 0x0e0a },

+  { 0x0dab, 0x0e0b },

+  { 0x0dac, 0x0e0c },

+  { 0x0dad, 0x0e0d },

+  { 0x0dae, 0x0e0e },

+  { 0x0daf, 0x0e0f },

+  { 0x0db0, 0x0e10 },

+  { 0x0db1, 0x0e11 },

+  { 0x0db2, 0x0e12 },

+  { 0x0db3, 0x0e13 },

+  { 0x0db4, 0x0e14 },

+  { 0x0db5, 0x0e15 },

+  { 0x0db6, 0x0e16 },

+  { 0x0db7, 0x0e17 },

+  { 0x0db8, 0x0e18 },

+  { 0x0db9, 0x0e19 },

+  { 0x0dba, 0x0e1a },

+  { 0x0dbb, 0x0e1b },

+  { 0x0dbc, 0x0e1c },

+  { 0x0dbd, 0x0e1d },

+  { 0x0dbe, 0x0e1e },

+  { 0x0dbf, 0x0e1f },

+  { 0x0dc0, 0x0e20 },

+  { 0x0dc1, 0x0e21 },

+  { 0x0dc2, 0x0e22 },

+  { 0x0dc3, 0x0e23 },

+  { 0x0dc4, 0x0e24 },

+  { 0x0dc5, 0x0e25 },

+  { 0x0dc6, 0x0e26 },

+  { 0x0dc7, 0x0e27 },

+  { 0x0dc8, 0x0e28 },

+  { 0x0dc9, 0x0e29 },

+  { 0x0dca, 0x0e2a },

+  { 0x0dcb, 0x0e2b },

+  { 0x0dcc, 0x0e2c },

+  { 0x0dcd, 0x0e2d },

+  { 0x0dce, 0x0e2e },

+  { 0x0dcf, 0x0e2f },

+  { 0x0dd0, 0x0e30 },

+  { 0x0dd1, 0x0e31 },

+  { 0x0dd2, 0x0e32 },

+  { 0x0dd3, 0x0e33 },

+  { 0x0dd4, 0x0e34 },

+  { 0x0dd5, 0x0e35 },

+  { 0x0dd6, 0x0e36 },

+  { 0x0dd7, 0x0e37 },

+  { 0x0dd8, 0x0e38 },

+  { 0x0dd9, 0x0e39 },

+  { 0x0dda, 0x0e3a },

+  { 0x0ddf, 0x0e3f },

+  { 0x0de0, 0x0e40 },

+  { 0x0de1, 0x0e41 },

+  { 0x0de2, 0x0e42 },

+  { 0x0de3, 0x0e43 },

+  { 0x0de4, 0x0e44 },

+  { 0x0de5, 0x0e45 },

+  { 0x0de6, 0x0e46 },

+  { 0x0de7, 0x0e47 },

+  { 0x0de8, 0x0e48 },

+  { 0x0de9, 0x0e49 },

+  { 0x0dea, 0x0e4a },

+  { 0x0deb, 0x0e4b },

+  { 0x0dec, 0x0e4c },

+  { 0x0ded, 0x0e4d },

+  { 0x0df0, 0x0e50 },

+  { 0x0df1, 0x0e51 },

+  { 0x0df2, 0x0e52 },

+  { 0x0df3, 0x0e53 },

+  { 0x0df4, 0x0e54 },

+  { 0x0df5, 0x0e55 },

+  { 0x0df6, 0x0e56 },

+  { 0x0df7, 0x0e57 },

+  { 0x0df8, 0x0e58 },

+  { 0x0df9, 0x0e59 },

+  { 0x0ea1, 0x3131 },

+  { 0x0ea2, 0x3132 },

+  { 0x0ea3, 0x3133 },

+  { 0x0ea4, 0x3134 },

+  { 0x0ea5, 0x3135 },

+  { 0x0ea6, 0x3136 },

+  { 0x0ea7, 0x3137 },

+  { 0x0ea8, 0x3138 },

+  { 0x0ea9, 0x3139 },

+  { 0x0eaa, 0x313a },

+  { 0x0eab, 0x313b },

+  { 0x0eac, 0x313c },

+  { 0x0ead, 0x313d },

+  { 0x0eae, 0x313e },

+  { 0x0eaf, 0x313f },

+  { 0x0eb0, 0x3140 },

+  { 0x0eb1, 0x3141 },

+  { 0x0eb2, 0x3142 },

+  { 0x0eb3, 0x3143 },

+  { 0x0eb4, 0x3144 },

+  { 0x0eb5, 0x3145 },

+  { 0x0eb6, 0x3146 },

+  { 0x0eb7, 0x3147 },

+  { 0x0eb8, 0x3148 },

+  { 0x0eb9, 0x3149 },

+  { 0x0eba, 0x314a },

+  { 0x0ebb, 0x314b },

+  { 0x0ebc, 0x314c },

+  { 0x0ebd, 0x314d },

+  { 0x0ebe, 0x314e },

+  { 0x0ebf, 0x314f },

+  { 0x0ec0, 0x3150 },

+  { 0x0ec1, 0x3151 },

+  { 0x0ec2, 0x3152 },

+  { 0x0ec3, 0x3153 },

+  { 0x0ec4, 0x3154 },

+  { 0x0ec5, 0x3155 },

+  { 0x0ec6, 0x3156 },

+  { 0x0ec7, 0x3157 },

+  { 0x0ec8, 0x3158 },

+  { 0x0ec9, 0x3159 },

+  { 0x0eca, 0x315a },

+  { 0x0ecb, 0x315b },

+  { 0x0ecc, 0x315c },

+  { 0x0ecd, 0x315d },

+  { 0x0ece, 0x315e },

+  { 0x0ecf, 0x315f },

+  { 0x0ed0, 0x3160 },

+  { 0x0ed1, 0x3161 },

+  { 0x0ed2, 0x3162 },

+  { 0x0ed3, 0x3163 },

+  { 0x0ed4, 0x11a8 },

+  { 0x0ed5, 0x11a9 },

+  { 0x0ed6, 0x11aa },

+  { 0x0ed7, 0x11ab },

+  { 0x0ed8, 0x11ac },

+  { 0x0ed9, 0x11ad },

+  { 0x0eda, 0x11ae },

+  { 0x0edb, 0x11af },

+  { 0x0edc, 0x11b0 },

+  { 0x0edd, 0x11b1 },

+  { 0x0ede, 0x11b2 },

+  { 0x0edf, 0x11b3 },

+  { 0x0ee0, 0x11b4 },

+  { 0x0ee1, 0x11b5 },

+  { 0x0ee2, 0x11b6 },

+  { 0x0ee3, 0x11b7 },

+  { 0x0ee4, 0x11b8 },

+  { 0x0ee5, 0x11b9 },

+  { 0x0ee6, 0x11ba },

+  { 0x0ee7, 0x11bb },

+  { 0x0ee8, 0x11bc },

+  { 0x0ee9, 0x11bd },

+  { 0x0eea, 0x11be },

+  { 0x0eeb, 0x11bf },

+  { 0x0eec, 0x11c0 },

+  { 0x0eed, 0x11c1 },

+  { 0x0eee, 0x11c2 },

+  { 0x0eef, 0x316d },

+  { 0x0ef0, 0x3171 },

+  { 0x0ef1, 0x3178 },

+  { 0x0ef2, 0x317f },

+  { 0x0ef3, 0x3181 },

+  { 0x0ef4, 0x3184 },

+  { 0x0ef5, 0x3186 },

+  { 0x0ef6, 0x318d },

+  { 0x0ef7, 0x318e },

+  { 0x0ef8, 0x11eb },

+  { 0x0ef9, 0x11f0 },

+  { 0x0efa, 0x11f9 },

+  { 0x0eff, 0x20a9 },

+  { 0x13a4, 0x20ac },

+  { 0x13bc, 0x0152 },

+  { 0x13bd, 0x0153 },

+  { 0x13be, 0x0178 },

+  { 0x20ac, 0x20ac }, 

+  // Numeric keypad with numlock on 

+  { XK_KP_Space, ' ' },

+  { XK_KP_Equal, '=' },

+  { XK_KP_Multiply, '*' },

+  { XK_KP_Add, '+' },

+  { XK_KP_Separator, ',' },

+  { XK_KP_Subtract, '-' },

+  { XK_KP_Decimal, '.' },

+  { XK_KP_Divide, '/' },

+  { XK_KP_0, 0x0030 }, 

+  { XK_KP_1, 0x0031 }, 

+  { XK_KP_2, 0x0032 }, 

+  { XK_KP_3, 0x0033 }, 

+  { XK_KP_4, 0x0034 }, 

+  { XK_KP_5, 0x0035 }, 

+  { XK_KP_6, 0x0036 }, 

+  { XK_KP_7, 0x0037 }, 

+  { XK_KP_8, 0x0038 }, 

+  { XK_KP_9, 0x0039 } 

+};

+

+

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

+//****                  GLFW internal functions                       ****

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

+

+//========================================================================

+// _glfwKeySym2Unicode() - Convert X11 KeySym to Unicode

+//========================================================================

+

+long _glfwKeySym2Unicode( KeySym keysym )

+{

+    int min = 0;

+    int max = sizeof(keysymtab) / sizeof(struct codepair) - 1;

+    int mid;

+

+    /* First check for Latin-1 characters (1:1 mapping) */

+    if( (keysym >= 0x0020 && keysym <= 0x007e) ||

+        (keysym >= 0x00a0 && keysym <= 0x00ff) )

+    {

+        return keysym;

+    }

+

+    /* Also check for directly encoded 24-bit UCS characters */

+    if( (keysym & 0xff000000) == 0x01000000 )

+    {

+        return keysym & 0x00ffffff;

+    }

+

+    /* Binary search in table */

+    while( max >= min )

+    {

+        mid = (min + max) / 2;

+        if( keysymtab[mid].keysym < keysym )

+        {

+            min = mid + 1;

+        }

+        else if( keysymtab[mid].keysym > keysym )

+        {

+            max = mid - 1;

+        }

+        else

+        {

+            /* Found it! */

+            return keysymtab[mid].ucs;

+        }

+    }

+

+    /* No matching Unicode value found */

+    return -1;

+}

diff --git a/src/engine/external/glfw/lib/x11/x11_thread.c b/src/engine/external/glfw/lib/x11/x11_thread.c
new file mode 100644
index 00000000..1a5db7e7
--- /dev/null
+++ b/src/engine/external/glfw/lib/x11/x11_thread.c
@@ -0,0 +1,507 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        x11_thread.c

+// Platform:    X11 (Unix)

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

+

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

+//****                  GLFW internal functions                       ****

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

+

+#ifdef _GLFW_HAS_PTHREAD

+

+//========================================================================

+// _glfwNewThread() - This is simply a "wrapper" for calling the user

+// thread function.

+//========================================================================

+

+void * _glfwNewThread( void * arg )

+{

+    GLFWthreadfun threadfun;

+    _GLFWthread   *t;

+    pthread_t   posixID;

+

+    // Get current thread ID

+    posixID = pthread_self();

+

+    // Enter critical section

+    ENTER_THREAD_CRITICAL_SECTION

+

+    // Loop through entire list of threads to find the matching POSIX

+    // thread ID

+    for( t = &_glfwThrd.First; t != NULL; t = t->Next )

+    {

+        if( t->PosixID == posixID )

+        {

+            break;

+        }

+    }

+    if( t == NULL )

+    {

+        LEAVE_THREAD_CRITICAL_SECTION

+        return NULL;

+    }

+

+    // Get user thread function pointer

+    threadfun = t->Function;

+

+    // Leave critical section

+    LEAVE_THREAD_CRITICAL_SECTION

+

+    // Call the user thread function

+    threadfun( arg );

+

+    // Remove thread from thread list

+    ENTER_THREAD_CRITICAL_SECTION

+    _glfwRemoveThread( t );

+    LEAVE_THREAD_CRITICAL_SECTION

+

+    // When the thread function returns, the thread will die...

+    return NULL;

+}

+

+#endif // _GLFW_HAS_PTHREAD

+

+

+

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

+//****               Platform implementation functions                ****

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

+

+//========================================================================

+// _glfwPlatformCreateThread() - Create a new thread

+//========================================================================

+

+GLFWthread _glfwPlatformCreateThread( GLFWthreadfun fun, void *arg )

+{

+#ifdef _GLFW_HAS_PTHREAD

+

+    GLFWthread  ID;

+    _GLFWthread *t;

+    int         result;

+

+    // Enter critical section

+    ENTER_THREAD_CRITICAL_SECTION

+

+    // Create a new thread information memory area

+    t = (_GLFWthread *) malloc( sizeof(_GLFWthread) );

+    if( t == NULL )

+    {

+        // Leave critical section

+        LEAVE_THREAD_CRITICAL_SECTION

+        return -1;

+    }

+

+    // Get a new unique thread id

+    ID = _glfwThrd.NextID ++;

+

+    // Store thread information in the thread list

+    t->Function = fun;

+    t->ID       = ID;

+

+    // Create thread

+    result = pthread_create(

+        &t->PosixID,      // Thread handle

+        NULL,             // Default thread attributes

+        _glfwNewThread,   // Thread function (a wrapper function)

+        (void *)arg       // Argument to thread is user argument

+    );

+

+    // Did the thread creation fail?

+    if( result != 0 )

+    {

+        free( (void *) t );

+        LEAVE_THREAD_CRITICAL_SECTION

+        return -1;

+    }

+

+    // Append thread to thread list

+    _glfwAppendThread( t );

+

+    // Leave critical section

+    LEAVE_THREAD_CRITICAL_SECTION

+

+    // Return the GLFW thread ID

+    return ID;

+

+#else

+

+    return -1;

+

+#endif // _GLFW_HAS_PTHREAD

+}

+

+

+//========================================================================

+// _glfwPlatformDestroyThread() - Kill a thread. NOTE: THIS IS A VERY

+// DANGEROUS OPERATION, AND SHOULD NOT BE USED EXCEPT IN EXTREME

+// SITUATIONS!

+//========================================================================

+

+void _glfwPlatformDestroyThread( GLFWthread ID )

+{

+#ifdef _GLFW_HAS_PTHREAD

+

+    _GLFWthread *t;

+

+    // Enter critical section

+    ENTER_THREAD_CRITICAL_SECTION

+

+    // Get thread information pointer

+    t = _glfwGetThreadPointer( ID );

+    if( t == NULL )

+    {

+        LEAVE_THREAD_CRITICAL_SECTION

+        return;

+    }

+

+    // Simply murder the process, no mercy!

+    pthread_kill( t->PosixID, SIGKILL );

+

+    // Remove thread from thread list

+    _glfwRemoveThread( t );

+

+    // Leave critical section

+    LEAVE_THREAD_CRITICAL_SECTION

+

+#endif // _GLFW_HAS_PTHREAD

+}

+

+

+//========================================================================

+// _glfwPlatformWaitThread() - Wait for a thread to die

+//========================================================================

+

+int _glfwPlatformWaitThread( GLFWthread ID, int waitmode )

+{

+#ifdef _GLFW_HAS_PTHREAD

+

+    pthread_t   thread;

+    _GLFWthread *t;

+

+    // Enter critical section

+    ENTER_THREAD_CRITICAL_SECTION

+

+    // Get thread information pointer

+    t = _glfwGetThreadPointer( ID );

+

+    // Is the thread already dead?

+    if( t == NULL )

+    {

+        LEAVE_THREAD_CRITICAL_SECTION

+        return GL_TRUE;

+    }

+

+    // If got this far, the thread is alive => polling returns FALSE

+    if( waitmode == GLFW_NOWAIT )

+    {

+        LEAVE_THREAD_CRITICAL_SECTION

+        return GL_FALSE;

+    }

+

+    // Get thread handle

+    thread = t->PosixID;

+

+    // Leave critical section

+    LEAVE_THREAD_CRITICAL_SECTION

+

+    // Wait for thread to die

+    (void) pthread_join( thread, NULL );

+

+    return GL_TRUE;

+

+#else

+

+    return GL_TRUE;

+

+#endif // _GLFW_HAS_PTHREAD

+}

+

+

+//========================================================================

+// _glfwPlatformGetThreadID() - Return the thread ID for the current

+// thread

+//========================================================================

+

+GLFWthread _glfwPlatformGetThreadID( void )

+{

+#ifdef _GLFW_HAS_PTHREAD

+

+    _GLFWthread *t;

+    GLFWthread  ID = -1;

+    pthread_t   posixID;

+

+    // Get current thread ID

+    posixID = pthread_self();

+

+    // Enter critical section

+    ENTER_THREAD_CRITICAL_SECTION

+

+    // Loop through entire list of threads to find the matching POSIX

+    // thread ID

+    for( t = &_glfwThrd.First; t != NULL; t = t->Next )

+    {

+        if( t->PosixID == posixID )

+        {

+            ID = t->ID;

+            break;

+        }

+    }

+

+    // Leave critical section

+    LEAVE_THREAD_CRITICAL_SECTION

+

+    // Return the found GLFW thread identifier

+    return ID;

+

+#else

+

+    return 0;

+

+#endif // _GLFW_HAS_PTHREAD

+}

+

+

+//========================================================================

+// _glfwPlatformCreateMutex() - Create a mutual exclusion object

+//========================================================================

+

+GLFWmutex _glfwPlatformCreateMutex( void )

+{

+#ifdef _GLFW_HAS_PTHREAD

+

+    pthread_mutex_t *mutex;

+

+    // Allocate memory for mutex

+    mutex = (pthread_mutex_t *) malloc( sizeof( pthread_mutex_t ) );

+    if( !mutex )

+    {

+        return NULL;

+    }

+

+    // Initialise a mutex object

+    (void) pthread_mutex_init( mutex, NULL );

+

+    // Cast to GLFWmutex and return

+    return (GLFWmutex) mutex;

+

+#else

+

+    return (GLFWmutex) 0;

+

+#endif // _GLFW_HAS_PTHREAD

+}

+

+

+//========================================================================

+// _glfwPlatformDestroyMutex() - Destroy a mutual exclusion object

+//========================================================================

+

+void _glfwPlatformDestroyMutex( GLFWmutex mutex )

+{

+#ifdef _GLFW_HAS_PTHREAD

+

+    // Destroy the mutex object

+    pthread_mutex_destroy( (pthread_mutex_t *) mutex );

+

+    // Free memory for mutex object

+    free( (void *) mutex );

+

+#endif // _GLFW_HAS_PTHREAD

+}

+

+

+//========================================================================

+// _glfwPlatformLockMutex() - Request access to a mutex

+//========================================================================

+

+void _glfwPlatformLockMutex( GLFWmutex mutex )

+{

+#ifdef _GLFW_HAS_PTHREAD

+

+    // Wait for mutex to be released

+    (void) pthread_mutex_lock( (pthread_mutex_t *) mutex );

+

+#endif // _GLFW_HAS_PTHREAD

+}

+

+

+//========================================================================

+// _glfwPlatformUnlockMutex() - Release a mutex

+//========================================================================

+

+void _glfwPlatformUnlockMutex( GLFWmutex mutex )

+{

+#ifdef _GLFW_HAS_PTHREAD

+

+    // Release mutex

+    pthread_mutex_unlock( (pthread_mutex_t *) mutex );

+

+#endif // _GLFW_HAS_PTHREAD

+}

+

+

+//========================================================================

+// _glfwPlatformCreateCond() - Create a new condition variable object

+//========================================================================

+

+GLFWcond _glfwPlatformCreateCond( void )

+{

+#ifdef _GLFW_HAS_PTHREAD

+

+    pthread_cond_t *cond;

+

+    // Allocate memory for condition variable

+    cond = (pthread_cond_t *) malloc( sizeof(pthread_cond_t) );

+    if( !cond )

+    {

+        return NULL;

+    }

+

+    // Initialise condition variable

+    (void) pthread_cond_init( cond, NULL );

+

+    // Cast to GLFWcond and return

+    return (GLFWcond) cond;

+

+#else

+

+    return (GLFWcond) 0;

+

+#endif // _GLFW_HAS_PTHREAD

+}

+

+

+//========================================================================

+// _glfwPlatformDestroyCond() - Destroy a condition variable object

+//========================================================================

+

+void _glfwPlatformDestroyCond( GLFWcond cond )

+{

+#ifdef _GLFW_HAS_PTHREAD

+

+    // Destroy the condition variable object

+    (void) pthread_cond_destroy( (pthread_cond_t *) cond );

+

+    // Free memory for condition variable object

+    free( (void *) cond );

+

+#endif // _GLFW_HAS_PTHREAD

+}

+

+

+//========================================================================

+// _glfwPlatformWaitCond() - Wait for a condition to be raised

+//========================================================================

+

+void _glfwPlatformWaitCond( GLFWcond cond, GLFWmutex mutex,

+    double timeout )

+{

+#ifdef _GLFW_HAS_PTHREAD

+

+    struct timeval  currenttime;

+    struct timespec wait;

+    long dt_sec, dt_usec;

+

+    // Select infinite or timed wait

+    if( timeout >= GLFW_INFINITY )

+    {

+        // Wait for condition (infinite wait)

+        (void) pthread_cond_wait( (pthread_cond_t *) cond,

+                  (pthread_mutex_t *) mutex );

+    }

+    else

+    {

+        // Set timeout time, relatvie to current time

+        gettimeofday( &currenttime, NULL );

+        dt_sec  = (long) timeout;

+        dt_usec = (long) ((timeout - (double)dt_sec) * 1000000.0);

+        wait.tv_nsec = (currenttime.tv_usec + dt_usec) * 1000L;

+        if( wait.tv_nsec > 1000000000L )

+        {

+            wait.tv_nsec -= 1000000000L;

+            dt_sec ++;

+        }

+        wait.tv_sec  = currenttime.tv_sec + dt_sec;

+

+        // Wait for condition (timed wait)

+        (void) pthread_cond_timedwait( (pthread_cond_t *) cond,

+                   (pthread_mutex_t *) mutex, &wait );

+    }

+

+#endif // _GLFW_HAS_PTHREAD

+}

+

+

+//========================================================================

+// _glfwPlatformSignalCond() - Signal a condition to one waiting thread

+//========================================================================

+

+void _glfwPlatformSignalCond( GLFWcond cond )

+{

+#ifdef _GLFW_HAS_PTHREAD

+

+    // Signal condition

+    (void) pthread_cond_signal( (pthread_cond_t *) cond );

+

+#endif // _GLFW_HAS_PTHREAD

+}

+

+

+//========================================================================

+// _glfwPlatformBroadcastCond() - Broadcast a condition to all waiting

+// threads

+//========================================================================

+

+void _glfwPlatformBroadcastCond( GLFWcond cond )

+{

+#ifdef _GLFW_HAS_PTHREAD

+

+    // Broadcast condition

+    (void) pthread_cond_broadcast( (pthread_cond_t *) cond );

+

+#endif // _GLFW_HAS_PTHREAD

+}

+

+

+//========================================================================

+// _glfwPlatformGetNumberOfProcessors() - Return the number of processors

+// in the system.

+//========================================================================

+

+int _glfwPlatformGetNumberOfProcessors( void )

+{

+    int n;

+

+    // Get number of processors online

+    _glfw_numprocessors( n );

+    return n;

+}

diff --git a/src/engine/external/glfw/lib/x11/x11_time.c b/src/engine/external/glfw/lib/x11/x11_time.c
new file mode 100644
index 00000000..32ae9d9d
--- /dev/null
+++ b/src/engine/external/glfw/lib/x11/x11_time.c
@@ -0,0 +1,154 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        x11_time.c

+// Platform:    X11 (Unix)

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

+//========================================================================

+// Initialise timer

+//========================================================================

+

+void _glfwInitTimer( void )

+{

+    struct timeval  tv;

+

+    // "Resolution" is 1 us

+    _glfwLibrary.Timer.Resolution = 1e-6;

+

+    // Set start-time for timer

+    gettimeofday( &tv, NULL );

+    _glfwLibrary.Timer.t0 = (long long) tv.tv_sec * (long long) 1000000 +

+		            (long long) tv.tv_usec;

+}

+

+

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

+//****               Platform implementation functions                ****

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

+

+//========================================================================

+// Return timer value in seconds

+//========================================================================

+

+double _glfwPlatformGetTime( void )

+{

+    long long t;

+    struct timeval  tv;

+

+    gettimeofday( &tv, NULL );

+    t = (long long) tv.tv_sec * (long long) 1000000 +

+	(long long) tv.tv_usec;

+

+    return (double)(t - _glfwLibrary.Timer.t0) * _glfwLibrary.Timer.Resolution;

+}

+

+

+//========================================================================

+// Set timer value in seconds

+//========================================================================

+

+void _glfwPlatformSetTime( double t )

+{

+    long long t0;

+    struct timeval  tv;

+

+    gettimeofday( &tv, NULL );

+    t0 = (long long) tv.tv_sec * (long long) 1000000 +

+	 (long long) tv.tv_usec;

+

+    // Calulate new starting time

+    _glfwLibrary.Timer.t0 = t0 - (long long)(t/_glfwLibrary.Timer.Resolution);

+}

+

+

+//========================================================================

+// Put a thread to sleep for a specified amount of time

+//========================================================================

+

+void _glfwPlatformSleep( double time )

+{

+#ifdef _GLFW_HAS_PTHREAD

+

+    if( time == 0.0 )

+    {

+#ifdef _GLFW_HAS_SCHED_YIELD

+	sched_yield();

+#endif

+	return;

+    }

+

+    struct timeval  currenttime;

+    struct timespec wait;

+    pthread_mutex_t mutex;

+    pthread_cond_t  cond;

+    long dt_sec, dt_usec;

+

+    // Not all pthread implementations have a pthread_sleep() function. We

+    // do it the portable way, using a timed wait for a condition that we

+    // will never signal. NOTE: The unistd functions sleep/usleep suspends

+    // the entire PROCESS, not a signle thread, which is why we can not

+    // use them to implement glfwSleep.

+

+    // Set timeout time, relatvie to current time

+    gettimeofday( &currenttime, NULL );

+    dt_sec  = (long) time;

+    dt_usec = (long) ((time - (double)dt_sec) * 1000000.0);

+    wait.tv_nsec = (currenttime.tv_usec + dt_usec) * 1000L;

+    if( wait.tv_nsec > 1000000000L )

+    {

+        wait.tv_nsec -= 1000000000L;

+        dt_sec++;

+    }

+    wait.tv_sec  = currenttime.tv_sec + dt_sec;

+

+    // Initialize condition and mutex objects

+    pthread_mutex_init( &mutex, NULL );

+    pthread_cond_init( &cond, NULL );

+

+    // Do a timed wait

+    pthread_mutex_lock( &mutex );

+    pthread_cond_timedwait( &cond, &mutex, &wait );

+    pthread_mutex_unlock( &mutex );

+

+    // Destroy condition and mutex objects

+    pthread_mutex_destroy( &mutex );

+    pthread_cond_destroy( &cond );

+

+#else

+

+    // For systems without PTHREAD, use unistd usleep

+    if( time > 0 )

+    {

+        usleep( (unsigned int) (time*1000000) );

+    }

+

+#endif // _GLFW_HAS_PTHREAD

+}

+

diff --git a/src/engine/external/glfw/lib/x11/x11_window.c b/src/engine/external/glfw/lib/x11/x11_window.c
new file mode 100644
index 00000000..d9d97be4
--- /dev/null
+++ b/src/engine/external/glfw/lib/x11/x11_window.c
@@ -0,0 +1,1746 @@
+//========================================================================

+// GLFW - An OpenGL framework

+// File:        x11_window.c

+// Platform:    X11 (Unix)

+// API version: 2.6

+// WWW:         http://glfw.sourceforge.net

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

+// Copyright (c) 2002-2006 Camilla Berglund

+//

+// 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.

+//

+//========================================================================

+

+#include "internal.h"

+

+

+/* Defines some GLX FSAA tokens if not yet defined */

+#ifndef GLX_SAMPLE_BUFFERS

+# define GLX_SAMPLE_BUFFERS  100000

+#endif 

+#ifndef GLX_SAMPLES 

+# define GLX_SAMPLES         100001

+#endif 

+

+

+/* KDE decoration values */

+enum {

+  KDE_noDecoration = 0,

+  KDE_normalDecoration = 1,

+  KDE_tinyDecoration = 2,

+  KDE_noFocus = 256,

+  KDE_standaloneMenuBar = 512,

+  KDE_desktopIcon = 1024 ,

+  KDE_staysOnTop = 2048

+};

+

+

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

+//****                  GLFW internal functions                       ****

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

+

+//========================================================================

+// _glfwWaitForMapNotify()

+//========================================================================

+

+Bool _glfwWaitForMapNotify( Display *d, XEvent *e, char *arg )

+{

+    return (e->type == MapNotify) && (e->xmap.window == (Window)arg);

+}

+

+

+//========================================================================

+// _glfwWaitForUnmapNotify()

+//========================================================================

+

+Bool _glfwWaitForUnmapNotify( Display *d, XEvent *e, char *arg )

+{

+    return (e->type == UnmapNotify) && (e->xmap.window == (Window)arg);

+}

+

+

+//========================================================================

+// _glfwDisableDecorations() - Turn off window decorations

+// Based on xawdecode: src/wmhooks.c

+//========================================================================

+

+#define MWM_HINTS_DECORATIONS (1L << 1)

+

+static void _glfwDisableDecorations( void )

+{

+    int                   RemovedDecorations;

+    Atom                  HintAtom;

+    XSetWindowAttributes  attributes;

+

+    RemovedDecorations = 0;

+

+    // First try to set MWM hints

+    HintAtom = XInternAtom( _glfwLibrary.Dpy, "_MOTIF_WM_HINTS", True );

+    if ( HintAtom != None )

+    {

+        struct {

+            unsigned long flags;

+            unsigned long functions;

+            unsigned long decorations;

+                     long input_mode;

+            unsigned long status;

+        } MWMHints = { MWM_HINTS_DECORATIONS, 0, 0, 0, 0 };

+

+        XChangeProperty( _glfwLibrary.Dpy, _glfwWin.Win, HintAtom, HintAtom,

+                         32, PropModeReplace, (unsigned char *)&MWMHints,

+                         sizeof(MWMHints)/4 );

+        RemovedDecorations = 1;

+    }

+

+    // Now try to set KWM hints

+    HintAtom = XInternAtom( _glfwLibrary.Dpy, "KWM_WIN_DECORATION", True );

+    if ( HintAtom != None )

+    {

+        long KWMHints = KDE_tinyDecoration;

+

+        XChangeProperty( _glfwLibrary.Dpy, _glfwWin.Win, HintAtom, HintAtom,

+                         32, PropModeReplace, (unsigned char *)&KWMHints,

+                         sizeof(KWMHints)/4 );

+        RemovedDecorations = 1;

+    }

+

+    // Now try to set GNOME hints

+    HintAtom = XInternAtom(_glfwLibrary.Dpy, "_WIN_HINTS", True );

+    if ( HintAtom != None )

+    {

+        long GNOMEHints = 0;

+

+        XChangeProperty( _glfwLibrary.Dpy, _glfwWin.Win, HintAtom, HintAtom,

+                         32, PropModeReplace, (unsigned char *)&GNOMEHints,

+                         sizeof(GNOMEHints)/4 );

+        RemovedDecorations = 1;

+    }

+

+    // Now try to set KDE NET_WM hints

+    HintAtom = XInternAtom( _glfwLibrary.Dpy, "_NET_WM_WINDOW_TYPE", True );

+    if ( HintAtom != None )

+    {

+        Atom NET_WMHints[2];

+

+        NET_WMHints[0] = XInternAtom( _glfwLibrary.Dpy, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True );

+        /* define a fallback... */

+        NET_WMHints[1] = XInternAtom( _glfwLibrary.Dpy, "_NET_WM_WINDOW_TYPE_NORMAL", True );

+

+        XChangeProperty( _glfwLibrary.Dpy, _glfwWin.Win, HintAtom, XA_ATOM,

+                         32, PropModeReplace, (unsigned char *)&NET_WMHints,

+                         2 );

+        RemovedDecorations = 1;

+    }

+

+    // Set ICCCM fullscreen WM hint

+    HintAtom = XInternAtom( _glfwLibrary.Dpy, "_NET_WM_STATE", True );

+    if ( HintAtom != None )

+    {

+        Atom NET_WMHints[1];

+

+        NET_WMHints[0] = XInternAtom( _glfwLibrary.Dpy, "_NET_WM_STATE_FULLSCREEN", True );

+

+        XChangeProperty( _glfwLibrary.Dpy, _glfwWin.Win, HintAtom, XA_ATOM,

+                         32, PropModeReplace, (unsigned char *)&NET_WMHints, 1 );

+    }

+

+

+    // Did we sucessfully remove the window decorations?

+    if( RemovedDecorations )

+    {

+        // Finally set the transient hints

+        XSetTransientForHint( _glfwLibrary.Dpy, _glfwWin.Win, RootWindow(_glfwLibrary.Dpy, _glfwWin.Scrn) );

+        XUnmapWindow( _glfwLibrary.Dpy, _glfwWin.Win );

+        XMapWindow( _glfwLibrary.Dpy, _glfwWin.Win );

+    }

+    else

+    {

+        // The Butcher way of removing window decorations

+        attributes.override_redirect = True;

+        XChangeWindowAttributes( _glfwLibrary.Dpy, _glfwWin.Win,

+                                 CWOverrideRedirect, &attributes );

+        _glfwWin.OverrideRedirect = GL_TRUE;

+    }

+}

+

+

+//========================================================================

+// _glfwEnableDecorations() - Turn on window decorations

+//========================================================================

+

+static void _glfwEnableDecorations( void )

+{

+    int                   ActivatedDecorations;

+    Atom                  HintAtom;

+

+    // If this is an override redirect window, skip it...

+    if( _glfwWin.OverrideRedirect )

+    {

+        return;

+    }

+

+    ActivatedDecorations = 0;

+

+    // First try to unset MWM hints

+    HintAtom = XInternAtom( _glfwLibrary.Dpy, "_MOTIF_WM_HINTS", True );

+    if ( HintAtom != None )

+    {

+        XDeleteProperty( _glfwLibrary.Dpy, _glfwWin.Win, HintAtom );

+        ActivatedDecorations = 1;

+    }

+

+    // Now try to unset KWM hints

+    HintAtom = XInternAtom( _glfwLibrary.Dpy, "KWM_WIN_DECORATION", True );

+    if ( HintAtom != None )

+    {

+        XDeleteProperty( _glfwLibrary.Dpy, _glfwWin.Win, HintAtom );

+        ActivatedDecorations = 1;

+    }

+

+    // Now try to unset GNOME hints

+    HintAtom = XInternAtom( _glfwLibrary.Dpy, "_WIN_HINTS", True );

+    if ( HintAtom != None )

+    {

+        XDeleteProperty( _glfwLibrary.Dpy, _glfwWin.Win, HintAtom );

+        ActivatedDecorations = 1;

+    }

+

+    // Now try to unset NET_WM hints

+    HintAtom = XInternAtom( _glfwLibrary.Dpy, "_NET_WM_WINDOW_TYPE", True );

+    if ( HintAtom != None )

+    {

+        Atom NET_WMHints = XInternAtom( _glfwLibrary.Dpy, "_NET_WM_WINDOW_TYPE_NORMAL", True);

+        if( NET_WMHints != None )

+        {

+            XChangeProperty( _glfwLibrary.Dpy, _glfwWin.Win,

+                            HintAtom, XA_ATOM, 32, PropModeReplace,

+                            (unsigned char *)&NET_WMHints, 1 );

+            ActivatedDecorations = 1;

+        }

+    }

+

+    // Finally unset the transient hints if necessary

+    if( ActivatedDecorations )

+    {

+        // NOTE: Does this work?

+        XSetTransientForHint( _glfwLibrary.Dpy, _glfwWin.Win, None);

+        XUnmapWindow( _glfwLibrary.Dpy, _glfwWin.Win );

+        XMapWindow( _glfwLibrary.Dpy, _glfwWin.Win );

+    }

+}

+

+

+//========================================================================

+// _glfwChooseVisual() - We do our own function here, since

+// glXChooseVisual does not behave as we want it to (not according to the

+// GLFW specs)

+//========================================================================

+

+XVisualInfo * _glfwChooseVisual( Display *Dpy, int Screen, int r, int g,

+    int b, int a, int d, int s, int ar, int ag, int ab, int aa, int aux,

+				 int fsaa, int stereo)

+{

+    XVisualInfo *VI, *VI_list, VI_tmp;

+    int  nitems_return, i;

+    int  vi_gl, vi_rgba, vi_double, vi_stereo;

+    int  vi_r, vi_g, vi_b, vi_a, vi_d, vi_s, vi_ar, vi_ag, vi_ab, vi_aa;

+    int  vi_aux;

+    int  color, accum, vi_accum;

+    int  missing, color_diff, extra_diff;

+    int  best_vis, best_missing, best_color_diff, best_extra_diff;

+    int  samples, samplebuffers, vi_samples, vi_samplebuffers;

+

+    // Get list of visuals for this screen & display

+    VI_tmp.screen = Screen;

+    VI_list = XGetVisualInfo( Dpy, VisualScreenMask, &VI_tmp,

+                              &nitems_return );

+    if( VI_list == NULL )

+    {

+        return NULL;

+    }

+

+    // Pick some prefered color depth if the user did not request a

+    // specific depth (note: if the user did not request a specific color

+    // depth, this will not be a driving demand, it's only here to avoid

+    // selection randomness)

+    color = (r > 0 || g > 0 || b > 0);

+    if( !color )

+    {

+        r = g = b = 8;

+    }

+

+    // Make sure that stereo is 1 or 0

+    stereo = stereo ? 1 : 0;

+

+    // Convenience pre-calculation

+    accum = (ar > 0 || ag > 0 || ab > 0 || aa > 0);

+    

+    samples = fsaa;

+    samplebuffers = (fsaa > 0) ? 1 : 0;

+    

+    

+

+    // Loop through list of visuals to find best match

+    best_vis        = -1;

+    best_missing    = 0x7fffffff;

+    best_color_diff = 0x7fffffff;

+    best_extra_diff = 0x7fffffff;

+    for( i = 0; i < nitems_return; i ++ )

+    {

+        // We want GL, RGBA & DOUBLEBUFFER, and NOT STEREO / STEREO

+        glXGetConfig( Dpy, &VI_list[i], GLX_USE_GL, &vi_gl );

+        glXGetConfig( Dpy, &VI_list[i], GLX_RGBA, &vi_rgba );

+        glXGetConfig( Dpy, &VI_list[i], GLX_DOUBLEBUFFER, &vi_double );

+        glXGetConfig( Dpy, &VI_list[i], GLX_STEREO, &vi_stereo );

+        vi_stereo = vi_stereo ? 1 : 0;

+        if( vi_gl && vi_rgba && vi_double && (vi_stereo == stereo) )

+        {

+            // Get visual color parameters

+            glXGetConfig( Dpy, &VI_list[i], GLX_RED_SIZE, &vi_r );

+            glXGetConfig( Dpy, &VI_list[i], GLX_GREEN_SIZE, &vi_g );

+            glXGetConfig( Dpy, &VI_list[i], GLX_BLUE_SIZE, &vi_b );

+

+            // Get visual "extra" parameters

+            glXGetConfig( Dpy, &VI_list[i], GLX_ALPHA_SIZE, &vi_a );

+            glXGetConfig( Dpy, &VI_list[i], GLX_DEPTH_SIZE, &vi_d );

+            glXGetConfig( Dpy, &VI_list[i], GLX_STENCIL_SIZE, &vi_s );

+            glXGetConfig( Dpy, &VI_list[i], GLX_ACCUM_RED_SIZE, &vi_ar );

+            glXGetConfig( Dpy, &VI_list[i], GLX_ACCUM_GREEN_SIZE, &vi_ag );

+            glXGetConfig( Dpy, &VI_list[i], GLX_ACCUM_BLUE_SIZE, &vi_ab );

+            glXGetConfig( Dpy, &VI_list[i], GLX_ACCUM_ALPHA_SIZE, &vi_aa );

+            glXGetConfig( Dpy, &VI_list[i], GLX_AUX_BUFFERS, &vi_aux );

+	    glXGetConfig( Dpy, &VI_list[i], GLX_SAMPLE_BUFFERS, &vi_samplebuffers );

+	    glXGetConfig( Dpy, &VI_list[i], GLX_SAMPLES, &vi_samples );

+	    

+            vi_accum = (vi_ar > 0 || vi_ag > 0 || vi_ab > 0 || vi_aa > 0);

+

+            // Check how many buffers are missing

+            missing = 0;

+            if( a > 0 && vi_a == 0 ) missing ++;

+            if( d > 0 && vi_d == 0 ) missing ++;

+            if( s > 0 && vi_s == 0 ) missing ++;

+            if( accum && !vi_accum ) missing ++;

+            if( aux > 0 && vi_aux == 0 ) missing ++;

+	    if( samplebuffers > 0 && vi_samplebuffers == 0 ) missing ++;

+	    

+

+            // Calculate color diff

+            color_diff = (r - vi_r) * (r - vi_r) +

+                         (g - vi_g) * (g - vi_g) +

+                         (b - vi_b) * (b - vi_b);

+

+            // Calculate "extra" diff

+            extra_diff = 0;

+            if( a > 0 )

+            {

+                extra_diff += (a - vi_a) * (a - vi_a);

+            }

+            if( d > 0 )

+            {

+                extra_diff += (d - vi_d) * (d - vi_d);

+            }

+            if( s > 0 )

+            {

+                extra_diff += (s - vi_s) * (s - vi_s);

+            }

+            if( accum )

+            {

+                extra_diff += (ar - vi_ar) * (ar - vi_ar) +

+                              (ag - vi_ag) * (ag - vi_ag) +

+                              (ab - vi_ab) * (ab - vi_ab) +

+                              (aa - vi_aa) * (aa - vi_aa);

+            }

+            if( aux > 0 )

+            {

+                extra_diff += (aux - vi_aux) * (aux - vi_aux);

+            }

+	    if( samples > 0 )

+	    {

+	      extra_diff += (samples - vi_samples) * (samples - vi_samples);

+	      

+	    }

+            // Check if this is a better match. We implement some

+            // complicated rules, by prioritizing in this order:

+            //  1) Visuals with the least number of missing buffers always

+            //     have priority

+            //  2a) If (r,g,b)!=(0,0,0), color depth has priority over

+            //      other buffers

+            //  2b) If (r,g,b)==(0,0,0), other buffers have priority over

+            //      color depth

+            if( missing < best_missing )

+            {

+                best_vis = i;

+            }

+            else if( missing == best_missing )

+            {

+                if( color )

+                {

+                    if( (color_diff < best_color_diff) ||

+                        (color_diff == best_color_diff &&

+                         extra_diff < best_extra_diff) )

+                    {

+                        best_vis = i;

+                    }

+                }

+                else

+                {

+                    if( (extra_diff < best_extra_diff) ||

+                        (extra_diff == best_extra_diff &&

+                         color_diff < best_color_diff) )

+                    {

+                        best_vis = i;

+                    }

+                }

+            }

+            if( best_vis == i )

+            {

+                best_missing    = missing;

+                best_color_diff = color_diff;

+                best_extra_diff = extra_diff;

+            }

+        }

+    }

+

+    // Copy best visual to a visual to return

+    if( best_vis >= 0 )

+    {

+        VI = XGetVisualInfo( Dpy, VisualIDMask, &VI_list[ best_vis ],

+                             &nitems_return );

+    }

+    else

+    {

+        VI = NULL;

+    }

+

+    // Free visuals list

+    XFree( VI_list );

+

+    return VI;

+}

+

+

+//========================================================================

+// _glfwTranslateKey() - Translates an X Window key to internal coding

+//========================================================================

+

+static int _glfwTranslateKey( int keycode )

+{

+    KeySym key, key_lc, key_uc;

+

+    // Try secondary keysym, for numeric keypad keys

+    // Note: This way we always force "NumLock = ON", which at least

+    // enables GLFW users to detect numeric keypad keys

+    key = XKeycodeToKeysym( _glfwLibrary.Dpy, keycode, 1 );

+    switch( key )

+    {

+        // Numeric keypad

+        case XK_KP_0:         return GLFW_KEY_KP_0;

+        case XK_KP_1:         return GLFW_KEY_KP_1;

+        case XK_KP_2:         return GLFW_KEY_KP_2;

+        case XK_KP_3:         return GLFW_KEY_KP_3;

+        case XK_KP_4:         return GLFW_KEY_KP_4;

+        case XK_KP_5:         return GLFW_KEY_KP_5;

+        case XK_KP_6:         return GLFW_KEY_KP_6;

+        case XK_KP_7:         return GLFW_KEY_KP_7;

+        case XK_KP_8:         return GLFW_KEY_KP_8;

+        case XK_KP_9:         return GLFW_KEY_KP_9;

+        case XK_KP_Separator:

+        case XK_KP_Decimal:   return GLFW_KEY_KP_DECIMAL;

+        case XK_KP_Equal:     return GLFW_KEY_KP_EQUAL;

+        case XK_KP_Enter:     return GLFW_KEY_KP_ENTER;

+        default:              break;

+    }

+

+    // Now try pimary keysym

+    key = XKeycodeToKeysym( _glfwLibrary.Dpy, keycode, 0 );

+    switch( key )

+    {

+        // Special keys (non character keys)

+        case XK_Escape:       return GLFW_KEY_ESC;

+        case XK_Tab:          return GLFW_KEY_TAB;

+        case XK_Shift_L:      return GLFW_KEY_LSHIFT;

+        case XK_Shift_R:      return GLFW_KEY_RSHIFT;

+        case XK_Control_L:    return GLFW_KEY_LCTRL;

+        case XK_Control_R:    return GLFW_KEY_RCTRL;

+        case XK_Meta_L:

+        case XK_Alt_L:        return GLFW_KEY_LALT;

+        case XK_Mode_switch:  // Mapped to Alt_R on many keyboards

+        case XK_Meta_R:

+        case XK_Alt_R:        return GLFW_KEY_RALT;

+        case XK_KP_Delete:

+        case XK_Delete:       return GLFW_KEY_DEL;

+        case XK_BackSpace:    return GLFW_KEY_BACKSPACE;

+        case XK_Return:       return GLFW_KEY_ENTER;

+        case XK_KP_Home:

+        case XK_Home:         return GLFW_KEY_HOME;

+        case XK_KP_End:

+        case XK_End:          return GLFW_KEY_END;

+        case XK_KP_Page_Up:

+        case XK_Page_Up:      return GLFW_KEY_PAGEUP;

+        case XK_KP_Page_Down:

+        case XK_Page_Down:    return GLFW_KEY_PAGEDOWN;

+        case XK_KP_Insert:

+        case XK_Insert:       return GLFW_KEY_INSERT;

+        case XK_KP_Left:

+        case XK_Left:         return GLFW_KEY_LEFT;

+        case XK_KP_Right:

+        case XK_Right:        return GLFW_KEY_RIGHT;

+        case XK_KP_Down:

+        case XK_Down:         return GLFW_KEY_DOWN;

+        case XK_KP_Up:

+        case XK_Up:           return GLFW_KEY_UP;

+        case XK_F1:           return GLFW_KEY_F1;

+        case XK_F2:           return GLFW_KEY_F2;

+        case XK_F3:           return GLFW_KEY_F3;

+        case XK_F4:           return GLFW_KEY_F4;

+        case XK_F5:           return GLFW_KEY_F5;

+        case XK_F6:           return GLFW_KEY_F6;

+        case XK_F7:           return GLFW_KEY_F7;

+        case XK_F8:           return GLFW_KEY_F8;

+        case XK_F9:           return GLFW_KEY_F9;

+        case XK_F10:          return GLFW_KEY_F10;

+        case XK_F11:          return GLFW_KEY_F11;

+        case XK_F12:          return GLFW_KEY_F12;

+        case XK_F13:          return GLFW_KEY_F13;

+        case XK_F14:          return GLFW_KEY_F14;

+        case XK_F15:          return GLFW_KEY_F15;

+        case XK_F16:          return GLFW_KEY_F16;

+        case XK_F17:          return GLFW_KEY_F17;

+        case XK_F18:          return GLFW_KEY_F18;

+        case XK_F19:          return GLFW_KEY_F19;

+        case XK_F20:          return GLFW_KEY_F20;

+        case XK_F21:          return GLFW_KEY_F21;

+        case XK_F22:          return GLFW_KEY_F22;

+        case XK_F23:          return GLFW_KEY_F23;

+        case XK_F24:          return GLFW_KEY_F24;

+        case XK_F25:          return GLFW_KEY_F25;

+

+        // Numeric keypad (should have been detected in secondary keysym!)

+        case XK_KP_Divide:    return GLFW_KEY_KP_DIVIDE;

+        case XK_KP_Multiply:  return GLFW_KEY_KP_MULTIPLY;

+        case XK_KP_Subtract:  return GLFW_KEY_KP_SUBTRACT;

+        case XK_KP_Add:       return GLFW_KEY_KP_ADD;

+        case XK_KP_Equal:     return GLFW_KEY_KP_EQUAL;

+        case XK_KP_Enter:     return GLFW_KEY_KP_ENTER;

+

+        // The rest (should be printable keys)

+        default:

+            // Make uppercase

+            XConvertCase( key, &key_lc, &key_uc );

+            key = key_uc;

+

+            // Valid ISO 8859-1 character?

+            if( (key >=  32 && key <= 126) ||

+                (key >= 160 && key <= 255) )

+            {

+                return (int) key;

+            }

+            return GLFW_KEY_UNKNOWN;

+    }

+}

+

+

+//========================================================================

+// _glfwTranslateChar() - Translates an X Window event to Unicode

+//========================================================================

+

+static int _glfwTranslateChar( XKeyEvent *event )

+{

+    KeySym keysym;

+

+    // Get X11 keysym

+    XLookupString( event, NULL, 0, &keysym, NULL );

+

+    // Convert to Unicode (see x11_keysym2unicode.c)

+    return (int) _glfwKeySym2Unicode( keysym );

+}

+

+

+

+//========================================================================

+// Get next X event (called by glfwPollEvents)

+//========================================================================

+

+static int _glfwGetNextEvent( void )

+{

+    XEvent event, next_event;

+

+    // Pull next event from event queue

+    XNextEvent( _glfwLibrary.Dpy, &event );

+

+    // Handle certain window messages

+    switch( event.type )

+    {

+        // Is a key being pressed?

+        case KeyPress:

+	{

+            // Translate and report key press

+            _glfwInputKey( _glfwTranslateKey( event.xkey.keycode ), GLFW_PRESS );

+

+            // Translate and report character input

+            if( _glfwWin.CharCallback )

+            {

+                _glfwInputChar( _glfwTranslateChar( &event.xkey ), GLFW_PRESS );

+            }

+            break;

+	}

+

+        // Is a key being released?

+        case KeyRelease:

+	{

+            // Do not report key releases for key repeats. For key repeats

+            // we will get KeyRelease/KeyPress pairs with identical time

+            // stamps. User selected key repeat filtering is handled in

+            // _glfwInputKey()/_glfwInputChar().

+            if( XEventsQueued( _glfwLibrary.Dpy, QueuedAfterReading ) )

+            {

+                XPeekEvent( _glfwLibrary.Dpy, &next_event );

+                if( next_event.type == KeyPress &&

+                    next_event.xkey.window == event.xkey.window &&

+                    next_event.xkey.keycode == event.xkey.keycode &&

+                    next_event.xkey.time == event.xkey.time )

+                {

+                    // Do not report anything for this event

+                    break;

+                }

+            }

+

+            // Translate and report key release

+            _glfwInputKey( _glfwTranslateKey( event.xkey.keycode ), GLFW_RELEASE );

+

+            // Translate and report character input

+            if( _glfwWin.CharCallback )

+            {

+                _glfwInputChar( _glfwTranslateChar( &event.xkey ), GLFW_RELEASE );

+            }

+            break;

+	}

+

+        // Were any of the mouse-buttons pressed?

+        case ButtonPress:

+	{

+            if( event.xbutton.button == Button1 )

+            {

+                _glfwInputMouseClick( GLFW_MOUSE_BUTTON_LEFT, GLFW_PRESS );

+            }

+            else if( event.xbutton.button == Button2 )

+            {

+                _glfwInputMouseClick( GLFW_MOUSE_BUTTON_MIDDLE, GLFW_PRESS );

+            }

+            else if( event.xbutton.button == Button3 )

+            {

+                _glfwInputMouseClick( GLFW_MOUSE_BUTTON_RIGHT, GLFW_PRESS );

+            }

+

+            // XFree86 3.3.2 and later translates mouse wheel up/down into

+            // mouse button 4 & 5 presses

+            else if( event.xbutton.button == Button4 )

+            {

+                _glfwInput.WheelPos++;  // To verify: is this up or down?

+                if( _glfwWin.MouseWheelCallback )

+                {

+                    _glfwWin.MouseWheelCallback( _glfwInput.WheelPos );

+                }

+            }

+            else if( event.xbutton.button == Button5 )

+            {

+                _glfwInput.WheelPos--;

+                if( _glfwWin.MouseWheelCallback )

+                {

+                    _glfwWin.MouseWheelCallback( _glfwInput.WheelPos );

+                }

+            }

+            break;

+	}

+

+        // Were any of the mouse-buttons released?

+        case ButtonRelease:

+	{

+            if( event.xbutton.button == Button1 )

+            {

+                _glfwInputMouseClick( GLFW_MOUSE_BUTTON_LEFT,

+                                      GLFW_RELEASE );

+            }

+            else if( event.xbutton.button == Button2 )

+            {

+                _glfwInputMouseClick( GLFW_MOUSE_BUTTON_MIDDLE,

+                                      GLFW_RELEASE );

+            }

+            else if( event.xbutton.button == Button3 )

+            {

+                _glfwInputMouseClick( GLFW_MOUSE_BUTTON_RIGHT,

+                                      GLFW_RELEASE );

+            }

+            break;

+	}

+

+        // Was the mouse moved?

+        case MotionNotify:

+	{

+            if( event.xmotion.x != _glfwInput.CursorPosX ||

+                event.xmotion.y != _glfwInput.CursorPosY )

+            {

+                if( _glfwWin.MouseLock )

+                {

+                    _glfwInput.MousePosX += event.xmotion.x -

+                                            _glfwInput.CursorPosX;

+                    _glfwInput.MousePosY += event.xmotion.y -

+                                            _glfwInput.CursorPosY;

+                }

+                else

+                {

+                    _glfwInput.MousePosX = event.xmotion.x;

+                    _glfwInput.MousePosY = event.xmotion.y;

+                }

+                _glfwInput.CursorPosX = event.xmotion.x;

+                _glfwInput.CursorPosY = event.xmotion.y;

+                _glfwInput.MouseMoved = GL_TRUE;

+

+                // Call user callback function

+                if( _glfwWin.MousePosCallback )

+                {

+                    _glfwWin.MousePosCallback( _glfwInput.MousePosX,

+                                               _glfwInput.MousePosY );

+                }

+            }

+            break;

+	}

+

+        // Was the window resized?

+        case ConfigureNotify:

+	{

+            if( event.xconfigure.width != _glfwWin.Width ||

+                event.xconfigure.height != _glfwWin.Height )

+            {

+                _glfwWin.Width = event.xconfigure.width;

+                _glfwWin.Height = event.xconfigure.height;

+                if( _glfwWin.WindowSizeCallback )

+                {

+                    _glfwWin.WindowSizeCallback( _glfwWin.Width,

+                                                 _glfwWin.Height );

+                }

+            }

+            break;

+	}

+

+        // Was the window closed by the window manager?

+        case ClientMessage:

+	{

+            if( (Atom) event.xclient.data.l[ 0 ] == _glfwWin.WMDeleteWindow )

+            {

+                return GL_TRUE;

+            }

+

+	    if( (Atom) event.xclient.data.l[ 0 ] == _glfwWin.WMPing )

+	    {

+		XSendEvent( _glfwLibrary.Dpy,

+			    RootWindow( _glfwLibrary.Dpy, _glfwWin.VI->screen ),

+			    False, SubstructureNotifyMask | SubstructureRedirectMask, &event );

+	    }

+            break;

+	}

+

+        // Was the window mapped (un-iconified)?

+        case MapNotify:

+            _glfwWin.MapNotifyCount++;

+            break;

+

+        // Was the window unmapped (iconified)?

+        case UnmapNotify:

+            _glfwWin.MapNotifyCount--;

+            break;

+

+        // Was the window activated?

+        case FocusIn:

+            _glfwWin.FocusInCount++;

+            break;

+

+        // Was the window de-activated?

+        case FocusOut:

+            _glfwWin.FocusInCount--;

+            break;

+

+        // Was the window contents damaged?

+        case Expose:

+	{

+            // Call user callback function

+            if( _glfwWin.WindowRefreshCallback )

+            {

+                _glfwWin.WindowRefreshCallback();

+            }

+            break;

+	}

+

+        // Was the window destroyed?

+        case DestroyNotify:

+            return GL_TRUE;

+

+        default:

+	{

+#if defined( _GLFW_HAS_XRANDR )

+	    switch( event.type - _glfwLibrary.XRandR.EventBase )

+	    {

+		case RRScreenChangeNotify:

+		{

+		    // Show XRandR that we really care

+		    XRRUpdateConfiguration( &event );

+		    break;

+		}

+	    }

+#endif

+            break;

+	}

+    }

+

+    // The window was not destroyed

+    return GL_FALSE;

+}

+

+

+//========================================================================

+// _glfwCreateNULLCursor() - Create a blank cursor (for locked mouse mode)

+//========================================================================

+

+Cursor _glfwCreateNULLCursor( Display *display, Window root )

+{

+    Pixmap    cursormask;

+    XGCValues xgc;

+    GC        gc;

+    XColor    col;

+    Cursor    cursor;

+

+    cursormask = XCreatePixmap( display, root, 1, 1, 1 );

+    xgc.function = GXclear;

+    gc = XCreateGC( display, cursormask, GCFunction, &xgc );

+    XFillRectangle( display, cursormask, gc, 0, 0, 1, 1 );

+    col.pixel = 0;

+    col.red = 0;

+    col.flags = 4;

+    cursor = XCreatePixmapCursor( display, cursormask, cursormask,

+                                  &col,&col, 0,0 );

+    XFreePixmap( display, cursormask );

+    XFreeGC( display, gc );

+

+    return cursor;

+}

+

+

+//========================================================================

+// _glfwInitGLXExtensions() - Initialize GLX-specific extensions

+//========================================================================

+

+static void _glfwInitGLXExtensions( void )

+{

+    int has_swap_control;

+

+    // Initialize OpenGL extension: GLX_SGI_swap_control

+    has_swap_control = _glfwPlatformExtensionSupported(

+                           "GLX_SGI_swap_control"

+                       );

+

+    if( has_swap_control )

+    {

+        _glfwWin.SwapInterval = (GLXSWAPINTERVALSGI_T)

+            _glfw_glXGetProcAddress( (GLubyte*) "glXSwapIntervalSGI" );

+    }

+    else

+    {

+        _glfwWin.SwapInterval = NULL;

+    }

+}

+

+

+

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

+//****               Platform implementation functions                ****

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

+

+//========================================================================

+// _glfwPlatformOpenWindow() - Here is where the window is created, and

+// the OpenGL rendering context is created

+//========================================================================

+

+int _glfwPlatformOpenWindow( int width, int height, int redbits,

+    int greenbits, int bluebits, int alphabits, int depthbits,

+    int stencilbits, int mode, _GLFWhints* hints )

+{

+    Colormap    cmap;

+    XSetWindowAttributes wa;

+    XEvent      event;

+    Atom protocols[2];

+

+    // Clear platform specific GLFW window state

+    _glfwWin.VI               = NULL;

+    _glfwWin.CX               = (GLXContext)0;

+    _glfwWin.Win              = (Window)0;

+    _glfwWin.Hints            = NULL;

+    _glfwWin.PointerGrabbed   = GL_FALSE;

+    _glfwWin.KeyboardGrabbed  = GL_FALSE;

+    _glfwWin.OverrideRedirect = GL_FALSE;

+    _glfwWin.FS.ModeChanged   = GL_FALSE;

+    _glfwWin.Saver.Changed    = GL_FALSE;

+    _glfwWin.RefreshRate      = hints->RefreshRate;

+

+    // Fullscreen & screen saver settings

+    // Check if GLX is supported on this display

+    if( !glXQueryExtension( _glfwLibrary.Dpy, NULL, NULL ) )

+    {

+        _glfwPlatformCloseWindow();

+        return GL_FALSE;

+    }

+

+    // Get screen ID for this window

+    _glfwWin.Scrn = _glfwLibrary.DefaultScreen;

+

+    // Get an appropriate visual

+    _glfwWin.VI = _glfwChooseVisual( _glfwLibrary.Dpy,

+                                     _glfwWin.Scrn,

+                                     redbits, greenbits, bluebits,

+                                     alphabits, depthbits, stencilbits,

+                                     hints->AccumRedBits, hints->AccumGreenBits,

+                                     hints->AccumBlueBits, hints->AccumAlphaBits,

+                                     hints->AuxBuffers, hints->Samples, hints->Stereo );

+    if( _glfwWin.VI == NULL )

+    {

+        _glfwPlatformCloseWindow();

+        return GL_FALSE;

+    }

+

+    // Create a GLX context

+    _glfwWin.CX = glXCreateContext( _glfwLibrary.Dpy, _glfwWin.VI, 0, GL_TRUE );

+    if( _glfwWin.CX == NULL )

+    {

+        _glfwPlatformCloseWindow();

+        return GL_FALSE;

+    }

+

+    // Create a colormap

+    cmap = XCreateColormap( _glfwLibrary.Dpy, RootWindow( _glfwLibrary.Dpy,

+               _glfwWin.VI->screen), _glfwWin.VI->visual, AllocNone );

+

+    // Do we want fullscreen?

+    if( mode == GLFW_FULLSCREEN )

+    {

+        // Change video mode

+        _glfwSetVideoMode( _glfwWin.Scrn, &_glfwWin.Width,

+                           &_glfwWin.Height, &_glfwWin.RefreshRate );

+

+        // Remember old screen saver settings

+        XGetScreenSaver( _glfwLibrary.Dpy, &_glfwWin.Saver.Timeout,

+                         &_glfwWin.Saver.Interval, &_glfwWin.Saver.Blanking,

+                         &_glfwWin.Saver.Exposure );

+

+        // Disable screen saver

+        XSetScreenSaver( _glfwLibrary.Dpy, 0, 0, DontPreferBlanking,

+                         DefaultExposures );

+    }

+

+    // Attributes for window

+    wa.colormap = cmap;

+    wa.border_pixel = 0;

+    wa.event_mask = StructureNotifyMask | KeyPressMask | KeyReleaseMask |

+        PointerMotionMask | ButtonPressMask | ButtonReleaseMask |

+        ExposureMask | FocusChangeMask | VisibilityChangeMask;

+

+    // Create a window

+    _glfwWin.Win = XCreateWindow(

+        _glfwLibrary.Dpy,

+        RootWindow( _glfwLibrary.Dpy, _glfwWin.VI->screen ),

+        0, 0,                            // Upper left corner

+        _glfwWin.Width, _glfwWin.Height, // Width, height

+        0,                               // Borderwidth

+        _glfwWin.VI->depth,              // Depth

+        InputOutput,

+        _glfwWin.VI->visual,

+        CWBorderPixel | CWColormap | CWEventMask,

+        &wa

+    );

+    if( !_glfwWin.Win )

+    {

+        _glfwPlatformCloseWindow();

+        return GL_FALSE;

+    }

+

+    // Get the delete window WM protocol atom

+    _glfwWin.WMDeleteWindow = XInternAtom( _glfwLibrary.Dpy,

+                                           "WM_DELETE_WINDOW",

+                                           False );

+

+    // Get the ping WM protocol atom

+    _glfwWin.WMPing = XInternAtom( _glfwLibrary.Dpy, "_NET_WM_PING", False );

+

+    protocols[0] = _glfwWin.WMDeleteWindow;

+    protocols[1] = _glfwWin.WMPing;

+

+    // Allow us to trap the Window Close protocol

+    XSetWMProtocols( _glfwLibrary.Dpy, _glfwWin.Win, protocols,

+                     sizeof(protocols) / sizeof(Atom) );

+

+    // Remove window decorations for fullscreen windows

+    if( mode == GLFW_FULLSCREEN )

+    {

+        _glfwDisableDecorations();

+    }

+

+    _glfwWin.Hints = XAllocSizeHints();

+

+    if( hints->WindowNoResize )

+    {

+	_glfwWin.Hints->flags |= (PMinSize | PMaxSize);

+        _glfwWin.Hints->min_width = _glfwWin.Hints->max_width = _glfwWin.Width;

+        _glfwWin.Hints->min_height = _glfwWin.Hints->max_height = _glfwWin.Height;

+    }

+

+    if( mode == GLFW_FULLSCREEN )

+    {

+	_glfwWin.Hints->flags |= PPosition;

+	_glfwWin.Hints->x = 0;

+	_glfwWin.Hints->y = 0;

+    }

+

+    XSetWMNormalHints( _glfwLibrary.Dpy, _glfwWin.Win, _glfwWin.Hints );

+

+    // Map window

+    XMapWindow( _glfwLibrary.Dpy, _glfwWin.Win );

+

+    // Wait for map notification

+    XIfEvent( _glfwLibrary.Dpy, &event, _glfwWaitForMapNotify,

+              (char*)_glfwWin.Win );

+

+    // Make sure that our window ends up on top of things

+    XRaiseWindow( _glfwLibrary.Dpy, _glfwWin.Win );

+

+    // Fullscreen mode "post processing"

+    if( mode == GLFW_FULLSCREEN )

+    {

+#if defined( _GLFW_HAS_XRANDR )

+	// Request screen change notifications

+	if( _glfwLibrary.XRandR.Available )

+	{

+	    XRRSelectInput( _glfwLibrary.Dpy,

+	                    _glfwWin.Win,

+			    RRScreenChangeNotifyMask );

+	}

+#endif

+

+        // Force window position/size (some WMs do their own window

+        // geometry, which we want to override)

+        XMoveWindow( _glfwLibrary.Dpy, _glfwWin.Win, 0, 0 );

+        XResizeWindow( _glfwLibrary.Dpy, _glfwWin.Win, _glfwWin.Width,

+                       _glfwWin.Height );

+

+        // Grab keyboard

+        if( XGrabKeyboard( _glfwLibrary.Dpy, _glfwWin.Win, True,

+                           GrabModeAsync, GrabModeAsync, CurrentTime ) ==

+            GrabSuccess )

+        {

+            _glfwWin.KeyboardGrabbed = GL_TRUE;

+        }

+

+        // Grab mouse cursor

+        if( XGrabPointer( _glfwLibrary.Dpy, _glfwWin.Win, True,

+                          ButtonPressMask | ButtonReleaseMask |

+                          PointerMotionMask, GrabModeAsync, GrabModeAsync,

+                          _glfwWin.Win, None, CurrentTime ) ==

+            GrabSuccess )

+        {

+            _glfwWin.PointerGrabbed = GL_TRUE;

+        }

+

+        // Try to get window inside viewport (for virtual displays) by

+        // moving the mouse cursor to the upper left corner (and then to

+        // the center) - this works for XFree86

+        XWarpPointer( _glfwLibrary.Dpy, None, _glfwWin.Win, 0,0,0,0, 0,0 );

+        XWarpPointer( _glfwLibrary.Dpy, None, _glfwWin.Win, 0,0,0,0,

+                      _glfwWin.Width/2, _glfwWin.Height/2 );

+    }

+

+    // Set window & icon name

+    _glfwPlatformSetWindowTitle( "GLFW Window" );

+

+    // Connect the context to the window

+    glXMakeCurrent( _glfwLibrary.Dpy, _glfwWin.Win, _glfwWin.CX );

+

+    // Start by clearing the front buffer to black (avoid ugly desktop

+    // remains in our OpenGL window)

+    glClear( GL_COLOR_BUFFER_BIT );

+    glXSwapBuffers( _glfwLibrary.Dpy, _glfwWin.Win );

+

+    // Initialize GLX-specific OpenGL extensions

+    _glfwInitGLXExtensions();

+

+    return GL_TRUE;

+}

+

+

+//========================================================================

+// Properly kill the window/video display

+//========================================================================

+

+void _glfwPlatformCloseWindow( void )

+{

+#if defined( _GLFW_HAS_XRANDR )

+    XRRScreenConfiguration *sc;

+    Window root;

+#endif

+

+    // Free WM size hints

+    if( _glfwWin.Hints )

+    {

+	XFree( _glfwWin.Hints );

+	_glfwWin.Hints = NULL;

+    }

+

+    // Do we have a rendering context?

+    if( _glfwWin.CX )

+    {

+        // Release the context

+        glXMakeCurrent( _glfwLibrary.Dpy, None, NULL );

+

+        // Delete the context

+        glXDestroyContext( _glfwLibrary.Dpy, _glfwWin.CX );

+        _glfwWin.CX = NULL;

+    }

+

+    // Ungrab pointer and/or keyboard?

+    if( _glfwWin.KeyboardGrabbed )

+    {

+        XUngrabKeyboard( _glfwLibrary.Dpy, CurrentTime );

+        _glfwWin.KeyboardGrabbed = GL_FALSE;

+    }

+    if( _glfwWin.PointerGrabbed )

+    {

+        XUngrabPointer( _glfwLibrary.Dpy, CurrentTime );

+        _glfwWin.PointerGrabbed = GL_FALSE;

+    }

+

+    // Do we have a window?

+    if( _glfwWin.Win )

+    {

+        // Unmap the window

+        XUnmapWindow( _glfwLibrary.Dpy, _glfwWin.Win );

+

+        // Destroy the window

+        XDestroyWindow( _glfwLibrary.Dpy, _glfwWin.Win );

+        _glfwWin.Win = (Window) 0;

+    }

+

+    // Did we change the fullscreen resolution?

+    if( _glfwWin.FS.ModeChanged )

+    {

+#if defined( _GLFW_HAS_XRANDR )

+	if( _glfwLibrary.XRandR.Available )

+	{

+	    root = RootWindow( _glfwLibrary.Dpy, _glfwWin.Scrn );

+	    sc = XRRGetScreenInfo( _glfwLibrary.Dpy, root );

+

+	    XRRSetScreenConfig( _glfwLibrary.Dpy,

+	                        sc,

+				root,

+			        _glfwWin.FS.OldSizeID,

+				_glfwWin.FS.OldRotation,

+				CurrentTime );

+

+	    XRRFreeScreenConfigInfo( sc );

+	}

+#elif defined( _GLFW_HAS_XF86VIDMODE )

+        if( _glfwLibrary.XF86VidMode.Available )

+        {

+            // Unlock mode switch

+            XF86VidModeLockModeSwitch( _glfwLibrary.Dpy,

+                                       _glfwWin.Scrn,

+                                       0 );

+

+            // Change the video mode back to the old mode

+            XF86VidModeSwitchToMode( _glfwLibrary.Dpy,

+                _glfwWin.Scrn, &_glfwWin.FS.OldMode );

+        }

+#endif

+        _glfwWin.FS.ModeChanged = GL_FALSE;

+    }

+

+    // Did we change the screen saver setting?

+    if( _glfwWin.Saver.Changed )

+    {

+        // Restore old screen saver settings

+        XSetScreenSaver( _glfwLibrary.Dpy, _glfwWin.Saver.Timeout,

+                         _glfwWin.Saver.Interval, _glfwWin.Saver.Blanking,

+                         _glfwWin.Saver.Exposure );

+        _glfwWin.Saver.Changed = GL_FALSE;

+    }

+

+    XSync( _glfwLibrary.Dpy, True );

+}

+

+

+//========================================================================

+// _glfwPlatformSetWindowTitle() - Set the window title.

+//========================================================================

+

+void _glfwPlatformSetWindowTitle( const char *title )

+{

+    // Set window & icon title

+    XStoreName( _glfwLibrary.Dpy, _glfwWin.Win, title );

+    XSetIconName( _glfwLibrary.Dpy, _glfwWin.Win, title );

+}

+

+

+//========================================================================

+// _glfwPlatformSetWindowSize() - Set the window size.

+//========================================================================

+

+void _glfwPlatformSetWindowSize( int width, int height )

+{

+    int     mode = 0, rate, sizechanged = GL_FALSE;

+    GLint   drawbuffer;

+    GLfloat clearcolor[4];

+

+    rate = _glfwWin.RefreshRate;

+

+    // If we are in fullscreen mode, get some info about the current mode

+    if( _glfwWin.Fullscreen )

+    {

+        // Get closest match for target video mode

+        mode = _glfwGetClosestVideoMode( _glfwWin.Scrn, &width, &height, &rate );

+    }

+

+    if( _glfwWin.WindowNoResize )

+    {

+        _glfwWin.Hints->min_width = _glfwWin.Hints->max_width = width;

+        _glfwWin.Hints->min_height = _glfwWin.Hints->max_height = height;

+    }

+

+    XSetWMNormalHints( _glfwLibrary.Dpy, _glfwWin.Win, _glfwWin.Hints );

+

+    // Change window size before changing fullscreen mode?

+    if( _glfwWin.Fullscreen && (width > _glfwWin.Width) )

+    {

+        XResizeWindow( _glfwLibrary.Dpy, _glfwWin.Win, width, height );

+        sizechanged = GL_TRUE;

+    }

+

+    // Change fullscreen video mode?

+    if( _glfwWin.Fullscreen )

+    {

+        // Change video mode (keeping current rate)

+        _glfwSetVideoModeMODE( _glfwWin.Scrn, mode, _glfwWin.RefreshRate );

+

+        // Clear the front buffer to black (avoid ugly desktop remains in

+        // our OpenGL window)

+        glGetIntegerv( GL_DRAW_BUFFER, &drawbuffer );

+        glGetFloatv( GL_COLOR_CLEAR_VALUE, clearcolor );

+        glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );

+        glClear( GL_COLOR_BUFFER_BIT );

+        if( drawbuffer == GL_BACK )

+        {

+            glXSwapBuffers( _glfwLibrary.Dpy, _glfwWin.Win );

+        }

+        glClearColor( clearcolor[0], clearcolor[1], clearcolor[2],

+                      clearcolor[3] );

+    }

+

+    // Set window size (if not already changed)

+    if( !sizechanged )

+    {

+        XResizeWindow( _glfwLibrary.Dpy, _glfwWin.Win, width, height );

+    }

+}

+

+

+//========================================================================

+// _glfwPlatformSetWindowPos() - Set the window position.

+//========================================================================

+

+void _glfwPlatformSetWindowPos( int x, int y )

+{

+    // Set window position

+    XMoveWindow( _glfwLibrary.Dpy, _glfwWin.Win, x, y );

+}

+

+

+//========================================================================

+// _glfwPlatformIconfyWindow() - Window iconification

+//========================================================================

+

+void _glfwPlatformIconifyWindow( void )

+{

+    // We can't do this for override redirect windows

+    if( _glfwWin.OverrideRedirect )

+    {

+        return;

+    }

+

+    // In fullscreen mode, we need to restore the desktop video mode

+    if( _glfwWin.Fullscreen )

+    {

+#if defined( _GLFW_HAS_XF86VIDMODE )

+        if( _glfwLibrary.XF86VidMode.Available )

+        {

+            // Unlock mode switch

+            XF86VidModeLockModeSwitch( _glfwLibrary.Dpy,

+                                       _glfwWin.Scrn,

+                                       0 );

+

+            // Change the video mode back to the old mode

+            XF86VidModeSwitchToMode( _glfwLibrary.Dpy,

+                _glfwWin.Scrn, &_glfwWin.FS.OldMode );

+        }

+#endif

+        _glfwWin.FS.ModeChanged = GL_FALSE;

+    }

+

+    // Show mouse pointer

+    if( _glfwWin.PointerHidden )

+    {

+        XUndefineCursor( _glfwLibrary.Dpy, _glfwWin.Win );

+        _glfwWin.PointerHidden = GL_FALSE;

+    }

+

+    // Un-grab mouse pointer

+    if( _glfwWin.PointerGrabbed )

+    {

+        XUngrabPointer( _glfwLibrary.Dpy, CurrentTime );

+        _glfwWin.PointerGrabbed = GL_FALSE;

+    }

+

+    // Iconify window

+    XIconifyWindow( _glfwLibrary.Dpy, _glfwWin.Win,

+                    _glfwWin.Scrn );

+

+    // Window is now iconified

+    _glfwWin.Iconified = GL_TRUE;

+}

+

+

+//========================================================================

+// Window un-iconification

+//========================================================================

+

+void _glfwPlatformRestoreWindow( void )

+{

+    // We can't do this for override redirect windows

+    if( _glfwWin.OverrideRedirect )

+    {

+        return;

+    }

+

+    // In fullscreen mode, change back video mode to user selected mode

+    if( _glfwWin.Fullscreen )

+    {

+        _glfwSetVideoMode( _glfwWin.Scrn,

+	                   &_glfwWin.Width, &_glfwWin.Height, &_glfwWin.RefreshRate );

+    }

+

+    // Un-iconify window

+    XMapWindow( _glfwLibrary.Dpy, _glfwWin.Win );

+

+    // In fullscreen mode...

+    if( _glfwWin.Fullscreen )

+    {

+        // Make sure window is in upper left corner

+        XMoveWindow( _glfwLibrary.Dpy, _glfwWin.Win, 0, 0 );

+

+        // Get input focus

+        XSetInputFocus( _glfwLibrary.Dpy, _glfwWin.Win, RevertToParent,

+                        CurrentTime );

+    }

+

+    // Lock mouse, if necessary

+    if( _glfwWin.MouseLock )

+    {

+        // Hide cursor

+        if( !_glfwWin.PointerHidden )

+        {

+            XDefineCursor( _glfwLibrary.Dpy, _glfwWin.Win,

+                           _glfwCreateNULLCursor( _glfwLibrary.Dpy,

+                                                  _glfwWin.Win ) );

+            _glfwWin.PointerHidden = GL_TRUE;

+        }

+

+        // Grab cursor

+        if( !_glfwWin.PointerGrabbed )

+        {

+            if( XGrabPointer( _glfwLibrary.Dpy, _glfwWin.Win, True,

+                              ButtonPressMask | ButtonReleaseMask |

+                              PointerMotionMask, GrabModeAsync,

+                              GrabModeAsync, _glfwWin.Win, None,

+                              CurrentTime ) == GrabSuccess )

+            {

+                _glfwWin.PointerGrabbed = GL_TRUE;

+            }

+        }

+    }

+

+    // Window is no longer iconified

+    _glfwWin.Iconified = GL_FALSE;

+}

+

+

+//========================================================================

+// _glfwPlatformSwapBuffers() - Swap buffers (double-buffering) and poll

+// any new events.

+//========================================================================

+

+void _glfwPlatformSwapBuffers( void )

+{

+    // Update display-buffer

+    glXSwapBuffers( _glfwLibrary.Dpy, _glfwWin.Win );

+}

+

+

+//========================================================================

+// _glfwPlatformSwapInterval() - Set double buffering swap interval

+//========================================================================

+

+void _glfwPlatformSwapInterval( int interval )

+{

+    if( _glfwWin.SwapInterval )

+    {

+        _glfwWin.SwapInterval( interval );

+    }

+}

+

+

+//========================================================================

+// _glfwPlatformRefreshWindowParams()

+//========================================================================

+

+void _glfwPlatformRefreshWindowParams( void )

+{

+#if defined( _GLFW_HAS_XRANDR )

+    XRRScreenConfiguration *sc;

+#elif defined( _GLFW_HAS_XF86VIDMODE )

+    XF86VidModeModeLine modeline;

+    int dotclock;

+    float pixels_per_second, pixels_per_frame;

+#endif

+    int sample_buffers;

+

+    // AFAIK, there is no easy/sure way of knowing if OpenGL is hardware

+    // accelerated

+    _glfwWin.Accelerated = GL_TRUE;

+

+    // "Standard" window parameters

+    glXGetConfig( _glfwLibrary.Dpy, _glfwWin.VI, GLX_RED_SIZE,

+                  &_glfwWin.RedBits );

+    glXGetConfig( _glfwLibrary.Dpy, _glfwWin.VI, GLX_GREEN_SIZE,

+                  &_glfwWin.GreenBits );

+    glXGetConfig( _glfwLibrary.Dpy, _glfwWin.VI, GLX_BLUE_SIZE,

+                  &_glfwWin.BlueBits );

+    glXGetConfig( _glfwLibrary.Dpy, _glfwWin.VI, GLX_ALPHA_SIZE,

+                  &_glfwWin.AlphaBits );

+    glXGetConfig( _glfwLibrary.Dpy, _glfwWin.VI, GLX_DEPTH_SIZE,

+                  &_glfwWin.DepthBits );

+    glXGetConfig( _glfwLibrary.Dpy, _glfwWin.VI, GLX_STENCIL_SIZE,

+                  &_glfwWin.StencilBits );

+    glXGetConfig( _glfwLibrary.Dpy, _glfwWin.VI, GLX_ACCUM_RED_SIZE,

+                  &_glfwWin.AccumRedBits );

+    glXGetConfig( _glfwLibrary.Dpy, _glfwWin.VI, GLX_ACCUM_GREEN_SIZE,

+                  &_glfwWin.AccumGreenBits );

+    glXGetConfig( _glfwLibrary.Dpy, _glfwWin.VI, GLX_ACCUM_BLUE_SIZE,

+                  &_glfwWin.AccumBlueBits );

+    glXGetConfig( _glfwLibrary.Dpy, _glfwWin.VI, GLX_ACCUM_ALPHA_SIZE,

+                  &_glfwWin.AccumAlphaBits );

+    glXGetConfig( _glfwLibrary.Dpy, _glfwWin.VI, GLX_AUX_BUFFERS,

+                  &_glfwWin.AuxBuffers );

+

+    // Get stereo rendering setting

+    glXGetConfig( _glfwLibrary.Dpy, _glfwWin.VI, GLX_STEREO,

+                  &_glfwWin.Stereo );

+    _glfwWin.Stereo = _glfwWin.Stereo ? 1 : 0;

+

+    // Get multisample buffer samples

+    glXGetConfig( _glfwLibrary.Dpy, _glfwWin.VI, GLX_SAMPLES,

+		  &_glfwWin.Samples );

+    glXGetConfig( _glfwLibrary.Dpy, _glfwWin.VI, GLX_SAMPLE_BUFFERS, 

+		  &sample_buffers );

+    if( sample_buffers == 0 )

+      _glfwWin.Samples = 0;

+    

+    // Default to refresh rate unknown (=0 according to GLFW spec)

+    _glfwWin.RefreshRate = 0;

+		  

+    // Retrieve refresh rate, if possible

+#if defined( _GLFW_HAS_XRANDR )

+    if( _glfwLibrary.XRandR.Available )

+    {

+	sc = XRRGetScreenInfo( _glfwLibrary.Dpy,

+	                       RootWindow( _glfwLibrary.Dpy, _glfwWin.Scrn ) );

+	_glfwWin.RefreshRate = XRRConfigCurrentRate( sc );

+	XRRFreeScreenConfigInfo( sc );

+    }

+#elif defined( _GLFW_HAS_XF86VIDMODE )

+    if( _glfwLibrary.XF86VidMode.Available )

+    {

+        // Use the XF86VidMode extension to get current video mode

+        XF86VidModeGetModeLine( _glfwLibrary.Dpy, _glfwWin.Scrn,

+                                &dotclock, &modeline );

+        pixels_per_second = 1000.0f * (float) dotclock;

+        pixels_per_frame  = (float) modeline.htotal * modeline.vtotal;

+        _glfwWin.RefreshRate = (int)(pixels_per_second/pixels_per_frame+0.5);

+    }

+#endif

+}

+

+

+//========================================================================

+// _glfwPlatformPollEvents() - Poll for new window and input events

+//========================================================================

+

+void _glfwPlatformPollEvents( void )

+{

+    int winclosed = GL_FALSE;

+

+    // Flag that the cursor has not moved

+    _glfwInput.MouseMoved = GL_FALSE;

+

+    // Clear MapNotify and FocusIn counts

+    _glfwWin.MapNotifyCount = 0;

+    _glfwWin.FocusInCount = 0;

+

+    // Use XSync to synchronise events to the X display.

+    // I don't know if this can have a serious performance impact. My

+    // benchmarks with a GeForce card under Linux shows no difference with

+    // or without XSync, but when the GL window is rendered over a slow

+    // network I have noticed bad event syncronisation problems when XSync

+    // is not used, so I decided to use it.

+    XSync( _glfwLibrary.Dpy, False );

+

+    // Empty the window event queue

+    while( XPending( _glfwLibrary.Dpy ) )

+    {

+        if( _glfwGetNextEvent() )

+        {

+            winclosed = GL_TRUE;

+        }

+    }

+

+    // Did we get mouse movement in locked cursor mode?

+    if( _glfwInput.MouseMoved && _glfwWin.MouseLock )

+    {

+        int maxx, minx, maxy, miny;

+

+        // Calculate movement threshold

+        minx = _glfwWin.Width / 4;

+        maxx = (_glfwWin.Width * 3) / 4;

+        miny = _glfwWin.Height / 4;

+        maxy = (_glfwWin.Height * 3) / 4;

+

+        // Did the mouse cursor move beyond our movement threshold

+        if(_glfwInput.CursorPosX < minx || _glfwInput.CursorPosX > maxx ||

+           _glfwInput.CursorPosY < miny || _glfwInput.CursorPosY > maxy)

+        {

+            // Move the mouse pointer back to the window center so that it

+            // does not wander off...

+            _glfwPlatformSetMouseCursorPos( _glfwWin.Width/2,

+                                            _glfwWin.Height/2 );

+            XSync( _glfwLibrary.Dpy, False );

+        }

+    }

+

+    // Was the window (un)iconified?

+    if( _glfwWin.MapNotifyCount < 0 && !_glfwWin.Iconified )

+    {

+        // Show mouse pointer

+        if( _glfwWin.PointerHidden )

+        {

+            XUndefineCursor( _glfwLibrary.Dpy, _glfwWin.Win );

+            _glfwWin.PointerHidden = GL_FALSE;

+        }

+

+        // Un-grab mouse pointer

+        if( _glfwWin.PointerGrabbed )

+        {

+            XUngrabPointer( _glfwLibrary.Dpy, CurrentTime );

+            _glfwWin.PointerGrabbed = GL_FALSE;

+        }

+

+        _glfwWin.Iconified = GL_TRUE;

+    }

+    else if( _glfwWin.MapNotifyCount > 0 && _glfwWin.Iconified )

+    {

+        // Restore fullscreen mode properties

+        if( _glfwWin.Fullscreen )

+        {

+            // Change back video mode to user selected mode

+            _glfwSetVideoMode( _glfwWin.Scrn, &_glfwWin.Width,

+                               &_glfwWin.Height, &_glfwWin.RefreshRate );

+

+            // Disable window manager decorations

+            _glfwEnableDecorations();

+

+            // Make sure window is in upper left corner

+            XMoveWindow( _glfwLibrary.Dpy, _glfwWin.Win, 0, 0 );

+

+            // Get input focus

+            XSetInputFocus( _glfwLibrary.Dpy, _glfwWin.Win,

+                            RevertToParent, CurrentTime );

+        }

+

+        // Hide cursor if necessary

+        if( _glfwWin.MouseLock && !_glfwWin.PointerHidden )

+        {

+            if( !_glfwWin.PointerHidden )

+            {

+                XDefineCursor( _glfwLibrary.Dpy, _glfwWin.Win,

+                    _glfwCreateNULLCursor( _glfwLibrary.Dpy,

+                                           _glfwWin.Win ) );

+                _glfwWin.PointerHidden = GL_TRUE;

+            }

+        }

+

+        // Grab cursor if necessary

+        if( (_glfwWin.MouseLock || _glfwWin.Fullscreen) &&

+            !_glfwWin.PointerGrabbed )

+        {

+            if( XGrabPointer( _glfwLibrary.Dpy, _glfwWin.Win, True,

+                    ButtonPressMask | ButtonReleaseMask |

+                    PointerMotionMask, GrabModeAsync,

+                    GrabModeAsync, _glfwWin.Win, None,

+                    CurrentTime ) == GrabSuccess )

+            {

+                _glfwWin.PointerGrabbed = GL_TRUE;

+            }

+        }

+

+        _glfwWin.Iconified = GL_FALSE;

+    }

+

+    // Did the window get/lose focus

+    if( _glfwWin.FocusInCount > 0 && !_glfwWin.Active )

+    {

+        // If we are in fullscreen mode, restore window

+        if( _glfwWin.Fullscreen && _glfwWin.Iconified )

+        {

+            _glfwPlatformRestoreWindow();

+        }

+

+        // Window is now active

+        _glfwWin.Active = GL_TRUE;

+    }

+    else if( _glfwWin.FocusInCount < 0 && _glfwWin.Active )

+    {

+        // If we are in fullscreen mode, iconfify window

+        if( _glfwWin.Fullscreen )

+        {

+            _glfwPlatformIconifyWindow();

+        }

+

+        // Window is not active

+        _glfwWin.Active = GL_FALSE;

+	_glfwInputDeactivation();

+    }

+

+    // Was there a window close request?

+    if( winclosed && _glfwWin.WindowCloseCallback )

+    {

+        // Check if the program wants us to close the window

+        winclosed = _glfwWin.WindowCloseCallback();

+    }

+    if( winclosed )

+    {

+        glfwCloseWindow();

+    }

+}

+

+

+//========================================================================

+// _glfwPlatformWaitEvents() - Wait for new window and input events

+//========================================================================

+

+void _glfwPlatformWaitEvents( void )

+{

+    XEvent event;

+

+    // Wait for new events (blocking)

+    XNextEvent( _glfwLibrary.Dpy, &event );

+    XPutBackEvent( _glfwLibrary.Dpy, &event );

+

+    // Poll events from queue

+    _glfwPlatformPollEvents();

+}

+

+

+//========================================================================

+// _glfwPlatformHideMouseCursor() - Hide mouse cursor (lock it)

+//========================================================================

+

+void _glfwPlatformHideMouseCursor( void )

+{

+    // Hide cursor

+    if( !_glfwWin.PointerHidden )

+    {

+        XDefineCursor( _glfwLibrary.Dpy, _glfwWin.Win,

+                       _glfwCreateNULLCursor( _glfwLibrary.Dpy,

+                                              _glfwWin.Win ) );

+        _glfwWin.PointerHidden = GL_TRUE;

+    }

+

+    // Grab cursor to user window

+    if( !_glfwWin.PointerGrabbed )

+    {

+        if( XGrabPointer( _glfwLibrary.Dpy, _glfwWin.Win, True,

+                          ButtonPressMask | ButtonReleaseMask |

+                          PointerMotionMask, GrabModeAsync, GrabModeAsync,

+                          _glfwWin.Win, None, CurrentTime ) ==

+            GrabSuccess )

+        {

+            _glfwWin.PointerGrabbed = GL_TRUE;

+        }

+    }

+}

+

+

+//========================================================================

+// _glfwPlatformShowMouseCursor() - Show mouse cursor (unlock it)

+//========================================================================

+

+void _glfwPlatformShowMouseCursor( void )

+{

+    // Un-grab cursor (only in windowed mode: in fullscreen mode we still

+    // want the mouse grabbed in order to confine the cursor to the window

+    // area)

+    if( _glfwWin.PointerGrabbed && !_glfwWin.Fullscreen )

+    {

+        XUngrabPointer( _glfwLibrary.Dpy, CurrentTime );

+        _glfwWin.PointerGrabbed = GL_FALSE;

+    }

+

+    // Show cursor

+    if( _glfwWin.PointerHidden )

+    {

+        XUndefineCursor( _glfwLibrary.Dpy, _glfwWin.Win );

+        _glfwWin.PointerHidden = GL_FALSE;

+    }

+}

+

+

+//========================================================================

+// _glfwPlatformSetMouseCursorPos() - Set physical mouse cursor position

+//========================================================================

+

+void _glfwPlatformSetMouseCursorPos( int x, int y )

+{

+    // Change cursor position

+    _glfwInput.CursorPosX = x;

+    _glfwInput.CursorPosY = y;

+    XWarpPointer( _glfwLibrary.Dpy, None, _glfwWin.Win, 0,0,0,0, x, y );

+}

+

diff --git a/src/engine/external/important.txt b/src/engine/external/important.txt
new file mode 100644
index 00000000..305ccadc
--- /dev/null
+++ b/src/engine/external/important.txt
@@ -0,0 +1,5 @@
+The source code under this directory are external libraries
+with their own licences. The source you find here is stripped
+of unnessesary information. Please visit their websites for
+more information and official releases.
+
diff --git a/src/engine/external/pa.c b/src/engine/external/pa.c
new file mode 100644
index 00000000..a417e9db
--- /dev/null
+++ b/src/engine/external/pa.c
@@ -0,0 +1,40 @@
+/* Include the auto configuration */
+#include <engine/detect.h>
+
+/* common part */
+#include "portaudio/pa_converters.c"
+#include "portaudio/pa_trace.c"
+#include "portaudio/pa_front.c"
+#include "portaudio/pa_dither.c"
+#include "portaudio/pa_process.c"
+#include "portaudio/pa_stream.c"
+#include "portaudio/pa_cpuload.c"
+#include "portaudio/pa_allocation.c"
+#include "portaudio/pa_debugprint.c"
+
+#if defined(CONF_FAMILY_UNIX)
+	#include "portaudio/pa_unix_util.c"
+	#if defined(CONF_PLATFORM_MACOSX)
+		#define PA_USE_COREAUDIO
+		#include "portaudio/pa_mac_core.c"
+		#include "portaudio/pa_mac_core_blocking.c"
+		#include "portaudio/pa_mac_core_utilities.c"
+		#include "portaudio/pa_mac_hostapis.c"
+		#include "portaudio/pa_ringbuffer.c"
+	#else
+		#define HAVE_SYS_SOUNDCARD_H
+		#define PA_USE_ALSA
+		#include "portaudio/pa_linux_alsa.c"
+		//#include "portaudio/pa_unix_oss.c"
+		#include "portaudio/pa_unix_hostapis.c"
+	#endif
+#elif defined(CONF_FAMILY_WINDOWS)
+	#define PA_NO_WMME
+	#define PA_NO_ASIO
+	#include "portaudio/pa_win_ds.c"
+	#include "portaudio/pa_win_ds_dynlink.c"
+	#include "portaudio/pa_win_hostapis.c"
+	#include "portaudio/pa_win_util.c"
+#else
+	#error help me!
+#endif
diff --git a/src/engine/client/pnglite/pnglite.c b/src/engine/external/pnglite/pnglite.c
index b33f60ba..b33f60ba 100644
--- a/src/engine/client/pnglite/pnglite.c
+++ b/src/engine/external/pnglite/pnglite.c
diff --git a/src/engine/client/pnglite/pnglite.h b/src/engine/external/pnglite/pnglite.h
index f464c46b..f464c46b 100644
--- a/src/engine/client/pnglite/pnglite.h
+++ b/src/engine/external/pnglite/pnglite.h
diff --git a/src/engine/external/portaudio/changes.txt b/src/engine/external/portaudio/changes.txt
new file mode 100644
index 00000000..545e0311
--- /dev/null
+++ b/src/engine/external/portaudio/changes.txt
@@ -0,0 +1,3 @@
+Removed all functionallity from function PaOSX_FixVolumeScalars in pa_mac_core.c. This keeps OSX in control of the volume and muting.
+2007-05-13 - jdv
+
diff --git a/src/engine/external/portaudio/pa_allocation.c b/src/engine/external/portaudio/pa_allocation.c
new file mode 100644
index 00000000..35158073
--- /dev/null
+++ b/src/engine/external/portaudio/pa_allocation.c
@@ -0,0 +1,243 @@
+/*

+ * $Id: pa_allocation.c 1097 2006-08-26 08:27:53Z rossb $

+ * Portable Audio I/O Library allocation group implementation

+ * memory allocation group for tracking allocation groups

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup common_src

+

+ @brief Allocation Group implementation.

+*/

+

+

+#include "pa_allocation.h"

+#include "pa_util.h"

+

+

+/*

+    Maintain 3 singly linked lists...

+    linkBlocks: the buffers used to allocate the links

+    spareLinks: links available for use in the allocations list

+    allocations: the buffers currently allocated using PaUtil_ContextAllocateMemory()

+

+    Link block size is doubled every time new links are allocated.

+*/

+

+

+#define PA_INITIAL_LINK_COUNT_    16

+

+struct PaUtilAllocationGroupLink

+{

+    struct PaUtilAllocationGroupLink *next;

+    void *buffer;

+};

+

+/*

+    Allocate a block of links. The first link will have it's buffer member

+    pointing to the block, and it's next member set to <nextBlock>. The remaining

+    links will have NULL buffer members, and each link will point to

+    the next link except the last, which will point to <nextSpare>

+*/

+static struct PaUtilAllocationGroupLink *AllocateLinks( long count,

+        struct PaUtilAllocationGroupLink *nextBlock,

+        struct PaUtilAllocationGroupLink *nextSpare )

+{

+    struct PaUtilAllocationGroupLink *result;

+    int i;

+    

+    result = (struct PaUtilAllocationGroupLink *)PaUtil_AllocateMemory(

+            sizeof(struct PaUtilAllocationGroupLink) * count );

+    if( result )

+    {

+        /* the block link */

+        result[0].buffer = result;

+        result[0].next = nextBlock;

+

+        /* the spare links */

+        for( i=1; i<count; ++i )

+        {

+            result[i].buffer = 0;

+            result[i].next = &result[i+1];

+        }

+        result[count-1].next = nextSpare;

+    }

+    

+    return result;

+}

+

+

+PaUtilAllocationGroup* PaUtil_CreateAllocationGroup( void )

+{

+    PaUtilAllocationGroup* result = 0;

+    struct PaUtilAllocationGroupLink *links;

+

+

+    links = AllocateLinks( PA_INITIAL_LINK_COUNT_, 0, 0 );

+    if( links != 0 )

+    {

+        result = (PaUtilAllocationGroup*)PaUtil_AllocateMemory( sizeof(PaUtilAllocationGroup) );

+        if( result )

+        {

+            result->linkCount = PA_INITIAL_LINK_COUNT_;

+            result->linkBlocks = &links[0];

+            result->spareLinks = &links[1];

+            result->allocations = 0;

+        }

+        else

+        {

+            PaUtil_FreeMemory( links );

+        }

+    }

+

+    return result;

+}

+

+

+void PaUtil_DestroyAllocationGroup( PaUtilAllocationGroup* group )

+{

+    struct PaUtilAllocationGroupLink *current = group->linkBlocks;

+    struct PaUtilAllocationGroupLink *next;

+

+    while( current )

+    {

+        next = current->next;

+        PaUtil_FreeMemory( current->buffer );

+        current = next;

+    }

+

+    PaUtil_FreeMemory( group );

+}

+

+

+void* PaUtil_GroupAllocateMemory( PaUtilAllocationGroup* group, long size )

+{

+    struct PaUtilAllocationGroupLink *links, *link;

+    void *result = 0;

+    

+    /* allocate more links if necessary */

+    if( !group->spareLinks )

+    {

+        /* double the link count on each block allocation */

+        links = AllocateLinks( group->linkCount, group->linkBlocks, group->spareLinks );

+        if( links )

+        {

+            group->linkCount += group->linkCount;

+            group->linkBlocks = &links[0];

+            group->spareLinks = &links[1];

+        }

+    }

+

+    if( group->spareLinks )

+    {

+        result = PaUtil_AllocateMemory( size );

+        if( result )

+        {

+            link = group->spareLinks;

+            group->spareLinks = link->next;

+

+            link->buffer = result;

+            link->next = group->allocations;

+

+            group->allocations = link;

+        }

+    }

+

+    return result;    

+}

+

+

+void PaUtil_GroupFreeMemory( PaUtilAllocationGroup* group, void *buffer )

+{

+    struct PaUtilAllocationGroupLink *current = group->allocations;

+    struct PaUtilAllocationGroupLink *previous = 0;

+

+    if( buffer == 0 )

+        return;

+

+    /* find the right link and remove it */

+    while( current )

+    {

+        if( current->buffer == buffer )

+        {

+            if( previous )

+            {

+                previous->next = current->next;

+            }

+            else

+            {

+                group->allocations = current->next;

+            }

+

+            current->buffer = 0;

+            current->next = group->spareLinks;

+            group->spareLinks = current;

+

+            break;

+        }

+        

+        previous = current;

+        current = current->next;

+    }

+

+    PaUtil_FreeMemory( buffer ); /* free the memory whether we found it in the list or not */

+}

+

+

+void PaUtil_FreeAllAllocations( PaUtilAllocationGroup* group )

+{

+    struct PaUtilAllocationGroupLink *current = group->allocations;

+    struct PaUtilAllocationGroupLink *previous = 0;

+

+    /* free all buffers in the allocations list */

+    while( current )

+    {

+        PaUtil_FreeMemory( current->buffer );

+        current->buffer = 0;

+

+        previous = current;

+        current = current->next;

+    }

+

+    /* link the former allocations list onto the front of the spareLinks list */

+    if( previous )

+    {

+        previous->next = group->spareLinks;

+        group->spareLinks = group->allocations;

+        group->allocations = 0;

+    }

+}

+

diff --git a/src/engine/external/portaudio/pa_allocation.h b/src/engine/external/portaudio/pa_allocation.h
new file mode 100644
index 00000000..7df2cd95
--- /dev/null
+++ b/src/engine/external/portaudio/pa_allocation.h
@@ -0,0 +1,104 @@
+#ifndef PA_ALLOCATION_H

+#define PA_ALLOCATION_H

+/*

+ * $Id: pa_allocation.h 1097 2006-08-26 08:27:53Z rossb $

+ * Portable Audio I/O Library allocation context header

+ * memory allocation context for tracking allocation groups

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup common_src

+

+ @brief Allocation Group prototypes. An Allocation Group makes it easy to

+ allocate multiple blocks of memory and free them all simultanously.

+ 

+ An allocation group is useful for keeping track of multiple blocks

+ of memory which are allocated at the same time (such as during initialization)

+ and need to be deallocated at the same time. The allocation group maintains

+ a list of allocated blocks, and can deallocate them all simultaneously which

+ can be usefull for cleaning up after a partially initialized object fails.

+

+ The allocation group implementation is built on top of the lower

+ level allocation functions defined in pa_util.h

+*/

+

+

+#ifdef __cplusplus

+extern "C"

+{

+#endif /* __cplusplus */

+

+

+typedef struct

+{

+    long linkCount;

+    struct PaUtilAllocationGroupLink *linkBlocks;

+    struct PaUtilAllocationGroupLink *spareLinks;

+    struct PaUtilAllocationGroupLink *allocations;

+}PaUtilAllocationGroup;

+

+

+

+/** Create an allocation group.

+*/

+PaUtilAllocationGroup* PaUtil_CreateAllocationGroup( void );

+

+/** Destroy an allocation group, but not the memory allocated through the group.

+*/

+void PaUtil_DestroyAllocationGroup( PaUtilAllocationGroup* group );

+

+/** Allocate a block of memory though an allocation group.

+*/

+void* PaUtil_GroupAllocateMemory( PaUtilAllocationGroup* group, long size );

+

+/** Free a block of memory that was previously allocated though an allocation

+ group. Calling this function is a relatively time consuming operation.

+ Under normal circumstances clients should call PaUtil_FreeAllAllocations to

+ free all allocated blocks simultaneously.

+ @see PaUtil_FreeAllAllocations

+*/

+void PaUtil_GroupFreeMemory( PaUtilAllocationGroup* group, void *buffer );

+

+/** Free all blocks of memory which have been allocated through the allocation

+ group. This function doesn't destroy the group itself.

+*/

+void PaUtil_FreeAllAllocations( PaUtilAllocationGroup* group );

+

+

+#ifdef __cplusplus

+}

+#endif /* __cplusplus */

+#endif /* PA_ALLOCATION_H */

diff --git a/src/engine/external/portaudio/pa_converters.c b/src/engine/external/portaudio/pa_converters.c
new file mode 100644
index 00000000..1813aab2
--- /dev/null
+++ b/src/engine/external/portaudio/pa_converters.c
@@ -0,0 +1,1935 @@
+/*

+ * $Id: pa_converters.c 1097 2006-08-26 08:27:53Z rossb $

+ * Portable Audio I/O Library sample conversion mechanism

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Phil Burk, Ross Bencina

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup common_src

+

+ @brief Conversion functions implementations.

+ 

+ If the C9x function lrintf() is available, define PA_USE_C99_LRINTF to use it

+

+ @todo Consider whether functions which dither but don't clip should exist,

+ V18 automatically enabled clipping whenever dithering was selected. Perhaps

+ we should do the same.

+

+ @todo implement the converters marked IMPLEMENT ME: Float32_To_UInt8_Dither,

+ Float32_To_UInt8_Clip, Float32_To_UInt8_DitherClip, Int32_To_Int24_Dither,

+ Int32_To_UInt8_Dither, Int24_To_Int16_Dither, Int24_To_Int8_Dither, 

+ Int24_To_UInt8_Dither, Int16_To_Int8_Dither, Int16_To_UInt8_Dither,

+

+ @todo review the converters marked REVIEW: Float32_To_Int32,

+ Float32_To_Int32_Dither, Float32_To_Int32_Clip, Float32_To_Int32_DitherClip,

+ Int32_To_Int16_Dither, Int32_To_Int8_Dither, Int16_To_Int32

+*/

+

+

+#include "pa_converters.h"

+#include "pa_dither.h"

+#include "pa_endianness.h"

+#include "pa_types.h"

+

+

+PaSampleFormat PaUtil_SelectClosestAvailableFormat(

+        PaSampleFormat availableFormats, PaSampleFormat format )

+{

+    PaSampleFormat result;

+

+    format &= ~paNonInterleaved;

+    availableFormats &= ~paNonInterleaved;

+    

+    if( (format & availableFormats) == 0 )

+    {

+        /* NOTE: this code depends on the sample format constants being in

+            descending order of quality - ie best quality is 0

+            FIXME: should write an assert which checks that all of the

+            known constants conform to that requirement.

+        */

+

+        if( format != 0x01 )

+        {

+            /* scan for better formats */

+            result = format;

+            do

+            {

+                result >>= 1;

+            }

+            while( (result & availableFormats) == 0 && result != 0 );

+        }

+        else

+        {

+            result = 0;

+        }

+        

+        if( result == 0 ){

+            /* scan for worse formats */

+            result = format;

+            do

+            {

+                result <<= 1;

+            }

+            while( (result & availableFormats) == 0 && result != paCustomFormat );

+

+            if( (result & availableFormats) == 0 )

+                result = paSampleFormatNotSupported;

+        }

+        

+    }else{

+        result = format;

+    }

+

+    return result;

+}

+

+/* -------------------------------------------------------------------------- */

+

+#define PA_SELECT_FORMAT_( format, float32, int32, int24, int16, int8, uint8 ) \

+    switch( format & ~paNonInterleaved ){                                      \

+    case paFloat32:                                                            \

+        float32                                                                \

+    case paInt32:                                                              \

+        int32                                                                  \

+    case paInt24:                                                              \

+        int24                                                                  \

+    case paInt16:                                                              \

+        int16                                                                  \

+    case paInt8:                                                               \

+        int8                                                                   \

+    case paUInt8:                                                              \

+        uint8                                                                  \

+    default: return 0;                                                         \

+    }

+

+/* -------------------------------------------------------------------------- */

+

+#define PA_SELECT_CONVERTER_DITHER_CLIP_( flags, source, destination )         \

+    if( flags & paClipOff ){ /* no clip */                                     \

+        if( flags & paDitherOff ){ /* no dither */                             \

+            return paConverters. source ## _To_ ## destination;                \

+        }else{ /* dither */                                                    \

+            return paConverters. source ## _To_ ## destination ## _Dither;     \

+        }                                                                      \

+    }else{ /* clip */                                                          \

+        if( flags & paDitherOff ){ /* no dither */                             \

+            return paConverters. source ## _To_ ## destination ## _Clip;       \

+        }else{ /* dither */                                                    \

+            return paConverters. source ## _To_ ## destination ## _DitherClip; \

+        }                                                                      \

+    }

+

+/* -------------------------------------------------------------------------- */

+

+#define PA_SELECT_CONVERTER_DITHER_( flags, source, destination )              \

+    if( flags & paDitherOff ){ /* no dither */                                 \

+        return paConverters. source ## _To_ ## destination;                    \

+    }else{ /* dither */                                                        \

+        return paConverters. source ## _To_ ## destination ## _Dither;         \

+    }

+

+/* -------------------------------------------------------------------------- */

+

+#define PA_USE_CONVERTER_( source, destination )\

+    return paConverters. source ## _To_ ## destination;

+

+/* -------------------------------------------------------------------------- */

+

+#define PA_UNITY_CONVERSION_( wordlength )\

+    return paConverters. Copy_ ## wordlength ## _To_ ## wordlength;

+

+/* -------------------------------------------------------------------------- */

+

+PaUtilConverter* PaUtil_SelectConverter( PaSampleFormat sourceFormat,

+        PaSampleFormat destinationFormat, PaStreamFlags flags )

+{

+    PA_SELECT_FORMAT_( sourceFormat,

+                       /* paFloat32: */

+                       PA_SELECT_FORMAT_( destinationFormat,

+                                          /* paFloat32: */        PA_UNITY_CONVERSION_( 32 ),

+                                          /* paInt32: */          PA_SELECT_CONVERTER_DITHER_CLIP_( flags, Float32, Int32 ),

+                                          /* paInt24: */          PA_SELECT_CONVERTER_DITHER_CLIP_( flags, Float32, Int24 ),

+                                          /* paInt16: */          PA_SELECT_CONVERTER_DITHER_CLIP_( flags, Float32, Int16 ),

+                                          /* paInt8: */           PA_SELECT_CONVERTER_DITHER_CLIP_( flags, Float32, Int8 ),

+                                          /* paUInt8: */          PA_SELECT_CONVERTER_DITHER_CLIP_( flags, Float32, UInt8 )

+                                        ),

+                       /* paInt32: */

+                       PA_SELECT_FORMAT_( destinationFormat,

+                                          /* paFloat32: */        PA_USE_CONVERTER_( Int32, Float32 ),

+                                          /* paInt32: */          PA_UNITY_CONVERSION_( 32 ),

+                                          /* paInt24: */          PA_SELECT_CONVERTER_DITHER_( flags, Int32, Int24 ),

+                                          /* paInt16: */          PA_SELECT_CONVERTER_DITHER_( flags, Int32, Int16 ),

+                                          /* paInt8: */           PA_SELECT_CONVERTER_DITHER_( flags, Int32, Int8 ),

+                                          /* paUInt8: */          PA_SELECT_CONVERTER_DITHER_( flags, Int32, UInt8 )

+                                        ),

+                       /* paInt24: */

+                       PA_SELECT_FORMAT_( destinationFormat,

+                                          /* paFloat32: */        PA_USE_CONVERTER_( Int24, Float32 ),

+                                          /* paInt32: */          PA_USE_CONVERTER_( Int24, Int32 ),

+                                          /* paInt24: */          PA_UNITY_CONVERSION_( 24 ),

+                                          /* paInt16: */          PA_SELECT_CONVERTER_DITHER_( flags, Int24, Int16 ),

+                                          /* paInt8: */           PA_SELECT_CONVERTER_DITHER_( flags, Int24, Int8 ),

+                                          /* paUInt8: */          PA_SELECT_CONVERTER_DITHER_( flags, Int24, UInt8 )

+                                        ),

+                       /* paInt16: */

+                       PA_SELECT_FORMAT_( destinationFormat,

+                                          /* paFloat32: */        PA_USE_CONVERTER_( Int16, Float32 ),

+                                          /* paInt32: */          PA_USE_CONVERTER_( Int16, Int32 ),

+                                          /* paInt24: */          PA_USE_CONVERTER_( Int16, Int24 ),

+                                          /* paInt16: */          PA_UNITY_CONVERSION_( 16 ),

+                                          /* paInt8: */           PA_SELECT_CONVERTER_DITHER_( flags, Int16, Int8 ),

+                                          /* paUInt8: */          PA_SELECT_CONVERTER_DITHER_( flags, Int16, UInt8 )

+                                        ),

+                       /* paInt8: */

+                       PA_SELECT_FORMAT_( destinationFormat,

+                                          /* paFloat32: */        PA_USE_CONVERTER_( Int8, Float32 ),

+                                          /* paInt32: */          PA_USE_CONVERTER_( Int8, Int32 ),

+                                          /* paInt24: */          PA_USE_CONVERTER_( Int8, Int24 ),

+                                          /* paInt16: */          PA_USE_CONVERTER_( Int8, Int16 ),

+                                          /* paInt8: */           PA_UNITY_CONVERSION_( 8 ),

+                                          /* paUInt8: */          PA_USE_CONVERTER_( Int8, UInt8 )

+                                        ),

+                       /* paUInt8: */

+                       PA_SELECT_FORMAT_( destinationFormat,

+                                          /* paFloat32: */        PA_USE_CONVERTER_( UInt8, Float32 ),

+                                          /* paInt32: */          PA_USE_CONVERTER_( UInt8, Int32 ),

+                                          /* paInt24: */          PA_USE_CONVERTER_( UInt8, Int24 ),

+                                          /* paInt16: */          PA_USE_CONVERTER_( UInt8, Int16 ),

+                                          /* paInt8: */           PA_USE_CONVERTER_( UInt8, Int8 ),

+                                          /* paUInt8: */          PA_UNITY_CONVERSION_( 8 )

+                                        )

+                     )

+}

+

+/* -------------------------------------------------------------------------- */

+

+#ifdef PA_NO_STANDARD_CONVERTERS

+

+/* -------------------------------------------------------------------------- */

+

+PaUtilConverterTable paConverters = {

+    0, /* PaUtilConverter *Float32_To_Int32; */

+    0, /* PaUtilConverter *Float32_To_Int32_Dither; */

+    0, /* PaUtilConverter *Float32_To_Int32_Clip; */

+    0, /* PaUtilConverter *Float32_To_Int32_DitherClip; */

+

+    0, /* PaUtilConverter *Float32_To_Int24; */

+    0, /* PaUtilConverter *Float32_To_Int24_Dither; */

+    0, /* PaUtilConverter *Float32_To_Int24_Clip; */

+    0, /* PaUtilConverter *Float32_To_Int24_DitherClip; */

+

+    0, /* PaUtilConverter *Float32_To_Int16; */

+    0, /* PaUtilConverter *Float32_To_Int16_Dither; */

+    0, /* PaUtilConverter *Float32_To_Int16_Clip; */

+    0, /* PaUtilConverter *Float32_To_Int16_DitherClip; */

+

+    0, /* PaUtilConverter *Float32_To_Int8; */

+    0, /* PaUtilConverter *Float32_To_Int8_Dither; */

+    0, /* PaUtilConverter *Float32_To_Int8_Clip; */

+    0, /* PaUtilConverter *Float32_To_Int8_DitherClip; */

+

+    0, /* PaUtilConverter *Float32_To_UInt8; */

+    0, /* PaUtilConverter *Float32_To_UInt8_Dither; */

+    0, /* PaUtilConverter *Float32_To_UInt8_Clip; */

+    0, /* PaUtilConverter *Float32_To_UInt8_DitherClip; */

+

+    0, /* PaUtilConverter *Int32_To_Float32; */

+    0, /* PaUtilConverter *Int32_To_Int24; */

+    0, /* PaUtilConverter *Int32_To_Int24_Dither; */

+    0, /* PaUtilConverter *Int32_To_Int16; */

+    0, /* PaUtilConverter *Int32_To_Int16_Dither; */

+    0, /* PaUtilConverter *Int32_To_Int8; */

+    0, /* PaUtilConverter *Int32_To_Int8_Dither; */

+    0, /* PaUtilConverter *Int32_To_UInt8; */

+    0, /* PaUtilConverter *Int32_To_UInt8_Dither; */

+

+    0, /* PaUtilConverter *Int24_To_Float32; */

+    0, /* PaUtilConverter *Int24_To_Int32; */

+    0, /* PaUtilConverter *Int24_To_Int16; */

+    0, /* PaUtilConverter *Int24_To_Int16_Dither; */

+    0, /* PaUtilConverter *Int24_To_Int8; */

+    0, /* PaUtilConverter *Int24_To_Int8_Dither; */

+    0, /* PaUtilConverter *Int24_To_UInt8; */

+    0, /* PaUtilConverter *Int24_To_UInt8_Dither; */

+    

+    0, /* PaUtilConverter *Int16_To_Float32; */

+    0, /* PaUtilConverter *Int16_To_Int32; */

+    0, /* PaUtilConverter *Int16_To_Int24; */

+    0, /* PaUtilConverter *Int16_To_Int8; */

+    0, /* PaUtilConverter *Int16_To_Int8_Dither; */

+    0, /* PaUtilConverter *Int16_To_UInt8; */

+    0, /* PaUtilConverter *Int16_To_UInt8_Dither; */

+

+    0, /* PaUtilConverter *Int8_To_Float32; */

+    0, /* PaUtilConverter *Int8_To_Int32; */

+    0, /* PaUtilConverter *Int8_To_Int24 */

+    0, /* PaUtilConverter *Int8_To_Int16; */

+    0, /* PaUtilConverter *Int8_To_UInt8; */

+

+    0, /* PaUtilConverter *UInt8_To_Float32; */

+    0, /* PaUtilConverter *UInt8_To_Int32; */

+    0, /* PaUtilConverter *UInt8_To_Int24; */

+    0, /* PaUtilConverter *UInt8_To_Int16; */

+    0, /* PaUtilConverter *UInt8_To_Int8; */

+

+    0, /* PaUtilConverter *Copy_8_To_8; */

+    0, /* PaUtilConverter *Copy_16_To_16; */

+    0, /* PaUtilConverter *Copy_24_To_24; */

+    0  /* PaUtilConverter *Copy_32_To_32; */

+};

+

+/* -------------------------------------------------------------------------- */

+

+#else /* PA_NO_STANDARD_CONVERTERS is not defined */

+

+/* -------------------------------------------------------------------------- */

+

+#define PA_CLIP_( val, min, max )\

+    { val = ((val) < (min)) ? (min) : (((val) > (max)) ? (max) : (val)); }

+

+

+static const float const_1_div_128_ = 1.0f / 128.0f;  /* 8 bit multiplier */

+

+static const float const_1_div_32768_ = 1.0f / 32768.f; /* 16 bit multiplier */

+

+static const double const_1_div_2147483648_ = 1.0 / 2147483648.0; /* 32 bit multiplier */

+

+/* -------------------------------------------------------------------------- */

+

+static void Float32_To_Int32(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    float *src = (float*)sourceBuffer;

+    PaInt32 *dest =  (PaInt32*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        /* REVIEW */

+#ifdef PA_USE_C99_LRINTF

+        float scaled = *src * 0x7FFFFFFF;

+        *dest = lrintf(scaled-0.5f);

+#else

+        double scaled = *src * 0x7FFFFFFF;

+        *dest = (PaInt32) scaled;        

+#endif

+        

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Float32_To_Int32_Dither(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    float *src = (float*)sourceBuffer;

+    PaInt32 *dest =  (PaInt32*)destinationBuffer;

+

+    while( count-- )

+    {

+        /* REVIEW */

+#ifdef PA_USE_C99_LRINTF

+        float dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );

+        /* use smaller scaler to prevent overflow when we add the dither */

+        float dithered = ((float)*src * (2147483646.0f)) + dither;

+        *dest = lrintf(dithered - 0.5f);

+#else

+        double dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );

+        /* use smaller scaler to prevent overflow when we add the dither */

+        double dithered = ((double)*src * (2147483646.0)) + dither;

+        *dest = (PaInt32) dithered;

+#endif

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Float32_To_Int32_Clip(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    float *src = (float*)sourceBuffer;

+    PaInt32 *dest =  (PaInt32*)destinationBuffer;

+    (void) ditherGenerator; /* unused parameter */

+    

+    while( count-- )

+    {

+        /* REVIEW */

+#ifdef PA_USE_C99_LRINTF

+        float scaled = *src * 0x7FFFFFFF;

+        PA_CLIP_( scaled, -2147483648.f, 2147483647.f  );

+        *dest = lrintf(scaled-0.5f);

+#else

+        double scaled = *src * 0x7FFFFFFF;

+        PA_CLIP_( scaled, -2147483648., 2147483647.  );

+        *dest = (PaInt32) scaled;

+#endif

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Float32_To_Int32_DitherClip(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    float *src = (float*)sourceBuffer;

+    PaInt32 *dest =  (PaInt32*)destinationBuffer;

+

+    while( count-- )

+    {

+        /* REVIEW */

+#ifdef PA_USE_C99_LRINTF

+        float dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );

+        /* use smaller scaler to prevent overflow when we add the dither */

+        float dithered = ((float)*src * (2147483646.0f)) + dither;

+        PA_CLIP_( dithered, -2147483648.f, 2147483647.f  );

+        *dest = lrintf(dithered-0.5f);

+#else

+        double dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );

+        /* use smaller scaler to prevent overflow when we add the dither */

+        double dithered = ((double)*src * (2147483646.0)) + dither;

+        PA_CLIP_( dithered, -2147483648., 2147483647.  );

+        *dest = (PaInt32) dithered;

+#endif

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Float32_To_Int24(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    float *src = (float*)sourceBuffer;

+    unsigned char *dest = (unsigned char*)destinationBuffer;

+    PaInt32 temp;

+

+    (void) ditherGenerator; /* unused parameter */

+    

+    while( count-- )

+    {

+        /* convert to 32 bit and drop the low 8 bits */

+        double scaled = *src * 0x7FFFFFFF;

+        temp = (PaInt32) scaled;

+        

+#if defined(PA_LITTLE_ENDIAN)

+        dest[0] = (unsigned char)(temp >> 8);

+        dest[1] = (unsigned char)(temp >> 16);

+        dest[2] = (unsigned char)(temp >> 24);

+#elif defined(PA_BIG_ENDIAN)

+        dest[0] = (unsigned char)(temp >> 24);

+        dest[1] = (unsigned char)(temp >> 16);

+        dest[2] = (unsigned char)(temp >> 8);

+#endif

+

+        src += sourceStride;

+        dest += destinationStride * 3;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Float32_To_Int24_Dither(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    float *src = (float*)sourceBuffer;

+    unsigned char *dest = (unsigned char*)destinationBuffer;

+    PaInt32 temp;

+

+    while( count-- )

+    {

+        /* convert to 32 bit and drop the low 8 bits */

+

+        double dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );

+        /* use smaller scaler to prevent overflow when we add the dither */

+        double dithered = ((double)*src * (2147483646.0)) + dither;

+        

+        temp = (PaInt32) dithered;

+

+#if defined(PA_LITTLE_ENDIAN)

+        dest[0] = (unsigned char)(temp >> 8);

+        dest[1] = (unsigned char)(temp >> 16);

+        dest[2] = (unsigned char)(temp >> 24);

+#elif defined(PA_BIG_ENDIAN)

+        dest[0] = (unsigned char)(temp >> 24);

+        dest[1] = (unsigned char)(temp >> 16);

+        dest[2] = (unsigned char)(temp >> 8);

+#endif

+

+        src += sourceStride;

+        dest += destinationStride * 3;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Float32_To_Int24_Clip(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    float *src = (float*)sourceBuffer;

+    unsigned char *dest = (unsigned char*)destinationBuffer;

+    PaInt32 temp;

+

+    (void) ditherGenerator; /* unused parameter */

+    

+    while( count-- )

+    {

+        /* convert to 32 bit and drop the low 8 bits */

+        double scaled = *src * 0x7FFFFFFF;

+        PA_CLIP_( scaled, -2147483648., 2147483647.  );

+        temp = (PaInt32) scaled;

+

+#if defined(PA_LITTLE_ENDIAN)

+        dest[0] = (unsigned char)(temp >> 8);

+        dest[1] = (unsigned char)(temp >> 16);

+        dest[2] = (unsigned char)(temp >> 24);

+#elif defined(PA_BIG_ENDIAN)

+        dest[0] = (unsigned char)(temp >> 24);

+        dest[1] = (unsigned char)(temp >> 16);

+        dest[2] = (unsigned char)(temp >> 8);

+#endif

+

+        src += sourceStride;

+        dest += destinationStride * 3;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Float32_To_Int24_DitherClip(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    float *src = (float*)sourceBuffer;

+    unsigned char *dest = (unsigned char*)destinationBuffer;

+    PaInt32 temp;

+    

+    while( count-- )

+    {

+        /* convert to 32 bit and drop the low 8 bits */

+        

+        double dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );

+        /* use smaller scaler to prevent overflow when we add the dither */

+        double dithered = ((double)*src * (2147483646.0)) + dither;

+        PA_CLIP_( dithered, -2147483648., 2147483647.  );

+        

+        temp = (PaInt32) dithered;

+

+#if defined(PA_LITTLE_ENDIAN)

+        dest[0] = (unsigned char)(temp >> 8);

+        dest[1] = (unsigned char)(temp >> 16);

+        dest[2] = (unsigned char)(temp >> 24);

+#elif defined(PA_BIG_ENDIAN)

+        dest[0] = (unsigned char)(temp >> 24);

+        dest[1] = (unsigned char)(temp >> 16);

+        dest[2] = (unsigned char)(temp >> 8);

+#endif

+

+        src += sourceStride;

+        dest += destinationStride * 3;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Float32_To_Int16(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    float *src = (float*)sourceBuffer;

+    PaInt16 *dest =  (PaInt16*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+#ifdef PA_USE_C99_LRINTF

+        float tempf = (*src * (32767.0f)) ;

+        *dest = lrintf(tempf-0.5f);

+#else

+        short samp = (short) (*src * (32767.0f));

+        *dest = samp;

+#endif

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Float32_To_Int16_Dither(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    float *src = (float*)sourceBuffer;

+    PaInt16 *dest = (PaInt16*)destinationBuffer;

+

+    while( count-- )

+    {

+

+        float dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );

+        /* use smaller scaler to prevent overflow when we add the dither */

+        float dithered = (*src * (32766.0f)) + dither;

+

+#ifdef PA_USE_C99_LRINTF

+        *dest = lrintf(dithered-0.5f);

+#else

+        *dest = (PaInt16) dithered;

+#endif

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Float32_To_Int16_Clip(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    float *src = (float*)sourceBuffer;

+    PaInt16 *dest =  (PaInt16*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+#ifdef PA_USE_C99_LRINTF

+        long samp = lrintf((*src * (32767.0f)) -0.5f);

+#else

+        long samp = (PaInt32) (*src * (32767.0f));

+#endif

+        PA_CLIP_( samp, -0x8000, 0x7FFF );

+        *dest = (PaInt16) samp;

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Float32_To_Int16_DitherClip(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    float *src = (float*)sourceBuffer;

+    PaInt16 *dest =  (PaInt16*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+

+        float dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );

+        /* use smaller scaler to prevent overflow when we add the dither */

+        float dithered = (*src * (32766.0f)) + dither;

+        PaInt32 samp = (PaInt32) dithered;

+        PA_CLIP_( samp, -0x8000, 0x7FFF );

+#ifdef PA_USE_C99_LRINTF

+        *dest = lrintf(samp-0.5f);

+#else

+        *dest = (PaInt16) samp;

+#endif

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Float32_To_Int8(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    float *src = (float*)sourceBuffer;

+    signed char *dest =  (signed char*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        signed char samp = (signed char) (*src * (127.0f));

+        *dest = samp;

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Float32_To_Int8_Dither(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    float *src = (float*)sourceBuffer;

+    signed char *dest =  (signed char*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        float dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );

+        /* use smaller scaler to prevent overflow when we add the dither */

+        float dithered = (*src * (126.0f)) + dither;

+        PaInt32 samp = (PaInt32) dithered;

+        *dest = (signed char) samp;

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Float32_To_Int8_Clip(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    float *src = (float*)sourceBuffer;

+    signed char *dest =  (signed char*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        PaInt32 samp = (PaInt32)(*src * (127.0f));

+        PA_CLIP_( samp, -0x80, 0x7F );

+        *dest = (signed char) samp;

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Float32_To_Int8_DitherClip(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    float *src = (float*)sourceBuffer;

+    signed char *dest =  (signed char*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        float dither  = PaUtil_GenerateFloatTriangularDither( ditherGenerator );

+        /* use smaller scaler to prevent overflow when we add the dither */

+        float dithered = (*src * (126.0f)) + dither;

+        PaInt32 samp = (PaInt32) dithered;

+        PA_CLIP_( samp, -0x80, 0x7F );

+        *dest = (signed char) samp;

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Float32_To_UInt8(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    float *src = (float*)sourceBuffer;

+    unsigned char *dest =  (unsigned char*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        unsigned char samp = (unsigned char)(128 + ((unsigned char) (*src * (127.0f))));

+        *dest = samp;

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Float32_To_UInt8_Dither(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    float *src = (float*)sourceBuffer;

+    unsigned char *dest =  (unsigned char*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        /* IMPLEMENT ME */

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Float32_To_UInt8_Clip(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    float *src = (float*)sourceBuffer;

+    unsigned char *dest =  (unsigned char*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        /* IMPLEMENT ME */

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Float32_To_UInt8_DitherClip(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    float *src = (float*)sourceBuffer;

+    unsigned char *dest =  (unsigned char*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        /* IMPLEMENT ME */

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int32_To_Float32(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    PaInt32 *src = (PaInt32*)sourceBuffer;

+    float *dest =  (float*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        *dest = (float) ((double)*src * const_1_div_2147483648_);

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int32_To_Int24(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    PaInt32 *src    = (PaInt32*)sourceBuffer;

+    unsigned char *dest = (unsigned char*)destinationBuffer;

+    (void) ditherGenerator; /* unused parameter */

+    

+	while( count-- )

+    {

+		/* REVIEW */

+#if defined(PA_LITTLE_ENDIAN)

+        dest[0] = (unsigned char)(*src >> 8);

+        dest[1] = (unsigned char)(*src >> 16);

+        dest[2] = (unsigned char)(*src >> 24);

+#elif defined(PA_BIG_ENDIAN)

+        dest[0] = (unsigned char)(*src >> 24);

+        dest[1] = (unsigned char)(*src >> 16);

+        dest[2] = (unsigned char)(*src >> 8);

+#endif

+        src += sourceStride;

+        dest += destinationStride * 3;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int32_To_Int24_Dither(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    (void) destinationBuffer; /* unused parameters */

+    (void) destinationStride; /* unused parameters */

+    (void) sourceBuffer; /* unused parameters */

+    (void) sourceStride; /* unused parameters */

+    (void) count; /* unused parameters */

+    (void) ditherGenerator; /* unused parameters */

+    /* IMPLEMENT ME */

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int32_To_Int16(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    PaInt32 *src = (PaInt32*)sourceBuffer;

+    PaInt16 *dest =  (PaInt16*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        *dest = (PaInt16) ((*src) >> 16);

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int32_To_Int16_Dither(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    PaInt32 *src = (PaInt32*)sourceBuffer;

+    PaInt16 *dest =  (PaInt16*)destinationBuffer;

+    PaInt32 dither;

+

+    while( count-- )

+    {

+        /* REVIEW */

+        dither = PaUtil_Generate16BitTriangularDither( ditherGenerator );

+        *dest = (PaInt16) ((((*src)>>1) + dither) >> 15);

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int32_To_Int8(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    PaInt32 *src = (PaInt32*)sourceBuffer;

+    signed char *dest =  (signed char*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        *dest = (signed char) ((*src) >> 24);

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int32_To_Int8_Dither(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    PaInt32 *src = (PaInt32*)sourceBuffer;

+    signed char *dest =  (signed char*)destinationBuffer;

+    PaInt32 dither;

+

+    while( count-- )

+    {

+        /* REVIEW */

+        dither = PaUtil_Generate16BitTriangularDither( ditherGenerator );

+        *dest = (signed char) ((((*src)>>1) + dither) >> 23);

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int32_To_UInt8(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    PaInt32 *src = (PaInt32*)sourceBuffer;

+    unsigned char *dest =  (unsigned char*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+		(*dest) = (unsigned char)(((*src) >> 24) + 128); 

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int32_To_UInt8_Dither(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    PaInt32 *src = (PaInt32*)sourceBuffer;

+    unsigned char *dest =  (unsigned char*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        /* IMPLEMENT ME */

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int24_To_Float32(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    unsigned char *src = (unsigned char*)sourceBuffer;

+    float *dest = (float*)destinationBuffer;

+    PaInt32 temp;

+

+    (void) ditherGenerator; /* unused parameter */

+    

+    while( count-- )

+    {

+

+#if defined(PA_LITTLE_ENDIAN)

+        temp = (((long)src[0]) << 8);  

+        temp = temp | (((long)src[1]) << 16);

+        temp = temp | (((long)src[2]) << 24);

+#elif defined(PA_BIG_ENDIAN)

+        temp = (((long)src[0]) << 24);

+        temp = temp | (((long)src[1]) << 16);

+        temp = temp | (((long)src[2]) << 8);

+#endif

+

+        *dest = (float) ((double)temp * const_1_div_2147483648_);

+

+        src += sourceStride * 3;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int24_To_Int32(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    unsigned char *src  = (unsigned char*)sourceBuffer;

+    PaInt32 *dest = (PaInt32*)  destinationBuffer;

+    PaInt32 temp;

+

+    (void) ditherGenerator; /* unused parameter */

+    

+    while( count-- )

+    {

+

+#if defined(PA_LITTLE_ENDIAN)

+        temp = (((long)src[0]) << 8);  

+        temp = temp | (((long)src[1]) << 16);

+        temp = temp | (((long)src[2]) << 24);

+#elif defined(PA_BIG_ENDIAN)

+        temp = (((long)src[0]) << 24);

+        temp = temp | (((long)src[1]) << 16);

+        temp = temp | (((long)src[2]) << 8);

+#endif

+

+        *dest = temp;

+

+        src += sourceStride * 3;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int24_To_Int16(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    unsigned char *src = (unsigned char*)sourceBuffer;

+    PaInt16 *dest = (PaInt16*)destinationBuffer;

+    

+    PaInt16 temp;

+

+    (void) ditherGenerator; /* unused parameter */

+        

+    while( count-- )

+    {

+		

+#if defined(PA_LITTLE_ENDIAN)

+		/* src[0] is discarded */

+        temp = (((PaInt16)src[1]));

+        temp = temp | (PaInt16)(((PaInt16)src[2]) << 8);

+#elif defined(PA_BIG_ENDIAN)

+		/* src[2] is discarded */

+        temp = (PaInt16)(((PaInt16)src[0]) << 8);

+        temp = temp | (((PaInt16)src[1]));

+#endif

+

+        *dest = temp;

+

+        src += sourceStride * 3;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int24_To_Int16_Dither(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    (void) destinationBuffer; /* unused parameters */

+    (void) destinationStride; /* unused parameters */

+    (void) sourceBuffer; /* unused parameters */

+    (void) sourceStride; /* unused parameters */

+    (void) count; /* unused parameters */

+    (void) ditherGenerator; /* unused parameters */

+    /* IMPLEMENT ME */

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int24_To_Int8(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    unsigned char *src = (unsigned char*)sourceBuffer;

+    signed char  *dest = (signed char*)destinationBuffer;

+    

+    (void) ditherGenerator; /* unused parameter */

+        

+    while( count-- )

+    {	

+	

+#if defined(PA_LITTLE_ENDIAN)

+		/* src[0] is discarded */

+		/* src[1] is discarded */

+        *dest = src[2];

+#elif defined(PA_BIG_ENDIAN)

+		/* src[2] is discarded */

+		/* src[1] is discarded */

+		*dest = src[0];

+#endif

+

+        src += sourceStride * 3;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int24_To_Int8_Dither(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    (void) destinationBuffer; /* unused parameters */

+    (void) destinationStride; /* unused parameters */

+    (void) sourceBuffer; /* unused parameters */

+    (void) sourceStride; /* unused parameters */

+    (void) count; /* unused parameters */

+    (void) ditherGenerator; /* unused parameters */

+    /* IMPLEMENT ME */

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int24_To_UInt8(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    unsigned char *src = (unsigned char*)sourceBuffer;

+    unsigned char *dest = (unsigned char*)destinationBuffer;

+    

+    (void) ditherGenerator; /* unused parameter */

+        

+    while( count-- )

+    {

+		

+#if defined(PA_LITTLE_ENDIAN)

+		/* src[0] is discarded */

+		/* src[1] is discarded */

+        *dest = (unsigned char)(src[2] + 128);

+#elif defined(PA_BIG_ENDIAN)

+        *dest = (unsigned char)(src[0] + 128);

+		/* src[1] is discarded */

+		/* src[2] is discarded */		

+#endif

+

+        src += sourceStride * 3;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int24_To_UInt8_Dither(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    (void) destinationBuffer; /* unused parameters */

+    (void) destinationStride; /* unused parameters */

+    (void) sourceBuffer; /* unused parameters */

+    (void) sourceStride; /* unused parameters */

+    (void) count; /* unused parameters */

+    (void) ditherGenerator; /* unused parameters */

+    /* IMPLEMENT ME */

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int16_To_Float32(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    PaInt16 *src = (PaInt16*)sourceBuffer;

+    float *dest =  (float*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        float samp = *src * const_1_div_32768_; /* FIXME: i'm concerned about this being asymetrical with float->int16 -rb */

+        *dest = samp;

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int16_To_Int32(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    PaInt16 *src = (PaInt16*)sourceBuffer;

+    PaInt32 *dest =  (PaInt32*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        /* REVIEW: we should consider something like

+            (*src << 16) | (*src & 0xFFFF)

+        */

+        

+        *dest = *src << 16;

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int16_To_Int24(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    PaInt16 *src   = (PaInt16*) sourceBuffer;

+    unsigned char *dest = (unsigned char*)destinationBuffer;

+    PaInt16 temp;

+

+    (void) ditherGenerator; /* unused parameter */

+    

+    while( count-- )

+    {

+        temp = *src;

+        

+#if defined(PA_LITTLE_ENDIAN)

+        dest[0] = 0;

+        dest[1] = (unsigned char)(temp);

+        dest[2] = (unsigned char)(temp >> 8);

+#elif defined(PA_BIG_ENDIAN)

+        dest[0] = (unsigned char)(temp >> 8);

+        dest[1] = (unsigned char)(temp);

+        dest[2] = 0;

+#endif

+

+        src += sourceStride;

+        dest += destinationStride * 3;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int16_To_Int8(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    PaInt16 *src = (PaInt16*)sourceBuffer;

+    signed char *dest =  (signed char*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        (*dest) = (signed char)((*src) >> 8);

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int16_To_Int8_Dither(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    PaInt16 *src = (PaInt16*)sourceBuffer;

+    signed char *dest =  (signed char*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        /* IMPLEMENT ME */

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int16_To_UInt8(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    PaInt16 *src = (PaInt16*)sourceBuffer;

+    unsigned char *dest =  (unsigned char*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+		(*dest) = (unsigned char)(((*src) >> 8) + 128); 

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int16_To_UInt8_Dither(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    PaInt16 *src = (PaInt16*)sourceBuffer;

+    unsigned char *dest =  (unsigned char*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        /* IMPLEMENT ME */

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int8_To_Float32(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    signed char *src = (signed char*)sourceBuffer;

+    float *dest =  (float*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        float samp = *src * const_1_div_128_;

+        *dest = samp;

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int8_To_Int32(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    signed char *src = (signed char*)sourceBuffer;

+    PaInt32 *dest =  (PaInt32*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+		(*dest) = (*src) << 24;

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int8_To_Int24(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    signed char *src = (signed char*)sourceBuffer;

+    unsigned char *dest =  (unsigned char*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+

+#if defined(PA_LITTLE_ENDIAN)

+        dest[0] = 0;

+        dest[1] = 0;

+        dest[2] = (*src);

+#elif defined(PA_BIG_ENDIAN)

+        dest[0] = (*src);

+        dest[1] = 0;

+        dest[2] = 0;

+#endif

+

+        src += sourceStride;

+        dest += destinationStride * 3;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int8_To_Int16(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    signed char *src = (signed char*)sourceBuffer;

+    PaInt16 *dest =  (PaInt16*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        (*dest) = (PaInt16)((*src) << 8);

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Int8_To_UInt8(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    signed char *src = (signed char*)sourceBuffer;

+    unsigned char *dest =  (unsigned char*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        (*dest) = (unsigned char)(*src + 128);

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void UInt8_To_Float32(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    unsigned char *src = (unsigned char*)sourceBuffer;

+    float *dest =  (float*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        float samp = (*src - 128) * const_1_div_128_;

+        *dest = samp;

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void UInt8_To_Int32(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    unsigned char *src = (unsigned char*)sourceBuffer;

+    PaInt32 *dest = (PaInt32*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+		(*dest) = (*src - 128) << 24;

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void UInt8_To_Int24(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+	unsigned char *src  = (unsigned char*)sourceBuffer;

+    unsigned char *dest = (unsigned char*)destinationBuffer;

+    (void) ditherGenerator; /* unused parameters */

+    

+	while( count-- )

+    {

+

+#if defined(PA_LITTLE_ENDIAN)

+        dest[0] = 0;

+        dest[1] = 0;

+        dest[2] = (unsigned char)(*src - 128);

+#elif defined(PA_BIG_ENDIAN)

+        dest[0] = (unsigned char)(*src - 128);

+        dest[1] = 0;

+        dest[2] = 0;

+#endif

+		

+        src += sourceStride;

+        dest += destinationStride * 3;    

+	}

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void UInt8_To_Int16(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    unsigned char *src = (unsigned char*)sourceBuffer;

+    PaInt16 *dest =  (PaInt16*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        (*dest) = (PaInt16)((*src - 128) << 8);

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void UInt8_To_Int8(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    unsigned char *src = (unsigned char*)sourceBuffer;

+    signed char  *dest = (signed char*)destinationBuffer;

+    (void)ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        (*dest) = (signed char)(*src - 128);

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Copy_8_To_8(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    unsigned char *src = (unsigned char*)sourceBuffer;

+    unsigned char *dest = (unsigned char*)destinationBuffer;

+                                                      

+    (void) ditherGenerator; /* unused parameter */

+

+    while( count-- )

+    {

+        *dest = *src;

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Copy_16_To_16(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    PaUint16 *src = (PaUint16 *)sourceBuffer;

+    PaUint16 *dest = (PaUint16 *)destinationBuffer;

+                                                        

+    (void) ditherGenerator; /* unused parameter */

+    

+    while( count-- )

+    {

+        *dest = *src;

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Copy_24_To_24(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    unsigned char *src = (unsigned char*)sourceBuffer;

+    unsigned char *dest = (unsigned char*)destinationBuffer;

+

+    (void) ditherGenerator; /* unused parameter */

+    

+    while( count-- )

+    {

+        dest[0] = src[0];

+        dest[1] = src[1];

+        dest[2] = src[2];

+

+        src += sourceStride * 3;

+        dest += destinationStride * 3;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Copy_32_To_32(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator )

+{

+    PaUint32 *dest = (PaUint32 *)destinationBuffer;

+    PaUint32 *src = (PaUint32 *)sourceBuffer;

+

+    (void) ditherGenerator; /* unused parameter */

+    

+    while( count-- )

+    {

+        *dest = *src;

+

+        src += sourceStride;

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+PaUtilConverterTable paConverters = {

+    Float32_To_Int32,              /* PaUtilConverter *Float32_To_Int32; */

+    Float32_To_Int32_Dither,       /* PaUtilConverter *Float32_To_Int32_Dither; */

+    Float32_To_Int32_Clip,         /* PaUtilConverter *Float32_To_Int32_Clip; */

+    Float32_To_Int32_DitherClip,   /* PaUtilConverter *Float32_To_Int32_DitherClip; */

+

+    Float32_To_Int24,              /* PaUtilConverter *Float32_To_Int24; */

+    Float32_To_Int24_Dither,       /* PaUtilConverter *Float32_To_Int24_Dither; */

+    Float32_To_Int24_Clip,         /* PaUtilConverter *Float32_To_Int24_Clip; */

+    Float32_To_Int24_DitherClip,   /* PaUtilConverter *Float32_To_Int24_DitherClip; */

+    

+    Float32_To_Int16,              /* PaUtilConverter *Float32_To_Int16; */

+    Float32_To_Int16_Dither,       /* PaUtilConverter *Float32_To_Int16_Dither; */

+    Float32_To_Int16_Clip,         /* PaUtilConverter *Float32_To_Int16_Clip; */

+    Float32_To_Int16_DitherClip,   /* PaUtilConverter *Float32_To_Int16_DitherClip; */

+

+    Float32_To_Int8,               /* PaUtilConverter *Float32_To_Int8; */

+    Float32_To_Int8_Dither,        /* PaUtilConverter *Float32_To_Int8_Dither; */

+    Float32_To_Int8_Clip,          /* PaUtilConverter *Float32_To_Int8_Clip; */

+    Float32_To_Int8_DitherClip,    /* PaUtilConverter *Float32_To_Int8_DitherClip; */

+

+    Float32_To_UInt8,              /* PaUtilConverter *Float32_To_UInt8; */

+    Float32_To_UInt8_Dither,       /* PaUtilConverter *Float32_To_UInt8_Dither; */

+    Float32_To_UInt8_Clip,         /* PaUtilConverter *Float32_To_UInt8_Clip; */

+    Float32_To_UInt8_DitherClip,   /* PaUtilConverter *Float32_To_UInt8_DitherClip; */

+

+    Int32_To_Float32,              /* PaUtilConverter *Int32_To_Float32; */

+    Int32_To_Int24,                /* PaUtilConverter *Int32_To_Int24; */

+    Int32_To_Int24_Dither,         /* PaUtilConverter *Int32_To_Int24_Dither; */

+    Int32_To_Int16,                /* PaUtilConverter *Int32_To_Int16; */

+    Int32_To_Int16_Dither,         /* PaUtilConverter *Int32_To_Int16_Dither; */

+    Int32_To_Int8,                 /* PaUtilConverter *Int32_To_Int8; */

+    Int32_To_Int8_Dither,          /* PaUtilConverter *Int32_To_Int8_Dither; */

+    Int32_To_UInt8,                /* PaUtilConverter *Int32_To_UInt8; */

+    Int32_To_UInt8_Dither,         /* PaUtilConverter *Int32_To_UInt8_Dither; */

+

+    Int24_To_Float32,              /* PaUtilConverter *Int24_To_Float32; */

+    Int24_To_Int32,                /* PaUtilConverter *Int24_To_Int32; */

+    Int24_To_Int16,                /* PaUtilConverter *Int24_To_Int16; */

+    Int24_To_Int16_Dither,         /* PaUtilConverter *Int24_To_Int16_Dither; */

+    Int24_To_Int8,                 /* PaUtilConverter *Int24_To_Int8; */

+    Int24_To_Int8_Dither,          /* PaUtilConverter *Int24_To_Int8_Dither; */

+    Int24_To_UInt8,                /* PaUtilConverter *Int24_To_UInt8; */

+    Int24_To_UInt8_Dither,         /* PaUtilConverter *Int24_To_UInt8_Dither; */

+

+    Int16_To_Float32,              /* PaUtilConverter *Int16_To_Float32; */

+    Int16_To_Int32,                /* PaUtilConverter *Int16_To_Int32; */

+    Int16_To_Int24,                /* PaUtilConverter *Int16_To_Int24; */

+    Int16_To_Int8,                 /* PaUtilConverter *Int16_To_Int8; */

+    Int16_To_Int8_Dither,          /* PaUtilConverter *Int16_To_Int8_Dither; */

+    Int16_To_UInt8,                /* PaUtilConverter *Int16_To_UInt8; */

+    Int16_To_UInt8_Dither,         /* PaUtilConverter *Int16_To_UInt8_Dither; */

+

+    Int8_To_Float32,               /* PaUtilConverter *Int8_To_Float32; */

+    Int8_To_Int32,                 /* PaUtilConverter *Int8_To_Int32; */

+    Int8_To_Int24,                 /* PaUtilConverter *Int8_To_Int24 */

+    Int8_To_Int16,                 /* PaUtilConverter *Int8_To_Int16; */

+    Int8_To_UInt8,                 /* PaUtilConverter *Int8_To_UInt8; */

+

+    UInt8_To_Float32,              /* PaUtilConverter *UInt8_To_Float32; */

+    UInt8_To_Int32,                /* PaUtilConverter *UInt8_To_Int32; */

+    UInt8_To_Int24,                /* PaUtilConverter *UInt8_To_Int24; */

+    UInt8_To_Int16,                /* PaUtilConverter *UInt8_To_Int16; */

+    UInt8_To_Int8,                 /* PaUtilConverter *UInt8_To_Int8; */

+

+    Copy_8_To_8,                   /* PaUtilConverter *Copy_8_To_8; */

+    Copy_16_To_16,                 /* PaUtilConverter *Copy_16_To_16; */

+    Copy_24_To_24,                 /* PaUtilConverter *Copy_24_To_24; */

+    Copy_32_To_32                  /* PaUtilConverter *Copy_32_To_32; */

+};

+

+/* -------------------------------------------------------------------------- */

+

+#endif /* PA_NO_STANDARD_CONVERTERS */

+

+/* -------------------------------------------------------------------------- */

+

+PaUtilZeroer* PaUtil_SelectZeroer( PaSampleFormat destinationFormat )

+{

+    switch( destinationFormat & ~paNonInterleaved ){

+    case paFloat32:

+        return paZeroers.Zero32;

+    case paInt32:

+        return paZeroers.Zero32;

+    case paInt24:

+        return paZeroers.Zero24;

+    case paInt16:

+        return paZeroers.Zero16;

+    case paInt8:

+        return paZeroers.Zero8;

+    case paUInt8:

+        return paZeroers.ZeroU8;

+    default: return 0;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+#ifdef PA_NO_STANDARD_ZEROERS

+

+/* -------------------------------------------------------------------------- */

+

+PaUtilZeroerTable paZeroers = {

+    0,  /* PaUtilZeroer *ZeroU8; */

+    0,  /* PaUtilZeroer *Zero8; */

+    0,  /* PaUtilZeroer *Zero16; */

+    0,  /* PaUtilZeroer *Zero24; */

+    0,  /* PaUtilZeroer *Zero32; */

+};

+

+/* -------------------------------------------------------------------------- */

+

+#else /* PA_NO_STANDARD_ZEROERS is not defined */

+

+/* -------------------------------------------------------------------------- */

+

+static void ZeroU8( void *destinationBuffer, signed int destinationStride,

+        unsigned int count )

+{

+    unsigned char *dest = (unsigned char*)destinationBuffer;

+

+    while( count-- )

+    {

+        *dest = 128;

+

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Zero8( void *destinationBuffer, signed int destinationStride,

+        unsigned int count )

+{

+    unsigned char *dest = (unsigned char*)destinationBuffer;

+

+    while( count-- )

+    {

+        *dest = 0;

+

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Zero16( void *destinationBuffer, signed int destinationStride,

+        unsigned int count )

+{

+    PaUint16 *dest = (PaUint16 *)destinationBuffer;

+

+    while( count-- )

+    {

+        *dest = 0;

+

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Zero24( void *destinationBuffer, signed int destinationStride,

+        unsigned int count )

+{

+    unsigned char *dest = (unsigned char*)destinationBuffer;

+

+    while( count-- )

+    {

+        dest[0] = 0;

+        dest[1] = 0;

+        dest[2] = 0;

+

+        dest += destinationStride * 3;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+static void Zero32( void *destinationBuffer, signed int destinationStride,

+        unsigned int count )

+{

+    PaUint32 *dest = (PaUint32 *)destinationBuffer;

+

+    while( count-- )

+    {

+        *dest = 0;

+

+        dest += destinationStride;

+    }

+}

+

+/* -------------------------------------------------------------------------- */

+

+PaUtilZeroerTable paZeroers = {

+    ZeroU8,  /* PaUtilZeroer *ZeroU8; */

+    Zero8,  /* PaUtilZeroer *Zero8; */

+    Zero16,  /* PaUtilZeroer *Zero16; */

+    Zero24,  /* PaUtilZeroer *Zero24; */

+    Zero32,  /* PaUtilZeroer *Zero32; */

+};

+

+/* -------------------------------------------------------------------------- */

+

+#endif /* PA_NO_STANDARD_ZEROERS */

diff --git a/src/engine/external/portaudio/pa_converters.h b/src/engine/external/portaudio/pa_converters.h
new file mode 100644
index 00000000..758756f4
--- /dev/null
+++ b/src/engine/external/portaudio/pa_converters.h
@@ -0,0 +1,263 @@
+#ifndef PA_CONVERTERS_H

+#define PA_CONVERTERS_H

+/*

+ * $Id: pa_converters.h 1097 2006-08-26 08:27:53Z rossb $

+ * Portable Audio I/O Library sample conversion mechanism

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Phil Burk, Ross Bencina

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup common_src

+

+ @brief Conversion functions used to convert buffers of samples from one

+ format to another.

+*/

+

+

+#include "portaudio.h"  /* for PaSampleFormat */

+

+#ifdef __cplusplus

+extern "C"

+{

+#endif /* __cplusplus */

+

+

+struct PaUtilTriangularDitherGenerator;

+

+

+/** Choose an available sample format which is most appropriate for

+ representing the requested format. If the requested format is not available

+ higher quality formats are considered before lower quality formates.

+ @param availableFormats A variable containing the logical OR of all available

+ formats.

+ @param format The desired format.

+ @return The most appropriate available format for representing the requested

+ format.

+*/

+PaSampleFormat PaUtil_SelectClosestAvailableFormat(

+        PaSampleFormat availableFormats, PaSampleFormat format );

+

+

+/* high level conversions functions for use by implementations */

+

+

+/** The generic sample converter prototype. Sample converters convert count

+    samples from sourceBuffer to destinationBuffer. The actual type of the data

+    pointed to by these parameters varys for different converter functions.

+    @param destinationBuffer A pointer to the first sample of the destination.

+    @param destinationStride An offset between successive destination samples

+    expressed in samples (not bytes.) It may be negative.

+    @param sourceBuffer A pointer to the first sample of the source.

+    @param sourceStride An offset between successive source samples

+    expressed in samples (not bytes.) It may be negative.

+    @param count The number of samples to convert.

+    @param ditherState State information used to calculate dither. Converters

+    that do not perform dithering will ignore this parameter, in which case

+    NULL or invalid dither state may be passed.

+*/

+typedef void PaUtilConverter(

+    void *destinationBuffer, signed int destinationStride,

+    void *sourceBuffer, signed int sourceStride,

+    unsigned int count, struct PaUtilTriangularDitherGenerator *ditherGenerator );

+

+

+/** Find a sample converter function for the given source and destinations

+    formats and flags (clip and dither.)

+    @return

+    A pointer to a PaUtilConverter which will perform the requested

+    conversion, or NULL if the given format conversion is not supported.

+    For conversions where clipping or dithering is not necessary, the

+    clip and dither flags are ignored and a non-clipping or dithering

+    version is returned.

+    If the source and destination formats are the same, a function which

+    copies data of the appropriate size will be returned.

+*/

+PaUtilConverter* PaUtil_SelectConverter( PaSampleFormat sourceFormat,

+        PaSampleFormat destinationFormat, PaStreamFlags flags );

+

+

+/** The generic buffer zeroer prototype. Buffer zeroers copy count zeros to

+    destinationBuffer. The actual type of the data pointed to varys for

+    different zeroer functions.

+    @param destinationBuffer A pointer to the first sample of the destination.

+    @param destinationStride An offset between successive destination samples

+    expressed in samples (not bytes.) It may be negative.

+    @param count The number of samples to zero.

+*/

+typedef void PaUtilZeroer(

+    void *destinationBuffer, signed int destinationStride, unsigned int count );

+

+    

+/** Find a buffer zeroer function for the given destination format.

+    @return

+    A pointer to a PaUtilZeroer which will perform the requested

+    zeroing.

+*/

+PaUtilZeroer* PaUtil_SelectZeroer( PaSampleFormat destinationFormat );

+

+/*----------------------------------------------------------------------------*/

+/* low level functions and data structures which may be used for

+    substituting conversion functions */

+

+

+/** The type used to store all sample conversion functions.

+    @see paConverters;

+*/

+typedef struct{

+    PaUtilConverter *Float32_To_Int32;

+    PaUtilConverter *Float32_To_Int32_Dither;

+    PaUtilConverter *Float32_To_Int32_Clip;

+    PaUtilConverter *Float32_To_Int32_DitherClip;

+

+    PaUtilConverter *Float32_To_Int24;

+    PaUtilConverter *Float32_To_Int24_Dither;

+    PaUtilConverter *Float32_To_Int24_Clip;

+    PaUtilConverter *Float32_To_Int24_DitherClip;

+    

+    PaUtilConverter *Float32_To_Int16;

+    PaUtilConverter *Float32_To_Int16_Dither;

+    PaUtilConverter *Float32_To_Int16_Clip;

+    PaUtilConverter *Float32_To_Int16_DitherClip;

+

+    PaUtilConverter *Float32_To_Int8;

+    PaUtilConverter *Float32_To_Int8_Dither;

+    PaUtilConverter *Float32_To_Int8_Clip;

+    PaUtilConverter *Float32_To_Int8_DitherClip;

+

+    PaUtilConverter *Float32_To_UInt8;

+    PaUtilConverter *Float32_To_UInt8_Dither;

+    PaUtilConverter *Float32_To_UInt8_Clip;

+    PaUtilConverter *Float32_To_UInt8_DitherClip;

+

+    PaUtilConverter *Int32_To_Float32;

+    PaUtilConverter *Int32_To_Int24;

+    PaUtilConverter *Int32_To_Int24_Dither;

+    PaUtilConverter *Int32_To_Int16;

+    PaUtilConverter *Int32_To_Int16_Dither;

+    PaUtilConverter *Int32_To_Int8;

+    PaUtilConverter *Int32_To_Int8_Dither;

+    PaUtilConverter *Int32_To_UInt8;

+    PaUtilConverter *Int32_To_UInt8_Dither;

+

+    PaUtilConverter *Int24_To_Float32;

+    PaUtilConverter *Int24_To_Int32;

+    PaUtilConverter *Int24_To_Int16;

+    PaUtilConverter *Int24_To_Int16_Dither;

+    PaUtilConverter *Int24_To_Int8;

+    PaUtilConverter *Int24_To_Int8_Dither;

+    PaUtilConverter *Int24_To_UInt8;

+    PaUtilConverter *Int24_To_UInt8_Dither;

+

+    PaUtilConverter *Int16_To_Float32;

+    PaUtilConverter *Int16_To_Int32;

+    PaUtilConverter *Int16_To_Int24;

+    PaUtilConverter *Int16_To_Int8;

+    PaUtilConverter *Int16_To_Int8_Dither;

+    PaUtilConverter *Int16_To_UInt8;

+    PaUtilConverter *Int16_To_UInt8_Dither;

+

+    PaUtilConverter *Int8_To_Float32;

+    PaUtilConverter *Int8_To_Int32;

+    PaUtilConverter *Int8_To_Int24;

+    PaUtilConverter *Int8_To_Int16;

+    PaUtilConverter *Int8_To_UInt8;

+    

+    PaUtilConverter *UInt8_To_Float32;

+    PaUtilConverter *UInt8_To_Int32;

+    PaUtilConverter *UInt8_To_Int24;

+    PaUtilConverter *UInt8_To_Int16;

+    PaUtilConverter *UInt8_To_Int8;

+

+    PaUtilConverter *Copy_8_To_8;       /* copy without any conversion */

+    PaUtilConverter *Copy_16_To_16;     /* copy without any conversion */

+    PaUtilConverter *Copy_24_To_24;     /* copy without any conversion */

+    PaUtilConverter *Copy_32_To_32;     /* copy without any conversion */

+} PaUtilConverterTable;

+

+

+/** A table of pointers to all required converter functions.

+    PaUtil_SelectConverter() uses this table to lookup the appropriate

+    conversion functions. The fields of this structure are initialized

+    with default conversion functions. Fields may be NULL, indicating that

+    no conversion function is available. User code may substitue optimised

+    conversion functions by assigning different function pointers to

+    these fields.

+

+    @note

+    If the PA_NO_STANDARD_CONVERTERS preprocessor variable is defined,

+    PortAudio's standard converters will not be compiled, and all fields

+    of this structure will be initialized to NULL. In such cases, users

+    should supply their own conversion functions if the require PortAudio

+    to open a stream that requires sample conversion.

+

+    @see PaUtilConverterTable, PaUtilConverter, PaUtil_SelectConverter

+*/

+extern PaUtilConverterTable paConverters;

+

+

+/** The type used to store all buffer zeroing functions.

+    @see paZeroers;

+*/

+typedef struct{

+    PaUtilZeroer *ZeroU8; /* unsigned 8 bit, zero == 128 */

+    PaUtilZeroer *Zero8;

+    PaUtilZeroer *Zero16;

+    PaUtilZeroer *Zero24;

+    PaUtilZeroer *Zero32;

+} PaUtilZeroerTable;

+

+

+/** A table of pointers to all required zeroer functions.

+    PaUtil_SelectZeroer() uses this table to lookup the appropriate

+    conversion functions. The fields of this structure are initialized

+    with default conversion functions. User code may substitue optimised

+    conversion functions by assigning different function pointers to

+    these fields.

+

+    @note

+    If the PA_NO_STANDARD_ZEROERS preprocessor variable is defined,

+    PortAudio's standard zeroers will not be compiled, and all fields

+    of this structure will be initialized to NULL. In such cases, users

+    should supply their own zeroing functions for the sample sizes which

+    they intend to use.

+

+    @see PaUtilZeroerTable, PaUtilZeroer, PaUtil_SelectZeroer

+*/

+extern PaUtilZeroerTable paZeroers;

+

+#ifdef __cplusplus

+}

+#endif /* __cplusplus */

+#endif /* PA_CONVERTERS_H */

diff --git a/src/engine/external/portaudio/pa_cpuload.c b/src/engine/external/portaudio/pa_cpuload.c
new file mode 100644
index 00000000..cc4fad77
--- /dev/null
+++ b/src/engine/external/portaudio/pa_cpuload.c
@@ -0,0 +1,105 @@
+/*

+ * $Id: pa_cpuload.c 1097 2006-08-26 08:27:53Z rossb $

+ * Portable Audio I/O Library CPU Load measurement functions

+ * Portable CPU load measurement facility.

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 2002 Ross Bencina

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup common_src

+

+ @brief Functions to assist in measuring the CPU utilization of a callback

+ stream. Used to implement the Pa_GetStreamCpuLoad() function.

+

+ @todo Dynamically calculate the coefficients used to smooth the CPU Load

+ Measurements over time to provide a uniform characterisation of CPU Load

+ independent of rate at which PaUtil_BeginCpuLoadMeasurement /

+ PaUtil_EndCpuLoadMeasurement are called.

+*/

+

+

+#include "pa_cpuload.h"

+

+#include <assert.h>

+

+#include "pa_util.h"   /* for PaUtil_GetTime() */

+

+

+void PaUtil_InitializeCpuLoadMeasurer( PaUtilCpuLoadMeasurer* measurer, double sampleRate )

+{

+    assert( sampleRate > 0 );

+

+    measurer->samplingPeriod = 1. / sampleRate;

+    measurer->averageLoad = 0.;

+}

+

+void PaUtil_ResetCpuLoadMeasurer( PaUtilCpuLoadMeasurer* measurer )

+{

+    measurer->averageLoad = 0.;

+}

+

+void PaUtil_BeginCpuLoadMeasurement( PaUtilCpuLoadMeasurer* measurer )

+{

+    measurer->measurementStartTime = PaUtil_GetTime();

+}

+

+

+void PaUtil_EndCpuLoadMeasurement( PaUtilCpuLoadMeasurer* measurer, unsigned long framesProcessed )

+{

+    double measurementEndTime, secondsFor100Percent, measuredLoad;

+

+    if( framesProcessed > 0 ){

+        measurementEndTime = PaUtil_GetTime();

+

+        assert( framesProcessed > 0 );

+        secondsFor100Percent = framesProcessed * measurer->samplingPeriod;

+

+        measuredLoad = (measurementEndTime - measurer->measurementStartTime) / secondsFor100Percent;

+

+        /* Low pass filter the calculated CPU load to reduce jitter using a simple IIR low pass filter. */

+        /** FIXME @todo these coefficients shouldn't be hardwired */

+#define LOWPASS_COEFFICIENT_0   (0.9)

+#define LOWPASS_COEFFICIENT_1   (0.99999 - LOWPASS_COEFFICIENT_0)

+

+        measurer->averageLoad = (LOWPASS_COEFFICIENT_0 * measurer->averageLoad) +

+                               (LOWPASS_COEFFICIENT_1 * measuredLoad);

+    }

+}

+

+

+double PaUtil_GetCpuLoad( PaUtilCpuLoadMeasurer* measurer )

+{

+    return measurer->averageLoad;

+}

diff --git a/src/engine/external/portaudio/pa_cpuload.h b/src/engine/external/portaudio/pa_cpuload.h
new file mode 100644
index 00000000..43c11799
--- /dev/null
+++ b/src/engine/external/portaudio/pa_cpuload.h
@@ -0,0 +1,72 @@
+#ifndef PA_CPULOAD_H

+#define PA_CPULOAD_H

+/*

+ * $Id: pa_cpuload.h 1097 2006-08-26 08:27:53Z rossb $

+ * Portable Audio I/O Library CPU Load measurement functions

+ * Portable CPU load measurement facility.

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 2002 Ross Bencina

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup common_src

+

+ @brief Functions to assist in measuring the CPU utilization of a callback

+ stream. Used to implement the Pa_GetStreamCpuLoad() function.

+*/

+

+

+#ifdef __cplusplus

+extern "C"

+{

+#endif /* __cplusplus */

+

+

+typedef struct {

+    double samplingPeriod;

+    double measurementStartTime;

+    double averageLoad;

+} PaUtilCpuLoadMeasurer; /**< @todo need better name than measurer */

+

+void PaUtil_InitializeCpuLoadMeasurer( PaUtilCpuLoadMeasurer* measurer, double sampleRate );

+void PaUtil_BeginCpuLoadMeasurement( PaUtilCpuLoadMeasurer* measurer );

+void PaUtil_EndCpuLoadMeasurement( PaUtilCpuLoadMeasurer* measurer, unsigned long framesProcessed );

+void PaUtil_ResetCpuLoadMeasurer( PaUtilCpuLoadMeasurer* measurer );

+double PaUtil_GetCpuLoad( PaUtilCpuLoadMeasurer* measurer );

+

+

+#ifdef __cplusplus

+}

+#endif /* __cplusplus */     

+#endif /* PA_CPULOAD_H */

diff --git a/src/engine/external/portaudio/pa_debugprint.c b/src/engine/external/portaudio/pa_debugprint.c
new file mode 100644
index 00000000..33fcf32e
--- /dev/null
+++ b/src/engine/external/portaudio/pa_debugprint.c
@@ -0,0 +1,107 @@
+/*

+ * $Id: pa_log.c $

+ * Portable Audio I/O Library Multi-Host API front end

+ * Validate function parameters and manage multiple host APIs.

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2006 Ross Bencina, Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however,

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also

+ * requested that these non-binding requests be included along with the

+ * license above.

+ */

+

+/** @file

+ @ingroup common_src

+

+ @brief Implements log function.

+

+    PaUtil_SetLogPrintFunction can be user called to replace the provided

+	DefaultLogPrint function, which writes to stderr.

+	One can NOT pass var_args across compiler/dll boundaries as it is not

+	"byte code/abi portable". So the technique used here is to allocate a local

+	a static array, write in it, then callback the user with a pointer to its

+	start.

+

+    @todo Consider allocating strdump using dynamic allocation.

+    @todo Consider reentrancy and possibly corrupted strdump buffer.

+*/

+

+

+#include <stdio.h>

+#include <stdarg.h>

+

+#include "pa_debugprint.h"

+

+

+

+static PaUtilLogCallback userCB=0;

+

+

+void PaUtil_SetDebugPrintFunction(PaUtilLogCallback cb)

+{

+    userCB = cb;

+}

+

+/*

+ If your platform doesn’t have vsnprintf, you are stuck with a

+ VERY dangerous alternative, vsprintf (with no n)

+ */

+

+#if (_MSC_VER) && (_MSC_VER < 1400)

+#define VSNPRINTF  _vsnprintf

+#else

+#define VSNPRINTF  vsnprintf

+#endif

+

+#define SIZEDUMP 1024

+

+static char strdump[SIZEDUMP];

+

+void PaUtil_DebugPrint( const char *format, ... )

+{

+

+    if (userCB)

+    {

+        va_list ap;

+        va_start( ap, format );

+        VSNPRINTF( strdump, SIZEDUMP, format, ap );

+        userCB(strdump);

+        va_end( ap ); 

+    }

+    else

+    {

+        va_list ap;

+        va_start( ap, format );

+        vfprintf( stderr, format, ap );

+        va_end( ap );

+        fflush( stderr );

+    }

+

+}

diff --git a/src/engine/external/portaudio/pa_debugprint.h b/src/engine/external/portaudio/pa_debugprint.h
new file mode 100644
index 00000000..493537c7
--- /dev/null
+++ b/src/engine/external/portaudio/pa_debugprint.h
@@ -0,0 +1,148 @@
+#ifndef PA_LOG_H

+#define PA_LOG_H

+/*

+ * Log file redirector function

+ * Copyright (c) 1999-2006 Ross Bencina, Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however,

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also

+ * requested that these non-binding requests be included along with the

+ * license above.

+ */

+

+/** @file

+ @ingroup common_src

+*/

+

+

+#ifdef __cplusplus

+extern "C"

+{

+#endif /* __cplusplus */

+

+

+

+void PaUtil_DebugPrint( const char *format, ... );

+

+

+/*

+    The basic format for log messages is described below. If you need to

+    add any log messages, please follow this format.

+

+    Function entry (void function):

+

+        "FunctionName called.\n"

+

+    Function entry (non void function):

+

+        "FunctionName called:\n"

+        "\tParam1Type param1: param1Value\n"

+        "\tParam2Type param2: param2Value\n"      (etc...)

+

+

+    Function exit (no return value):

+

+        "FunctionName returned.\n"

+

+    Function exit (simple return value):

+

+        "FunctionName returned:\n"

+        "\tReturnType: returnValue\n"

+

+    If the return type is an error code, the error text is displayed in ()

+

+    If the return type is not an error code, but has taken a special value

+    because an error occurred, then the reason for the error is shown in []

+

+    If the return type is a struct ptr, the struct is dumped.

+

+    See the code below for examples

+*/

+

+/** PA_DEBUG() provides a simple debug message printing facility. The macro

+ passes it's argument to a printf-like function called PaUtil_DebugPrint()

+ which prints to stderr and always flushes the stream after printing.

+ Because preprocessor macros cannot directly accept variable length argument

+ lists, calls to the macro must include an additional set of parenthesis, eg:

+ PA_DEBUG(("errorno: %d", 1001 ));

+*/

+

+#ifdef PA_ENABLE_DEBUG_OUTPUT

+#define PA_DEBUG(x) PaUtil_DebugPrint x ;

+#else

+#define PA_DEBUG(x)

+#endif

+

+

+#ifdef PA_LOG_API_CALLS

+#define PA_LOGAPI(x) PaUtil_DebugPrint x 

+

+#define PA_LOGAPI_ENTER(functionName) PaUtil_DebugPrint( functionName " called.\n" )

+

+#define PA_LOGAPI_ENTER_PARAMS(functionName) PaUtil_DebugPrint( functionName " called:\n" )

+

+#define PA_LOGAPI_EXIT(functionName) PaUtil_DebugPrint( functionName " returned.\n" )

+

+#define PA_LOGAPI_EXIT_PAERROR( functionName, result ) \

+	PaUtil_DebugPrint( functionName " returned:\n" ); \

+	PaUtil_DebugPrint("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) )

+

+#define PA_LOGAPI_EXIT_T( functionName, resultFormatString, result ) \

+	PaUtil_DebugPrint( functionName " returned:\n" ); \

+	PaUtil_DebugPrint("\t" resultFormatString "\n", result )

+

+#define PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( functionName, positiveResultFormatString, result ) \

+	PaUtil_DebugPrint( functionName " returned:\n" ); \

+	if( result > 0 ) \

+        PaUtil_DebugPrint("\t" positiveResultFormatString "\n", result ); \

+    else \

+        PaUtil_DebugPrint("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) )

+#else

+#define PA_LOGAPI(x)

+#define PA_LOGAPI_ENTER(functionName)

+#define PA_LOGAPI_ENTER_PARAMS(functionName)

+#define PA_LOGAPI_EXIT(functionName)

+#define PA_LOGAPI_EXIT_PAERROR( functionName, result )

+#define PA_LOGAPI_EXIT_T( functionName, resultFormatString, result )

+#define PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( functionName, positiveResultFormatString, result )

+#endif

+

+    

+typedef void (*PaUtilLogCallback ) (const char *log);

+

+/**

+    Install user provided log function

+*/

+void PaUtil_SetDebugPrintFunction(PaUtilLogCallback  cb);

+

+

+

+#ifdef __cplusplus

+}

+#endif /* __cplusplus */

+#endif /* PA_LOG_H */

diff --git a/src/engine/external/portaudio/pa_dither.c b/src/engine/external/portaudio/pa_dither.c
new file mode 100644
index 00000000..ca0b09b3
--- /dev/null
+++ b/src/engine/external/portaudio/pa_dither.c
@@ -0,0 +1,213 @@
+/*

+ * $Id: pa_dither.c 1097 2006-08-26 08:27:53Z rossb $

+ * Portable Audio I/O Library triangular dither generator

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Phil Burk, Ross Bencina

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup common_src

+

+ @brief Functions for generating dither noise

+*/

+

+

+#include "pa_dither.h"

+#include "pa_types.h"

+

+#define PA_DITHER_BITS_   (15)

+

+

+void PaUtil_InitializeTriangularDitherState( PaUtilTriangularDitherGenerator *state )

+{

+    state->previous = 0;

+    state->randSeed1 = 22222;

+    state->randSeed2 = 5555555;

+}

+

+

+signed long PaUtil_Generate16BitTriangularDither( PaUtilTriangularDitherGenerator *state )

+{

+    signed long current, highPass;

+

+    /* Generate two random numbers. */

+    state->randSeed1 = (state->randSeed1 * 196314165) + 907633515;

+    state->randSeed2 = (state->randSeed2 * 196314165) + 907633515;

+

+    /* Generate triangular distribution about 0.

+     * Shift before adding to prevent overflow which would skew the distribution.

+     * Also shift an extra bit for the high pass filter. 

+     */

+#define DITHER_SHIFT_  ((SIZEOF_LONG*8 - PA_DITHER_BITS_) + 1)

+    current = (((signed long)state->randSeed1)>>DITHER_SHIFT_) +

+              (((signed long)state->randSeed2)>>DITHER_SHIFT_);

+

+    /* High pass filter to reduce audibility. */

+    highPass = current - state->previous;

+    state->previous = current;

+    return highPass;

+}

+

+

+/* Multiply by PA_FLOAT_DITHER_SCALE_ to get a float between -2.0 and +1.99999 */

+#define PA_FLOAT_DITHER_SCALE_  (1.0f / ((1<<PA_DITHER_BITS_)-1))

+static const float const_float_dither_scale_ = PA_FLOAT_DITHER_SCALE_;

+

+float PaUtil_GenerateFloatTriangularDither( PaUtilTriangularDitherGenerator *state )

+{

+    signed long current, highPass;

+

+    /* Generate two random numbers. */

+    state->randSeed1 = (state->randSeed1 * 196314165) + 907633515;

+    state->randSeed2 = (state->randSeed2 * 196314165) + 907633515;

+

+    /* Generate triangular distribution about 0.

+     * Shift before adding to prevent overflow which would skew the distribution.

+     * Also shift an extra bit for the high pass filter. 

+     */

+#define DITHER_SHIFT_  ((SIZEOF_LONG*8 - PA_DITHER_BITS_) + 1)

+    current = (((signed long)state->randSeed1)>>DITHER_SHIFT_) +

+              (((signed long)state->randSeed2)>>DITHER_SHIFT_);

+

+    /* High pass filter to reduce audibility. */

+    highPass = current - state->previous;

+    state->previous = current;

+    return ((float)highPass) * const_float_dither_scale_;

+}

+

+

+/*

+The following alternate dither algorithms (from musicdsp.org) could be

+considered

+*/

+

+/*Noise shaped dither  (March 2000)

+-------------------

+

+This is a simple implementation of highpass triangular-PDF dither with

+2nd-order noise shaping, for use when truncating floating point audio

+data to fixed point.

+

+The noise shaping lowers the noise floor by 11dB below 5kHz (@ 44100Hz

+sample rate) compared to triangular-PDF dither. The code below assumes

+input data is in the range +1 to -1 and doesn't check for overloads!

+

+To save time when generating dither for multiple channels you can do

+things like this:  r3=(r1 & 0x7F)<<8; instead of calling rand() again.

+

+

+

+  int   r1, r2;                //rectangular-PDF random numbers

+  float s1, s2;                //error feedback buffers

+  float s = 0.5f;              //set to 0.0f for no noise shaping

+  float w = pow(2.0,bits-1);   //word length (usually bits=16)

+  float wi= 1.0f/w;            

+  float d = wi / RAND_MAX;     //dither amplitude (2 lsb)

+  float o = wi * 0.5f;         //remove dc offset

+  float in, tmp;

+  int   out;

+

+

+//for each sample...

+

+  r2=r1;                               //can make HP-TRI dither by

+  r1=rand();                           //subtracting previous rand()

+    

+  in += s * (s1 + s1 - s2);            //error feedback

+  tmp = in + o + d * (float)(r1 - r2); //dc offset and dither 

+  

+  out = (int)(w * tmp);                //truncate downwards

+  if(tmp<0.0f) out--;                  //this is faster than floor()

+

+  s2 = s1;                            

+  s1 = in - wi * (float)out;           //error

+

+

+

+-- 

+paul.kellett@maxim.abel.co.uk

+http://www.maxim.abel.co.uk

+*/

+

+

+/*

+16-to-8-bit first-order dither

+

+Type : First order error feedforward dithering code

+References : Posted by Jon Watte

+

+Notes : 

+This is about as simple a dithering algorithm as you can implement, but it's

+likely to sound better than just truncating to N bits.

+

+Note that you might not want to carry forward the full difference for infinity.

+It's probably likely that the worst performance hit comes from the saturation

+conditionals, which can be avoided with appropriate instructions on many DSPs

+and integer SIMD type instructions, or CMOV.

+

+Last, if sound quality is paramount (such as when going from > 16 bits to 16

+bits) you probably want to use a higher-order dither function found elsewhere

+on this site. 

+

+

+Code : 

+// This code will down-convert and dither a 16-bit signed short 

+// mono signal into an 8-bit unsigned char signal, using a first 

+// order forward-feeding error term dither. 

+

+#define uchar unsigned char 

+

+void dither_one_channel_16_to_8( short * input, uchar * output, int count, int * memory ) 

+{ 

+  int m = *memory; 

+  while( count-- > 0 ) { 

+    int i = *input++; 

+    i += m; 

+    int j = i + 32768 - 128; 

+    uchar o; 

+    if( j < 0 ) { 

+      o = 0; 

+    } 

+    else if( j > 65535 ) { 

+      o = 255; 

+    } 

+    else { 

+      o = (uchar)((j>>8)&0xff); 

+    } 

+    m = ((j-32768+128)-i); 

+    *output++ = o; 

+  } 

+  *memory = m; 

+} 

+*/

diff --git a/src/engine/external/portaudio/pa_dither.h b/src/engine/external/portaudio/pa_dither.h
new file mode 100644
index 00000000..c76af3ae
--- /dev/null
+++ b/src/engine/external/portaudio/pa_dither.h
@@ -0,0 +1,100 @@
+#ifndef PA_DITHER_H

+#define PA_DITHER_H

+/*

+ * $Id: pa_dither.h 1097 2006-08-26 08:27:53Z rossb $

+ * Portable Audio I/O Library triangular dither generator

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Phil Burk, Ross Bencina

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup common_src

+

+ @brief Functions for generating dither noise

+*/

+

+

+#ifdef __cplusplus

+extern "C"

+{

+#endif /* __cplusplus */

+

+

+/** @brief State needed to generate a dither signal */

+typedef struct PaUtilTriangularDitherGenerator{

+    unsigned long previous;

+    unsigned long randSeed1;

+    unsigned long randSeed2;

+} PaUtilTriangularDitherGenerator;

+

+

+/** @brief Initialize dither state */

+void PaUtil_InitializeTriangularDitherState( PaUtilTriangularDitherGenerator *ditherState );

+

+

+/**

+ @brief Calculate 2 LSB dither signal with a triangular distribution.

+ Ranged for adding to a 1 bit right-shifted 32 bit integer

+ prior to >>15. eg:

+<pre>

+    signed long in = *

+    signed long dither = PaUtil_Generate16BitTriangularDither( ditherState );

+    signed short out = (signed short)(((in>>1) + dither) >> 15);

+</pre>

+ @return

+ A signed long with a range of +32767 to -32768

+*/

+signed long PaUtil_Generate16BitTriangularDither( PaUtilTriangularDitherGenerator *ditherState );

+

+

+/**

+ @brief Calculate 2 LSB dither signal with a triangular distribution.

+ Ranged for adding to a pre-scaled float.

+<pre>

+    float in = *

+    float dither = PaUtil_GenerateFloatTriangularDither( ditherState );

+    // use smaller scaler to prevent overflow when we add the dither

+    signed short out = (signed short)(in*(32766.0f) + dither );

+</pre>

+ @return

+ A float with a range of -2.0 to +1.99999.

+*/

+float PaUtil_GenerateFloatTriangularDither( PaUtilTriangularDitherGenerator *ditherState );

+

+

+

+#ifdef __cplusplus

+}

+#endif /* __cplusplus */

+#endif /* PA_DITHER_H */

diff --git a/src/engine/external/portaudio/pa_endianness.h b/src/engine/external/portaudio/pa_endianness.h
new file mode 100644
index 00000000..9ed317bc
--- /dev/null
+++ b/src/engine/external/portaudio/pa_endianness.h
@@ -0,0 +1,141 @@
+#ifndef PA_ENDIANNESS_H

+#define PA_ENDIANNESS_H

+/*

+ * $Id: pa_endianness.h 1216 2007-06-10 09:26:00Z aknudsen $

+ * Portable Audio I/O Library current platform endianness macros

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Phil Burk, Ross Bencina

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup common_src

+

+ @brief Configure endianness symbols for the target processor.

+

+ Arrange for either the PA_LITTLE_ENDIAN or PA_BIG_ENDIAN preprocessor symbols

+ to be defined. The one that is defined reflects the endianness of the target

+ platform and may be used to implement conditional compilation of byte-order

+ dependent code.

+

+ If either PA_LITTLE_ENDIAN or PA_BIG_ENDIAN is defined already, then no attempt

+ is made to override that setting. This may be useful if you have a better way

+ of determining the platform's endianness. The autoconf mechanism uses this for

+ example.

+

+ A PA_VALIDATE_ENDIANNESS macro is provided to compare the compile time

+ and runtime endiannes and raise an assertion if they don't match.

+*/

+

+

+#ifdef __cplusplus

+extern "C"

+{

+#endif /* __cplusplus */

+

+/* If this is an apple, we need to do detect endianness this way */

+#if defined(__APPLE__)

+    /* we need to do some endian detection that is sensitive to harware arch */

+    #if defined(__LITTLE_ENDIAN__)

+       #if !defined( PA_LITTLE_ENDIAN )

+          #define PA_LITTLE_ENDIAN

+       #endif

+       #if defined( PA_BIG_ENDIAN )

+          #undef PA_BIG_ENDIAN

+       #endif

+    #else

+       #if !defined( PA_BIG_ENDIAN )

+          #define PA_BIG_ENDIAN

+       #endif

+       #if defined( PA_LITTLE_ENDIAN )

+          #undef PA_LITTLE_ENDIAN

+       #endif

+    #endif

+#else

+    /* this is not an apple, so first check the existing defines, and, failing that,

+       detect well-known architechtures. */

+

+    #if defined(PA_LITTLE_ENDIAN) || defined(PA_BIG_ENDIAN)

+        /* endianness define has been set externally, such as by autoconf */

+

+        #if defined(PA_LITTLE_ENDIAN) && defined(PA_BIG_ENDIAN)

+        #error both PA_LITTLE_ENDIAN and PA_BIG_ENDIAN have been defined externally to pa_endianness.h - only one endianness at a time please

+        #endif

+

+    #else

+        /* endianness define has not been set externally */

+

+        /* set PA_LITTLE_ENDIAN or PA_BIG_ENDIAN by testing well known platform specific defines */

+

+        #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) || defined(LITTLE_ENDIAN) || defined(__i386) || defined(_M_IX86) || defined(__x86_64__)

+            #define PA_LITTLE_ENDIAN /* win32, assume intel byte order */

+        #else

+            #define PA_BIG_ENDIAN

+        #endif

+    #endif

+

+    #if !defined(PA_LITTLE_ENDIAN) && !defined(PA_BIG_ENDIAN)

+        /*

+         If the following error is raised, you either need to modify the code above

+         to automatically determine the endianness from other symbols defined on your

+         platform, or define either PA_LITTLE_ENDIAN or PA_BIG_ENDIAN externally.

+        */

+        #error pa_endianness.h was unable to automatically determine the endianness of the target platform

+    #endif

+

+#endif

+

+

+/* PA_VALIDATE_ENDIANNESS compares the compile time and runtime endianness,

+ and raises an assertion if they don't match. <assert.h> must be included in

+ the context in which this macro is used.

+*/

+#if defined(PA_LITTLE_ENDIAN)

+    #define PA_VALIDATE_ENDIANNESS \

+    { \

+        const long nativeOne = 1; \

+        assert( "PortAudio: compile time and runtime endianness don't match" && (((char *)&nativeOne)[0]) == 1 ); \

+    }

+#elif defined(PA_BIG_ENDIAN)

+    #define PA_VALIDATE_ENDIANNESS \

+    { \

+        const long nativeOne = 1; \

+        assert( "PortAudio: compile time and runtime endianness don't match" && (((char *)&nativeOne)[0]) == 0 ); \

+    }

+#endif

+

+

+#ifdef __cplusplus

+}

+#endif /* __cplusplus */

+#endif /* PA_ENDIANNESS_H */

diff --git a/src/engine/external/portaudio/pa_front.c b/src/engine/external/portaudio/pa_front.c
new file mode 100644
index 00000000..ac04855c
--- /dev/null
+++ b/src/engine/external/portaudio/pa_front.c
@@ -0,0 +1,1760 @@
+/*

+ * $Id: pa_front.c 1229 2007-06-15 16:11:11Z rossb $

+ * Portable Audio I/O Library Multi-Host API front end

+ * Validate function parameters and manage multiple host APIs.

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup common_src

+

+ @brief Implements public PortAudio API, checks some errors, forwards to

+ host API implementations.

+ 

+ Implements the functions defined in the PortAudio API, checks for

+ some parameter and state inconsistencies and forwards API requests to

+ specific Host API implementations (via the interface declared in

+ pa_hostapi.h), and Streams (via the interface declared in pa_stream.h).

+

+ This file handles initialization and termination of Host API

+ implementations via initializers stored in the paHostApiInitializers

+ global variable.

+

+ Some utility functions declared in pa_util.h are implemented in this file.

+

+ All PortAudio API functions can be conditionally compiled with logging code.

+ To compile with logging, define the PA_LOG_API_CALLS precompiler symbol.

+

+    @todo Consider adding host API specific error text in Pa_GetErrorText() for

+    paUnanticipatedHostError

+

+    @todo Consider adding a new error code for when (inputParameters == NULL)

+    && (outputParameters == NULL)

+

+    @todo review whether Pa_CloseStream() should call the interface's

+    CloseStream function if aborting the stream returns an error code.

+

+    @todo Create new error codes if a NULL buffer pointer, or a

+    zero frame count is passed to Pa_ReadStream or Pa_WriteStream.

+*/

+

+

+#include <stdio.h>

+#include <memory.h>

+#include <string.h>

+#include <assert.h> /* needed by PA_VALIDATE_ENDIANNESS */

+

+#include "portaudio.h"

+#include "pa_util.h"

+#include "pa_endianness.h"

+#include "pa_types.h"

+#include "pa_hostapi.h"

+#include "pa_stream.h"

+#include "pa_trace.h" /* still usefull?*/

+#include "pa_debugprint.h"

+

+

+#define PA_VERSION_  1899

+#define PA_VERSION_TEXT_ "PortAudio V19-devel (built " __DATE__  ")"

+

+

+

+

+int Pa_GetVersion( void )

+{

+    return PA_VERSION_;

+}

+

+

+const char* Pa_GetVersionText( void )

+{

+    return PA_VERSION_TEXT_;

+}

+

+

+

+#define PA_LAST_HOST_ERROR_TEXT_LENGTH_  1024

+

+static char lastHostErrorText_[ PA_LAST_HOST_ERROR_TEXT_LENGTH_ + 1 ] = {0};

+

+static PaHostErrorInfo lastHostErrorInfo_ = { (PaHostApiTypeId)-1, 0, lastHostErrorText_ };

+

+

+void PaUtil_SetLastHostErrorInfo( PaHostApiTypeId hostApiType, long errorCode,

+        const char *errorText )

+{

+    lastHostErrorInfo_.hostApiType = hostApiType;

+    lastHostErrorInfo_.errorCode = errorCode;

+

+    strncpy( lastHostErrorText_, errorText, PA_LAST_HOST_ERROR_TEXT_LENGTH_ );

+}

+

+

+

+static PaUtilHostApiRepresentation **hostApis_ = 0;

+static int hostApisCount_ = 0;

+static int initializationCount_ = 0;

+static int deviceCount_ = 0;

+

+PaUtilStreamRepresentation *firstOpenStream_ = NULL;

+

+

+#define PA_IS_INITIALISED_ (initializationCount_ != 0)

+

+

+static int CountHostApiInitializers( void )

+{

+    int result = 0;

+

+    while( paHostApiInitializers[ result ] != 0 )

+        ++result;

+    return result;

+}

+

+

+static void TerminateHostApis( void )

+{

+    /* terminate in reverse order from initialization */

+    PA_DEBUG(("TerminateHostApis in \n"));

+

+    while( hostApisCount_ > 0 )

+    {

+        --hostApisCount_;

+        hostApis_[hostApisCount_]->Terminate( hostApis_[hostApisCount_] );

+    }

+    hostApisCount_ = 0;

+    deviceCount_ = 0;

+

+    if( hostApis_ != 0 )

+        PaUtil_FreeMemory( hostApis_ );

+    hostApis_ = 0;

+

+    PA_DEBUG(("TerminateHostApis out\n"));

+}

+

+

+static PaError InitializeHostApis( void )

+{

+    PaError result = paNoError;

+    int i, initializerCount, baseDeviceIndex;

+

+    initializerCount = CountHostApiInitializers();

+

+    hostApis_ = (PaUtilHostApiRepresentation**)PaUtil_AllocateMemory(

+            sizeof(PaUtilHostApiRepresentation*) * initializerCount );

+    if( !hostApis_ )

+    {

+        result = paInsufficientMemory;

+        goto error; 

+    }

+

+    hostApisCount_ = 0;

+    deviceCount_ = 0;

+    baseDeviceIndex = 0;

+

+    for( i=0; i< initializerCount; ++i )

+    {

+        hostApis_[hostApisCount_] = NULL;

+

+        PA_DEBUG(( "before paHostApiInitializers[%d].\n",i));

+

+        result = paHostApiInitializers[i]( &hostApis_[hostApisCount_], hostApisCount_ );

+        if( result != paNoError )

+            goto error;

+

+        PA_DEBUG(( "after paHostApiInitializers[%d].\n",i));

+

+        if( hostApis_[hostApisCount_] )

+        {

+            PaUtilHostApiRepresentation* hostApi = hostApis_[hostApisCount_];

+            assert( hostApi->info.defaultInputDevice < hostApi->info.deviceCount );

+            assert( hostApi->info.defaultOutputDevice < hostApi->info.deviceCount );

+

+            hostApi->privatePaFrontInfo.baseDeviceIndex = baseDeviceIndex;

+

+            if( hostApi->info.defaultInputDevice != paNoDevice )

+                hostApi->info.defaultInputDevice += baseDeviceIndex;

+

+            if( hostApi->info.defaultOutputDevice != paNoDevice )

+                hostApi->info.defaultOutputDevice += baseDeviceIndex;

+

+            baseDeviceIndex += hostApi->info.deviceCount;

+            deviceCount_ += hostApi->info.deviceCount;

+

+            ++hostApisCount_;

+        }

+    }

+

+    return result;

+

+error:

+    TerminateHostApis();

+    return result;

+}

+

+

+/*

+    FindHostApi() finds the index of the host api to which

+    <device> belongs and returns it. if <hostSpecificDeviceIndex> is

+    non-null, the host specific device index is returned in it.

+    returns -1 if <device> is out of range.

+ 

+*/

+static int FindHostApi( PaDeviceIndex device, int *hostSpecificDeviceIndex )

+{

+    int i=0;

+

+    if( !PA_IS_INITIALISED_ )

+        return -1;

+

+    if( device < 0 )

+        return -1;

+

+    while( i < hostApisCount_

+            && device >= hostApis_[i]->info.deviceCount )

+    {

+

+        device -= hostApis_[i]->info.deviceCount;

+        ++i;

+    }

+

+    if( i >= hostApisCount_ )

+        return -1;

+

+    if( hostSpecificDeviceIndex )

+        *hostSpecificDeviceIndex = device;

+

+    return i;

+}

+

+

+static void AddOpenStream( PaStream* stream )

+{

+    ((PaUtilStreamRepresentation*)stream)->nextOpenStream = firstOpenStream_;

+    firstOpenStream_ = (PaUtilStreamRepresentation*)stream;

+}

+

+

+static void RemoveOpenStream( PaStream* stream )

+{

+    PaUtilStreamRepresentation *previous = NULL;

+    PaUtilStreamRepresentation *current = firstOpenStream_;

+

+    while( current != NULL )

+    {

+        if( ((PaStream*)current) == stream )

+        {

+            if( previous == NULL )

+            {

+                firstOpenStream_ = current->nextOpenStream;

+            }

+            else

+            {

+                previous->nextOpenStream = current->nextOpenStream;

+            }

+            return;

+        }

+        else

+        {

+            previous = current;

+            current = current->nextOpenStream;

+        }

+    }

+}

+

+

+static void CloseOpenStreams( void )

+{

+    /* we call Pa_CloseStream() here to ensure that the same destruction

+        logic is used for automatically closed streams */

+

+    while( firstOpenStream_ != NULL )

+        Pa_CloseStream( firstOpenStream_ );

+}

+

+

+PaError Pa_Initialize( void )

+{

+    PaError result;

+

+    PA_LOGAPI_ENTER( "Pa_Initialize" );

+

+    if( PA_IS_INITIALISED_ )

+    {

+        ++initializationCount_;

+        result = paNoError;

+    }

+    else

+    {

+        PA_VALIDATE_TYPE_SIZES;

+        PA_VALIDATE_ENDIANNESS;

+        

+        PaUtil_InitializeClock();

+        PaUtil_ResetTraceMessages();

+

+        result = InitializeHostApis();

+        if( result == paNoError )

+            ++initializationCount_;

+    }

+

+    PA_LOGAPI_EXIT_PAERROR( "Pa_Initialize", result );

+

+    return result;

+}

+

+

+PaError Pa_Terminate( void )

+{

+    PaError result;

+

+    PA_LOGAPI_ENTER( "Pa_Terminate" );

+

+    if( PA_IS_INITIALISED_ )

+    {

+        if( --initializationCount_ == 0 )

+        {

+            CloseOpenStreams();

+

+            TerminateHostApis();

+

+            PaUtil_DumpTraceMessages();

+        }

+        result = paNoError;

+    }

+    else

+    {

+        result=  paNotInitialized;

+    }

+

+    PA_LOGAPI_EXIT_PAERROR( "Pa_Terminate", result );

+

+    return result;

+}

+

+

+const PaHostErrorInfo* Pa_GetLastHostErrorInfo( void )

+{

+    return &lastHostErrorInfo_;

+}

+

+

+const char *Pa_GetErrorText( PaError errorCode )

+{

+    const char *result;

+

+    switch( errorCode )

+    {

+    case paNoError:                  result = "Success"; break;

+    case paNotInitialized:           result = "PortAudio not initialized"; break;

+    /** @todo could catenate the last host error text to result in the case of paUnanticipatedHostError */

+    case paUnanticipatedHostError:   result = "Unanticipated host error"; break;

+    case paInvalidChannelCount:      result = "Invalid number of channels"; break;

+    case paInvalidSampleRate:        result = "Invalid sample rate"; break;

+    case paInvalidDevice:            result = "Invalid device"; break;

+    case paInvalidFlag:              result = "Invalid flag"; break;

+    case paSampleFormatNotSupported: result = "Sample format not supported"; break;

+    case paBadIODeviceCombination:   result = "Illegal combination of I/O devices"; break;

+    case paInsufficientMemory:       result = "Insufficient memory"; break;

+    case paBufferTooBig:             result = "Buffer too big"; break;

+    case paBufferTooSmall:           result = "Buffer too small"; break;

+    case paNullCallback:             result = "No callback routine specified"; break;

+    case paBadStreamPtr:             result = "Invalid stream pointer"; break;

+    case paTimedOut:                 result = "Wait timed out"; break;

+    case paInternalError:            result = "Internal PortAudio error"; break;

+    case paDeviceUnavailable:        result = "Device unavailable"; break;

+    case paIncompatibleHostApiSpecificStreamInfo:   result = "Incompatible host API specific stream info"; break;

+    case paStreamIsStopped:          result = "Stream is stopped"; break;

+    case paStreamIsNotStopped:       result = "Stream is not stopped"; break;

+    case paInputOverflowed:          result = "Input overflowed"; break;

+    case paOutputUnderflowed:        result = "Output underflowed"; break;

+    case paHostApiNotFound:          result = "Host API not found"; break;

+    case paInvalidHostApi:           result = "Invalid host API"; break;

+    case paCanNotReadFromACallbackStream:       result = "Can't read from a callback stream"; break;

+    case paCanNotWriteToACallbackStream:        result = "Can't write to a callback stream"; break;

+    case paCanNotReadFromAnOutputOnlyStream:    result = "Can't read from an output only stream"; break;

+    case paCanNotWriteToAnInputOnlyStream:      result = "Can't write to an input only stream"; break;

+    default:                         

+		if( errorCode > 0 )

+			result = "Invalid error code (value greater than zero)"; 

+        else

+			result = "Invalid error code"; 

+        break;

+    }

+    return result;

+}

+

+

+PaHostApiIndex Pa_HostApiTypeIdToHostApiIndex( PaHostApiTypeId type )

+{

+    PaHostApiIndex result;

+    int i;

+    

+    PA_LOGAPI_ENTER_PARAMS( "Pa_HostApiTypeIdToHostApiIndex" );

+    PA_LOGAPI(("\tPaHostApiTypeId type: %d\n", type ));

+

+    if( !PA_IS_INITIALISED_ )

+    {

+        result = paNotInitialized;

+    }

+    else

+    {

+        result = paHostApiNotFound;

+        

+        for( i=0; i < hostApisCount_; ++i )

+        {

+            if( hostApis_[i]->info.type == type )

+            {

+                result = i;

+                break;

+            }         

+        }

+    }

+

+    PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( "Pa_HostApiTypeIdToHostApiIndex", "PaHostApiIndex: %d", result );

+

+    return result;

+}

+

+

+PaError PaUtil_GetHostApiRepresentation( struct PaUtilHostApiRepresentation **hostApi,

+        PaHostApiTypeId type )

+{

+    PaError result;

+    int i;

+    

+    if( !PA_IS_INITIALISED_ )

+    {

+        result = paNotInitialized;

+    }

+    else

+    {

+        result = paHostApiNotFound;

+                

+        for( i=0; i < hostApisCount_; ++i )

+        {

+            if( hostApis_[i]->info.type == type )

+            {

+                *hostApi = hostApis_[i];

+                result = paNoError;

+                break;

+            }

+        }

+    }

+

+    return result;

+}

+

+

+PaError PaUtil_DeviceIndexToHostApiDeviceIndex(

+        PaDeviceIndex *hostApiDevice, PaDeviceIndex device, struct PaUtilHostApiRepresentation *hostApi )

+{

+    PaError result;

+    PaDeviceIndex x;

+    

+    x = device - hostApi->privatePaFrontInfo.baseDeviceIndex;

+

+    if( x < 0 || x >= hostApi->info.deviceCount )

+    {

+        result = paInvalidDevice;

+    }

+    else

+    {

+        *hostApiDevice = x;

+        result = paNoError;

+    }

+

+    return result;

+}

+

+

+PaHostApiIndex Pa_GetHostApiCount( void )

+{

+    int result;

+

+    PA_LOGAPI_ENTER( "Pa_GetHostApiCount" );

+

+    if( !PA_IS_INITIALISED_ )

+    {

+        result = paNotInitialized;

+    }

+    else

+    {

+        result = hostApisCount_;

+    }

+

+    PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( "Pa_GetHostApiCount", "PaHostApiIndex: %d", result );

+

+    return result;

+}

+

+

+PaHostApiIndex Pa_GetDefaultHostApi( void )

+{

+    int result;

+

+    PA_LOGAPI_ENTER( "Pa_GetDefaultHostApi" );

+

+    if( !PA_IS_INITIALISED_ )

+    {

+        result = paNotInitialized;

+    }

+    else

+    {

+        result = paDefaultHostApiIndex;

+

+        /* internal consistency check: make sure that the default host api

+         index is within range */

+

+        if( result < 0 || result >= hostApisCount_ )

+        {

+            result = paInternalError;

+        }

+    }

+

+    PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( "Pa_GetDefaultHostApi", "PaHostApiIndex: %d", result );

+

+    return result;

+}

+

+

+const PaHostApiInfo* Pa_GetHostApiInfo( PaHostApiIndex hostApi )

+{

+    PaHostApiInfo *info;

+

+    PA_LOGAPI_ENTER_PARAMS( "Pa_GetHostApiInfo" );

+    PA_LOGAPI(("\tPaHostApiIndex hostApi: %d\n", hostApi ));

+

+    if( !PA_IS_INITIALISED_ )

+    {

+        info = NULL;

+

+        PA_LOGAPI(("Pa_GetHostApiInfo returned:\n" ));

+        PA_LOGAPI(("\tPaHostApiInfo*: NULL [ PortAudio not initialized ]\n" ));

+

+    }

+    else if( hostApi < 0 || hostApi >= hostApisCount_ )

+    {

+        info = NULL;

+        

+        PA_LOGAPI(("Pa_GetHostApiInfo returned:\n" ));

+        PA_LOGAPI(("\tPaHostApiInfo*: NULL [ hostApi out of range ]\n" ));

+

+    }

+    else

+    {

+        info = &hostApis_[hostApi]->info;

+

+        PA_LOGAPI(("Pa_GetHostApiInfo returned:\n" ));

+        PA_LOGAPI(("\tPaHostApiInfo*: 0x%p\n", info ));

+        PA_LOGAPI(("\t{\n" ));

+        PA_LOGAPI(("\t\tint structVersion: %d\n", info->structVersion ));

+        PA_LOGAPI(("\t\tPaHostApiTypeId type: %d\n", info->type ));

+        PA_LOGAPI(("\t\tconst char *name: %s\n", info->name ));

+        PA_LOGAPI(("\t}\n" ));

+

+    }

+

+     return info;

+}

+

+

+PaDeviceIndex Pa_HostApiDeviceIndexToDeviceIndex( PaHostApiIndex hostApi, int hostApiDeviceIndex )

+{

+    PaDeviceIndex result;

+

+    PA_LOGAPI_ENTER_PARAMS( "Pa_HostApiDeviceIndexToPaDeviceIndex" );

+    PA_LOGAPI(("\tPaHostApiIndex hostApi: %d\n", hostApi ));

+    PA_LOGAPI(("\tint hostApiDeviceIndex: %d\n", hostApiDeviceIndex ));

+

+    if( !PA_IS_INITIALISED_ )

+    {

+        result = paNotInitialized;

+    }

+    else

+    {

+        if( hostApi < 0 || hostApi >= hostApisCount_ )

+        {

+            result = paInvalidHostApi;

+        }

+        else

+        {

+            if( hostApiDeviceIndex < 0 ||

+                    hostApiDeviceIndex >= hostApis_[hostApi]->info.deviceCount )

+            {

+                result = paInvalidDevice;

+            }

+            else

+            {

+                result = hostApis_[hostApi]->privatePaFrontInfo.baseDeviceIndex + hostApiDeviceIndex;

+            }

+        }

+    }

+

+    PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( "Pa_HostApiDeviceIndexToPaDeviceIndex", "PaDeviceIndex: %d", result );

+

+    return result;

+}

+

+

+PaDeviceIndex Pa_GetDeviceCount( void )

+{

+    PaDeviceIndex result;

+

+    PA_LOGAPI_ENTER( "Pa_GetDeviceCount" );

+

+    if( !PA_IS_INITIALISED_ )

+    {

+        result = paNotInitialized;

+    }

+    else

+    {

+        result = deviceCount_;

+    }

+

+    PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( "Pa_GetDeviceCount", "PaDeviceIndex: %d", result );

+

+    return result;

+}

+

+

+PaDeviceIndex Pa_GetDefaultInputDevice( void )

+{

+    PaHostApiIndex hostApi;

+    PaDeviceIndex result;

+

+    PA_LOGAPI_ENTER( "Pa_GetDefaultInputDevice" );

+

+    hostApi = Pa_GetDefaultHostApi();

+    if( hostApi < 0 )

+    {

+        result = paNoDevice;

+    }

+    else

+    {

+        result = hostApis_[hostApi]->info.defaultInputDevice;

+    }

+

+    PA_LOGAPI_EXIT_T( "Pa_GetDefaultInputDevice", "PaDeviceIndex: %d", result );

+

+    return result;

+}

+

+

+PaDeviceIndex Pa_GetDefaultOutputDevice( void )

+{

+    PaHostApiIndex hostApi;

+    PaDeviceIndex result;

+    

+    PA_LOGAPI_ENTER( "Pa_GetDefaultOutputDevice" );

+

+    hostApi = Pa_GetDefaultHostApi();

+    if( hostApi < 0 )

+    {

+        result = paNoDevice;

+    }

+    else

+    {

+        result = hostApis_[hostApi]->info.defaultOutputDevice;

+    }

+

+    PA_LOGAPI_EXIT_T( "Pa_GetDefaultOutputDevice", "PaDeviceIndex: %d", result );

+

+    return result;

+}

+

+

+const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceIndex device )

+{

+    int hostSpecificDeviceIndex;

+    int hostApiIndex = FindHostApi( device, &hostSpecificDeviceIndex );

+    PaDeviceInfo *result;

+

+

+    PA_LOGAPI_ENTER_PARAMS( "Pa_GetDeviceInfo" );

+    PA_LOGAPI(("\tPaDeviceIndex device: %d\n", device ));

+

+    if( hostApiIndex < 0 )

+    {

+        result = NULL;

+

+        PA_LOGAPI(("Pa_GetDeviceInfo returned:\n" ));

+        PA_LOGAPI(("\tPaDeviceInfo* NULL [ invalid device index ]\n" ));

+

+    }

+    else

+    {

+        result = hostApis_[hostApiIndex]->deviceInfos[ hostSpecificDeviceIndex ];

+

+        PA_LOGAPI(("Pa_GetDeviceInfo returned:\n" ));

+        PA_LOGAPI(("\tPaDeviceInfo*: 0x%p:\n", result ));

+        PA_LOGAPI(("\t{\n" ));

+

+        PA_LOGAPI(("\t\tint structVersion: %d\n", result->structVersion ));

+        PA_LOGAPI(("\t\tconst char *name: %s\n", result->name ));

+        PA_LOGAPI(("\t\tPaHostApiIndex hostApi: %d\n", result->hostApi ));

+        PA_LOGAPI(("\t\tint maxInputChannels: %d\n", result->maxInputChannels ));

+        PA_LOGAPI(("\t\tint maxOutputChannels: %d\n", result->maxOutputChannels ));

+        PA_LOGAPI(("\t}\n" ));

+

+    }

+

+    return result;

+}

+

+

+/*

+    SampleFormatIsValid() returns 1 if sampleFormat is a sample format

+    defined in portaudio.h, or 0 otherwise.

+*/

+static int SampleFormatIsValid( PaSampleFormat format )

+{

+    switch( format & ~paNonInterleaved )

+    {

+    case paFloat32: return 1;

+    case paInt16: return 1;

+    case paInt32: return 1;

+    case paInt24: return 1;

+    case paInt8: return 1;

+    case paUInt8: return 1;

+    case paCustomFormat: return 1;

+    default: return 0;

+    }

+}

+

+/*

+    NOTE: make sure this validation list is kept syncronised with the one in

+            pa_hostapi.h

+

+    ValidateOpenStreamParameters() checks that parameters to Pa_OpenStream()

+    conform to the expected values as described below. This function is

+    also designed to be used with the proposed Pa_IsFormatSupported() function.

+    

+    There are basically two types of validation that could be performed:

+    Generic conformance validation, and device capability mismatch

+    validation. This function performs only generic conformance validation.

+    Validation that would require knowledge of device capabilities is

+    not performed because of potentially complex relationships between

+    combinations of parameters - for example, even if the sampleRate

+    seems ok, it might not be for a duplex stream - we have no way of

+    checking this in an API-neutral way, so we don't try.

+ 

+    On success the function returns PaNoError and fills in hostApi,

+    hostApiInputDeviceID, and hostApiOutputDeviceID fields. On failure

+    the function returns an error code indicating the first encountered

+    parameter error.

+ 

+ 

+    If ValidateOpenStreamParameters() returns paNoError, the following

+    assertions are guaranteed to be true.

+ 

+    - at least one of inputParameters & outputParmeters is valid (not NULL)

+

+    - if inputParameters & outputParameters are both valid, that

+        inputParameters->device & outputParameters->device  both use the same host api

+ 

+    PaDeviceIndex inputParameters->device

+        - is within range (0 to Pa_GetDeviceCount-1) Or:

+        - is paUseHostApiSpecificDeviceSpecification and

+            inputParameters->hostApiSpecificStreamInfo is non-NULL and refers

+            to a valid host api

+

+    int inputParameters->channelCount

+        - if inputParameters->device is not paUseHostApiSpecificDeviceSpecification, channelCount is > 0

+        - upper bound is NOT validated against device capabilities

+ 

+    PaSampleFormat inputParameters->sampleFormat

+        - is one of the sample formats defined in portaudio.h

+

+    void *inputParameters->hostApiSpecificStreamInfo

+        - if supplied its hostApi field matches the input device's host Api

+ 

+    PaDeviceIndex outputParmeters->device

+        - is within range (0 to Pa_GetDeviceCount-1)

+ 

+    int outputParmeters->channelCount

+        - if inputDevice is valid, channelCount is > 0

+        - upper bound is NOT validated against device capabilities

+ 

+    PaSampleFormat outputParmeters->sampleFormat

+        - is one of the sample formats defined in portaudio.h

+        

+    void *outputParmeters->hostApiSpecificStreamInfo

+        - if supplied its hostApi field matches the output device's host Api

+ 

+    double sampleRate

+        - is not an 'absurd' rate (less than 1000. or greater than 200000.)

+        - sampleRate is NOT validated against device capabilities

+ 

+    PaStreamFlags streamFlags

+        - unused platform neutral flags are zero

+        - paNeverDropInput is only used for full-duplex callback streams with

+            variable buffer size (paFramesPerBufferUnspecified)

+*/

+static PaError ValidateOpenStreamParameters(

+    const PaStreamParameters *inputParameters,

+    const PaStreamParameters *outputParameters,

+    double sampleRate,

+    unsigned long framesPerBuffer,

+    PaStreamFlags streamFlags,

+    PaStreamCallback *streamCallback,

+    PaUtilHostApiRepresentation **hostApi,

+    PaDeviceIndex *hostApiInputDevice,

+    PaDeviceIndex *hostApiOutputDevice )

+{

+    int inputHostApiIndex  = -1, /* Surpress uninitialised var warnings: compiler does */

+        outputHostApiIndex = -1; /* not see that if inputParameters and outputParame-  */

+                                 /* ters are both nonzero, these indices are set.      */

+

+    if( (inputParameters == NULL) && (outputParameters == NULL) )

+    {

+        return paInvalidDevice; /** @todo should be a new error code "invalid device parameters" or something */

+    }

+    else

+    {

+        if( inputParameters == NULL )

+        {

+            *hostApiInputDevice = paNoDevice;

+        }

+        else if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )

+        {

+            if( inputParameters->hostApiSpecificStreamInfo )

+            {

+                inputHostApiIndex = Pa_HostApiTypeIdToHostApiIndex(

+                        ((PaUtilHostApiSpecificStreamInfoHeader*)inputParameters->hostApiSpecificStreamInfo)->hostApiType );

+

+                if( inputHostApiIndex != -1 )

+                {

+                    *hostApiInputDevice = paUseHostApiSpecificDeviceSpecification;

+                    *hostApi = hostApis_[inputHostApiIndex];

+                }

+                else

+                {

+                    return paInvalidDevice;

+                }

+            }

+            else

+            {

+                return paInvalidDevice;

+            }

+        }

+        else

+        {

+            if( inputParameters->device < 0 || inputParameters->device >= deviceCount_ )

+                return paInvalidDevice;

+

+            inputHostApiIndex = FindHostApi( inputParameters->device, hostApiInputDevice );

+            if( inputHostApiIndex < 0 )

+                return paInternalError;

+

+            *hostApi = hostApis_[inputHostApiIndex];

+

+            if( inputParameters->channelCount <= 0 )

+                return paInvalidChannelCount;

+

+            if( !SampleFormatIsValid( inputParameters->sampleFormat ) )

+                return paSampleFormatNotSupported;

+

+            if( inputParameters->hostApiSpecificStreamInfo != NULL )

+            {

+                if( ((PaUtilHostApiSpecificStreamInfoHeader*)inputParameters->hostApiSpecificStreamInfo)->hostApiType

+                        != (*hostApi)->info.type )

+                    return paIncompatibleHostApiSpecificStreamInfo;

+            }

+        }

+

+        if( outputParameters == NULL )

+        {

+            *hostApiOutputDevice = paNoDevice;

+        }

+        else if( outputParameters->device == paUseHostApiSpecificDeviceSpecification  )

+        {

+            if( outputParameters->hostApiSpecificStreamInfo )

+            {

+                outputHostApiIndex = Pa_HostApiTypeIdToHostApiIndex(

+                        ((PaUtilHostApiSpecificStreamInfoHeader*)outputParameters->hostApiSpecificStreamInfo)->hostApiType );

+

+                if( outputHostApiIndex != -1 )

+                {

+                    *hostApiOutputDevice = paUseHostApiSpecificDeviceSpecification;

+                    *hostApi = hostApis_[outputHostApiIndex];

+                }

+                else

+                {

+                    return paInvalidDevice;

+                }

+            }

+            else

+            {

+                return paInvalidDevice;

+            }

+        }

+        else

+        {

+            if( outputParameters->device < 0 || outputParameters->device >= deviceCount_ )

+                return paInvalidDevice;

+

+            outputHostApiIndex = FindHostApi( outputParameters->device, hostApiOutputDevice );

+            if( outputHostApiIndex < 0 )

+                return paInternalError;

+

+            *hostApi = hostApis_[outputHostApiIndex];

+

+            if( outputParameters->channelCount <= 0 )

+                return paInvalidChannelCount;

+

+            if( !SampleFormatIsValid( outputParameters->sampleFormat ) )

+                return paSampleFormatNotSupported;

+

+            if( outputParameters->hostApiSpecificStreamInfo != NULL )

+            {

+                if( ((PaUtilHostApiSpecificStreamInfoHeader*)outputParameters->hostApiSpecificStreamInfo)->hostApiType

+                        != (*hostApi)->info.type )

+                    return paIncompatibleHostApiSpecificStreamInfo;

+            }

+        }   

+

+        if( (inputParameters != NULL) && (outputParameters != NULL) )

+        {

+            /* ensure that both devices use the same API */

+            if( inputHostApiIndex != outputHostApiIndex )

+                return paBadIODeviceCombination;

+        }

+    }

+    

+    

+    /* Check for absurd sample rates. */

+    if( (sampleRate < 1000.0) || (sampleRate > 200000.0) )

+        return paInvalidSampleRate;

+

+    if( ((streamFlags & ~paPlatformSpecificFlags) & ~(paClipOff | paDitherOff | paNeverDropInput | paPrimeOutputBuffersUsingStreamCallback ) ) != 0 )

+        return paInvalidFlag;

+

+    if( streamFlags & paNeverDropInput )

+    {

+        /* must be a callback stream */

+        if( !streamCallback )

+             return paInvalidFlag;

+

+        /* must be a full duplex stream */

+        if( (inputParameters == NULL) || (outputParameters == NULL) )

+            return paInvalidFlag;

+

+        /* must use paFramesPerBufferUnspecified */

+        if( framesPerBuffer != paFramesPerBufferUnspecified )

+            return paInvalidFlag;

+    }

+    

+    return paNoError;

+}

+

+

+PaError Pa_IsFormatSupported( const PaStreamParameters *inputParameters,

+                              const PaStreamParameters *outputParameters,

+                              double sampleRate )

+{

+    PaError result;

+    PaUtilHostApiRepresentation *hostApi = 0;

+    PaDeviceIndex hostApiInputDevice = paNoDevice, hostApiOutputDevice = paNoDevice;

+    PaStreamParameters hostApiInputParameters, hostApiOutputParameters;

+    PaStreamParameters *hostApiInputParametersPtr, *hostApiOutputParametersPtr;

+

+

+#ifdef PA_LOG_API_CALLS

+    PA_LOGAPI_ENTER_PARAMS( "Pa_IsFormatSupported" );

+

+    if( inputParameters == NULL ){

+        PA_LOGAPI(("\tPaStreamParameters *inputParameters: NULL\n" ));

+    }else{

+        PA_LOGAPI(("\tPaStreamParameters *inputParameters: 0x%p\n", inputParameters ));

+        PA_LOGAPI(("\tPaDeviceIndex inputParameters->device: %d\n", inputParameters->device ));

+        PA_LOGAPI(("\tint inputParameters->channelCount: %d\n", inputParameters->channelCount ));

+        PA_LOGAPI(("\tPaSampleFormat inputParameters->sampleFormat: %d\n", inputParameters->sampleFormat ));

+        PA_LOGAPI(("\tPaTime inputParameters->suggestedLatency: %f\n", inputParameters->suggestedLatency ));

+        PA_LOGAPI(("\tvoid *inputParameters->hostApiSpecificStreamInfo: 0x%p\n", inputParameters->hostApiSpecificStreamInfo ));

+    }

+

+    if( outputParameters == NULL ){

+        PA_LOGAPI(("\tPaStreamParameters *outputParameters: NULL\n" ));

+    }else{

+        PA_LOGAPI(("\tPaStreamParameters *outputParameters: 0x%p\n", outputParameters ));

+        PA_LOGAPI(("\tPaDeviceIndex outputParameters->device: %d\n", outputParameters->device ));

+        PA_LOGAPI(("\tint outputParameters->channelCount: %d\n", outputParameters->channelCount ));

+        PA_LOGAPI(("\tPaSampleFormat outputParameters->sampleFormat: %d\n", outputParameters->sampleFormat ));

+        PA_LOGAPI(("\tPaTime outputParameters->suggestedLatency: %f\n", outputParameters->suggestedLatency ));

+        PA_LOGAPI(("\tvoid *outputParameters->hostApiSpecificStreamInfo: 0x%p\n", outputParameters->hostApiSpecificStreamInfo ));

+    }

+    

+    PA_LOGAPI(("\tdouble sampleRate: %g\n", sampleRate ));

+#endif

+

+    if( !PA_IS_INITIALISED_ )

+    {

+        result = paNotInitialized;

+

+        PA_LOGAPI_EXIT_PAERROR( "Pa_IsFormatSupported", result );

+        return result;

+    }

+

+    result = ValidateOpenStreamParameters( inputParameters,

+                                           outputParameters,

+                                           sampleRate, 0, paNoFlag, 0,

+                                           &hostApi,

+                                           &hostApiInputDevice,

+                                           &hostApiOutputDevice );

+    if( result != paNoError )

+    {

+        PA_LOGAPI_EXIT_PAERROR( "Pa_IsFormatSupported", result );

+        return result;

+    }

+    

+

+    if( inputParameters )

+    {

+        hostApiInputParameters.device = hostApiInputDevice;

+        hostApiInputParameters.channelCount = inputParameters->channelCount;

+        hostApiInputParameters.sampleFormat = inputParameters->sampleFormat;

+        hostApiInputParameters.suggestedLatency = inputParameters->suggestedLatency;

+        hostApiInputParameters.hostApiSpecificStreamInfo = inputParameters->hostApiSpecificStreamInfo;

+        hostApiInputParametersPtr = &hostApiInputParameters;

+    }

+    else

+    {

+        hostApiInputParametersPtr = NULL;

+    }

+

+    if( outputParameters )

+    {

+        hostApiOutputParameters.device = hostApiOutputDevice;

+        hostApiOutputParameters.channelCount = outputParameters->channelCount;

+        hostApiOutputParameters.sampleFormat = outputParameters->sampleFormat;

+        hostApiOutputParameters.suggestedLatency = outputParameters->suggestedLatency;

+        hostApiOutputParameters.hostApiSpecificStreamInfo = outputParameters->hostApiSpecificStreamInfo;

+        hostApiOutputParametersPtr = &hostApiOutputParameters;

+    }

+    else

+    {

+        hostApiOutputParametersPtr = NULL;

+    }

+

+    result = hostApi->IsFormatSupported( hostApi,

+                                  hostApiInputParametersPtr, hostApiOutputParametersPtr,

+                                  sampleRate );

+

+#ifdef PA_LOG_API_CALLS

+    PA_LOGAPI(("Pa_OpenStream returned:\n" ));

+    if( result == paFormatIsSupported )

+        PA_LOGAPI(("\tPaError: 0 [ paFormatIsSupported ]\n" ));

+    else

+        PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));

+#endif

+

+    return result;

+}

+

+

+PaError Pa_OpenStream( PaStream** stream,

+                       const PaStreamParameters *inputParameters,

+                       const PaStreamParameters *outputParameters,

+                       double sampleRate,

+                       unsigned long framesPerBuffer,

+                       PaStreamFlags streamFlags,

+                       PaStreamCallback *streamCallback,

+                       void *userData )

+{

+    PaError result;

+    PaUtilHostApiRepresentation *hostApi = 0;

+    PaDeviceIndex hostApiInputDevice = paNoDevice, hostApiOutputDevice = paNoDevice;

+    PaStreamParameters hostApiInputParameters, hostApiOutputParameters;

+    PaStreamParameters *hostApiInputParametersPtr, *hostApiOutputParametersPtr;

+

+

+#ifdef PA_LOG_API_CALLS

+    PA_LOGAPI_ENTER_PARAMS( "Pa_OpenStream" );

+    PA_LOGAPI(("\tPaStream** stream: 0x%p\n", stream ));

+

+    if( inputParameters == NULL ){

+        PA_LOGAPI(("\tPaStreamParameters *inputParameters: NULL\n" ));

+    }else{

+        PA_LOGAPI(("\tPaStreamParameters *inputParameters: 0x%p\n", inputParameters ));

+        PA_LOGAPI(("\tPaDeviceIndex inputParameters->device: %d\n", inputParameters->device ));

+        PA_LOGAPI(("\tint inputParameters->channelCount: %d\n", inputParameters->channelCount ));

+        PA_LOGAPI(("\tPaSampleFormat inputParameters->sampleFormat: %d\n", inputParameters->sampleFormat ));

+        PA_LOGAPI(("\tPaTime inputParameters->suggestedLatency: %f\n", inputParameters->suggestedLatency ));

+        PA_LOGAPI(("\tvoid *inputParameters->hostApiSpecificStreamInfo: 0x%p\n", inputParameters->hostApiSpecificStreamInfo ));

+    }

+

+    if( outputParameters == NULL ){

+        PA_LOGAPI(("\tPaStreamParameters *outputParameters: NULL\n" ));

+    }else{

+        PA_LOGAPI(("\tPaStreamParameters *outputParameters: 0x%p\n", outputParameters ));

+        PA_LOGAPI(("\tPaDeviceIndex outputParameters->device: %d\n", outputParameters->device ));

+        PA_LOGAPI(("\tint outputParameters->channelCount: %d\n", outputParameters->channelCount ));

+        PA_LOGAPI(("\tPaSampleFormat outputParameters->sampleFormat: %d\n", outputParameters->sampleFormat ));

+        PA_LOGAPI(("\tPaTime outputParameters->suggestedLatency: %f\n", outputParameters->suggestedLatency ));

+        PA_LOGAPI(("\tvoid *outputParameters->hostApiSpecificStreamInfo: 0x%p\n", outputParameters->hostApiSpecificStreamInfo ));

+    }

+    

+    PA_LOGAPI(("\tdouble sampleRate: %g\n", sampleRate ));

+    PA_LOGAPI(("\tunsigned long framesPerBuffer: %d\n", framesPerBuffer ));

+    PA_LOGAPI(("\tPaStreamFlags streamFlags: 0x%x\n", streamFlags ));

+    PA_LOGAPI(("\tPaStreamCallback *streamCallback: 0x%p\n", streamCallback ));

+    PA_LOGAPI(("\tvoid *userData: 0x%p\n", userData ));

+#endif

+

+    if( !PA_IS_INITIALISED_ )

+    {

+        result = paNotInitialized;

+

+        PA_LOGAPI(("Pa_OpenStream returned:\n" ));

+        PA_LOGAPI(("\t*(PaStream** stream): undefined\n" ));

+        PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));

+        return result;

+    }

+

+    /* Check for parameter errors.

+        NOTE: make sure this validation list is kept syncronised with the one

+        in pa_hostapi.h

+    */

+

+    if( stream == NULL )

+    {

+        result = paBadStreamPtr;

+

+        PA_LOGAPI(("Pa_OpenStream returned:\n" ));

+        PA_LOGAPI(("\t*(PaStream** stream): undefined\n" ));

+        PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));

+        return result;

+    }

+

+    result = ValidateOpenStreamParameters( inputParameters,

+                                           outputParameters,

+                                           sampleRate, framesPerBuffer,

+                                           streamFlags, streamCallback,

+                                           &hostApi,

+                                           &hostApiInputDevice,

+                                           &hostApiOutputDevice );

+    if( result != paNoError )

+    {

+        PA_LOGAPI(("Pa_OpenStream returned:\n" ));

+        PA_LOGAPI(("\t*(PaStream** stream): undefined\n" ));

+        PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));

+        return result;

+    }

+    

+

+    if( inputParameters )

+    {

+        hostApiInputParameters.device = hostApiInputDevice;

+        hostApiInputParameters.channelCount = inputParameters->channelCount;

+        hostApiInputParameters.sampleFormat = inputParameters->sampleFormat;

+        hostApiInputParameters.suggestedLatency = inputParameters->suggestedLatency;

+        hostApiInputParameters.hostApiSpecificStreamInfo = inputParameters->hostApiSpecificStreamInfo;

+        hostApiInputParametersPtr = &hostApiInputParameters;

+    }

+    else

+    {

+        hostApiInputParametersPtr = NULL;

+    }

+

+    if( outputParameters )

+    {

+        hostApiOutputParameters.device = hostApiOutputDevice;

+        hostApiOutputParameters.channelCount = outputParameters->channelCount;

+        hostApiOutputParameters.sampleFormat = outputParameters->sampleFormat;

+        hostApiOutputParameters.suggestedLatency = outputParameters->suggestedLatency;

+        hostApiOutputParameters.hostApiSpecificStreamInfo = outputParameters->hostApiSpecificStreamInfo;

+        hostApiOutputParametersPtr = &hostApiOutputParameters;

+    }

+    else

+    {

+        hostApiOutputParametersPtr = NULL;

+    }

+

+    result = hostApi->OpenStream( hostApi, stream,

+                                  hostApiInputParametersPtr, hostApiOutputParametersPtr,

+                                  sampleRate, framesPerBuffer, streamFlags, streamCallback, userData );

+

+    if( result == paNoError )

+        AddOpenStream( *stream );

+

+

+    PA_LOGAPI(("Pa_OpenStream returned:\n" ));

+    PA_LOGAPI(("\t*(PaStream** stream): 0x%p\n", *stream ));

+    PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));

+

+    return result;

+}

+

+

+PaError Pa_OpenDefaultStream( PaStream** stream,

+                              int inputChannelCount,

+                              int outputChannelCount,

+                              PaSampleFormat sampleFormat,

+                              double sampleRate,

+                              unsigned long framesPerBuffer,

+                              PaStreamCallback *streamCallback,

+                              void *userData )

+{

+    PaError result;

+    PaStreamParameters hostApiInputParameters, hostApiOutputParameters;

+    PaStreamParameters *hostApiInputParametersPtr, *hostApiOutputParametersPtr;

+

+    PA_LOGAPI_ENTER_PARAMS( "Pa_OpenDefaultStream" );

+    PA_LOGAPI(("\tPaStream** stream: 0x%p\n", stream ));

+    PA_LOGAPI(("\tint inputChannelCount: %d\n", inputChannelCount ));

+    PA_LOGAPI(("\tint outputChannelCount: %d\n", outputChannelCount ));

+    PA_LOGAPI(("\tPaSampleFormat sampleFormat: %d\n", sampleFormat ));

+    PA_LOGAPI(("\tdouble sampleRate: %g\n", sampleRate ));

+    PA_LOGAPI(("\tunsigned long framesPerBuffer: %d\n", framesPerBuffer ));

+    PA_LOGAPI(("\tPaStreamCallback *streamCallback: 0x%p\n", streamCallback ));

+    PA_LOGAPI(("\tvoid *userData: 0x%p\n", userData ));

+

+

+    if( inputChannelCount > 0 )

+    {

+        hostApiInputParameters.device = Pa_GetDefaultInputDevice();

+		if( hostApiInputParameters.device == paNoDevice )

+			return paDeviceUnavailable; 

+	

+        hostApiInputParameters.channelCount = inputChannelCount;

+        hostApiInputParameters.sampleFormat = sampleFormat;

+        /* defaultHighInputLatency is used below instead of

+           defaultLowInputLatency because it is more important for the default

+           stream to work reliably than it is for it to work with the lowest

+           latency.

+         */

+        hostApiInputParameters.suggestedLatency = 

+             Pa_GetDeviceInfo( hostApiInputParameters.device )->defaultHighInputLatency;

+        hostApiInputParameters.hostApiSpecificStreamInfo = NULL;

+        hostApiInputParametersPtr = &hostApiInputParameters;

+    }

+    else

+    {

+        hostApiInputParametersPtr = NULL;

+    }

+

+    if( outputChannelCount > 0 )

+    {

+        hostApiOutputParameters.device = Pa_GetDefaultOutputDevice();

+		if( hostApiOutputParameters.device == paNoDevice )

+			return paDeviceUnavailable; 

+

+        hostApiOutputParameters.channelCount = outputChannelCount;

+        hostApiOutputParameters.sampleFormat = sampleFormat;

+        /* defaultHighOutputLatency is used below instead of

+           defaultLowOutputLatency because it is more important for the default

+           stream to work reliably than it is for it to work with the lowest

+           latency.

+         */

+        hostApiOutputParameters.suggestedLatency =

+             Pa_GetDeviceInfo( hostApiOutputParameters.device )->defaultHighOutputLatency;

+        hostApiOutputParameters.hostApiSpecificStreamInfo = NULL;

+        hostApiOutputParametersPtr = &hostApiOutputParameters;

+    }

+    else

+    {

+        hostApiOutputParametersPtr = NULL;

+    }

+

+

+    result = Pa_OpenStream(

+                 stream, hostApiInputParametersPtr, hostApiOutputParametersPtr,

+                 sampleRate, framesPerBuffer, paNoFlag, streamCallback, userData );

+

+    PA_LOGAPI(("Pa_OpenDefaultStream returned:\n" ));

+    PA_LOGAPI(("\t*(PaStream** stream): 0x%p", *stream ));

+    PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));

+

+    return result;

+}

+

+

+PaError PaUtil_ValidateStreamPointer( PaStream* stream )

+{

+    if( !PA_IS_INITIALISED_ ) return paNotInitialized;

+

+    if( stream == NULL ) return paBadStreamPtr;

+

+    if( ((PaUtilStreamRepresentation*)stream)->magic != PA_STREAM_MAGIC )

+        return paBadStreamPtr;

+

+    return paNoError;

+}

+

+

+PaError Pa_CloseStream( PaStream* stream )

+{

+    PaUtilStreamInterface *interface;

+    PaError result = PaUtil_ValidateStreamPointer( stream );

+

+    PA_LOGAPI_ENTER_PARAMS( "Pa_CloseStream" );

+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));

+

+    /* always remove the open stream from our list, even if this function

+        eventually returns an error. Otherwise CloseOpenStreams() will

+        get stuck in an infinite loop */

+    RemoveOpenStream( stream ); /* be sure to call this _before_ closing the stream */

+

+    if( result == paNoError )

+    {

+        interface = PA_STREAM_INTERFACE(stream);

+

+        /* abort the stream if it isn't stopped */

+        result = interface->IsStopped( stream );

+        if( result == 1 )

+            result = paNoError;

+        else if( result == 0 )

+            result = interface->Abort( stream );

+

+        if( result == paNoError )                 /** @todo REVIEW: shouldn't we close anyway? */

+            result = interface->Close( stream );

+    }

+

+    PA_LOGAPI_EXIT_PAERROR( "Pa_CloseStream", result );

+

+    return result;

+}

+

+

+PaError Pa_SetStreamFinishedCallback( PaStream *stream, PaStreamFinishedCallback* streamFinishedCallback )

+{

+    PaError result = PaUtil_ValidateStreamPointer( stream );

+

+    PA_LOGAPI_ENTER_PARAMS( "Pa_SetStreamFinishedCallback" );

+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));

+    PA_LOGAPI(("\tPaStreamFinishedCallback* streamFinishedCallback: 0x%p\n", streamFinishedCallback ));

+

+    if( result == paNoError )

+    {

+        result = PA_STREAM_INTERFACE(stream)->IsStopped( stream );

+        if( result == 0 )

+        {

+            result = paStreamIsNotStopped ;

+        }

+        if( result == 1 )

+        {

+            PA_STREAM_REP( stream )->streamFinishedCallback = streamFinishedCallback;

+            result = paNoError;

+        }

+    }

+

+    PA_LOGAPI_EXIT_PAERROR( "Pa_SetStreamFinishedCallback", result );

+

+    return result;

+

+}

+

+

+PaError Pa_StartStream( PaStream *stream )

+{

+    PaError result = PaUtil_ValidateStreamPointer( stream );

+

+    PA_LOGAPI_ENTER_PARAMS( "Pa_StartStream" );

+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));

+

+    if( result == paNoError )

+    {

+        result = PA_STREAM_INTERFACE(stream)->IsStopped( stream );

+        if( result == 0 )

+        {

+            result = paStreamIsNotStopped ;

+        }

+        else if( result == 1 )

+        {

+            result = PA_STREAM_INTERFACE(stream)->Start( stream );

+        }

+    }

+

+    PA_LOGAPI_EXIT_PAERROR( "Pa_StartStream", result );

+

+    return result;

+}

+

+

+PaError Pa_StopStream( PaStream *stream )

+{

+    PaError result = PaUtil_ValidateStreamPointer( stream );

+

+    PA_LOGAPI_ENTER_PARAMS( "Pa_StopStream" );

+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));

+

+    if( result == paNoError )

+    {

+        result = PA_STREAM_INTERFACE(stream)->IsStopped( stream );

+        if( result == 0 )

+        {

+            result = PA_STREAM_INTERFACE(stream)->Stop( stream );

+        }

+        else if( result == 1 )

+        {

+            result = paStreamIsStopped;

+        }

+    }

+

+    PA_LOGAPI_EXIT_PAERROR( "Pa_StopStream", result );

+

+    return result;

+}

+

+

+PaError Pa_AbortStream( PaStream *stream )

+{

+    PaError result = PaUtil_ValidateStreamPointer( stream );

+

+    PA_LOGAPI_ENTER_PARAMS( "Pa_AbortStream" );

+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));

+

+    if( result == paNoError )

+    {

+        result = PA_STREAM_INTERFACE(stream)->IsStopped( stream );

+        if( result == 0 )

+        {

+            result = PA_STREAM_INTERFACE(stream)->Abort( stream );

+        }

+        else if( result == 1 )

+        {

+            result = paStreamIsStopped;

+        }

+    }

+

+    PA_LOGAPI_EXIT_PAERROR( "Pa_AbortStream", result );

+

+    return result;

+}

+

+

+PaError Pa_IsStreamStopped( PaStream *stream )

+{

+    PaError result = PaUtil_ValidateStreamPointer( stream );

+

+    PA_LOGAPI_ENTER_PARAMS( "Pa_IsStreamStopped" );

+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));

+

+    if( result == paNoError )

+        result = PA_STREAM_INTERFACE(stream)->IsStopped( stream );

+

+    PA_LOGAPI_EXIT_PAERROR( "Pa_IsStreamStopped", result );

+

+    return result;

+}

+

+

+PaError Pa_IsStreamActive( PaStream *stream )

+{

+    PaError result = PaUtil_ValidateStreamPointer( stream );

+

+    PA_LOGAPI_ENTER_PARAMS( "Pa_IsStreamActive" );

+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));

+

+    if( result == paNoError )

+        result = PA_STREAM_INTERFACE(stream)->IsActive( stream );

+

+

+    PA_LOGAPI_EXIT_PAERROR( "Pa_IsStreamActive", result );

+

+    return result;

+}

+

+

+const PaStreamInfo* Pa_GetStreamInfo( PaStream *stream )

+{

+    PaError error = PaUtil_ValidateStreamPointer( stream );

+    const PaStreamInfo *result;

+

+    PA_LOGAPI_ENTER_PARAMS( "Pa_GetStreamInfo" );

+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));

+

+    if( error != paNoError )

+    {

+        result = 0;

+

+        PA_LOGAPI(("Pa_GetStreamInfo returned:\n" ));

+        PA_LOGAPI(("\tconst PaStreamInfo*: 0 [PaError error:%d ( %s )]\n", result, error, Pa_GetErrorText( error ) ));

+

+    }

+    else

+    {

+        result = &PA_STREAM_REP( stream )->streamInfo;

+

+        PA_LOGAPI(("Pa_GetStreamInfo returned:\n" ));

+        PA_LOGAPI(("\tconst PaStreamInfo*: 0x%p:\n", result ));

+        PA_LOGAPI(("\t{" ));

+

+        PA_LOGAPI(("\t\tint structVersion: %d\n", result->structVersion ));

+        PA_LOGAPI(("\t\tPaTime inputLatency: %f\n", result->inputLatency ));

+        PA_LOGAPI(("\t\tPaTime outputLatency: %f\n", result->outputLatency ));

+        PA_LOGAPI(("\t\tdouble sampleRate: %f\n", result->sampleRate ));

+        PA_LOGAPI(("\t}\n" ));

+

+    }

+

+    return result;

+}

+

+

+PaTime Pa_GetStreamTime( PaStream *stream )

+{

+    PaError error = PaUtil_ValidateStreamPointer( stream );

+    PaTime result;

+

+    PA_LOGAPI_ENTER_PARAMS( "Pa_GetStreamTime" );

+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));

+

+    if( error != paNoError )

+    {

+        result = 0;

+

+        PA_LOGAPI(("Pa_GetStreamTime returned:\n" ));

+        PA_LOGAPI(("\tPaTime: 0 [PaError error:%d ( %s )]\n", result, error, Pa_GetErrorText( error ) ));

+

+    }

+    else

+    {

+        result = PA_STREAM_INTERFACE(stream)->GetTime( stream );

+

+        PA_LOGAPI(("Pa_GetStreamTime returned:\n" ));

+        PA_LOGAPI(("\tPaTime: %g\n", result ));

+

+    }

+

+    return result;

+}

+

+

+double Pa_GetStreamCpuLoad( PaStream* stream )

+{

+    PaError error = PaUtil_ValidateStreamPointer( stream );

+    double result;

+

+    PA_LOGAPI_ENTER_PARAMS( "Pa_GetStreamCpuLoad" );

+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));

+

+    if( error != paNoError )

+    {

+

+        result = 0.0;

+

+        PA_LOGAPI(("Pa_GetStreamCpuLoad returned:\n" ));

+        PA_LOGAPI(("\tdouble: 0.0 [PaError error: %d ( %s )]\n", error, Pa_GetErrorText( error ) ));

+

+    }

+    else

+    {

+        result = PA_STREAM_INTERFACE(stream)->GetCpuLoad( stream );

+

+        PA_LOGAPI(("Pa_GetStreamCpuLoad returned:\n" ));

+        PA_LOGAPI(("\tdouble: %g\n", result ));

+

+    }

+

+    return result;

+}

+

+

+PaError Pa_ReadStream( PaStream* stream,

+                       void *buffer,

+                       unsigned long frames )

+{

+    PaError result = PaUtil_ValidateStreamPointer( stream );

+

+    PA_LOGAPI_ENTER_PARAMS( "Pa_ReadStream" );

+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));

+

+    if( result == paNoError )

+    {

+        if( frames == 0 )

+        {

+            /* XXX: Should we not allow the implementation to signal any overflow condition? */

+            result = paNoError;

+        }

+        else if( buffer == 0 )

+        {

+            result = paBadBufferPtr;

+        }

+        else

+        {

+            result = PA_STREAM_INTERFACE(stream)->IsStopped( stream );

+            if( result == 0 )

+            {

+                result = PA_STREAM_INTERFACE(stream)->Read( stream, buffer, frames );

+            }

+            else if( result == 1 )

+            {

+                result = paStreamIsStopped;

+            }

+        }

+    }

+

+    PA_LOGAPI_EXIT_PAERROR( "Pa_ReadStream", result );

+

+    return result;

+}

+

+

+PaError Pa_WriteStream( PaStream* stream,

+                        const void *buffer,

+                        unsigned long frames )

+{

+    PaError result = PaUtil_ValidateStreamPointer( stream );

+

+    PA_LOGAPI_ENTER_PARAMS( "Pa_WriteStream" );

+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));

+

+    if( result == paNoError )

+    {

+        if( frames == 0 )

+        {

+            /* XXX: Should we not allow the implementation to signal any underflow condition? */

+            result = paNoError;

+        }

+        else if( buffer == 0 )

+        {

+            result = paBadBufferPtr;

+        }

+        else

+        {

+            result = PA_STREAM_INTERFACE(stream)->IsStopped( stream );

+            if( result == 0 )

+            {

+                result = PA_STREAM_INTERFACE(stream)->Write( stream, buffer, frames );

+            }

+            else if( result == 1 )

+            {

+                result = paStreamIsStopped;

+            }  

+        }

+    }

+

+    PA_LOGAPI_EXIT_PAERROR( "Pa_WriteStream", result );

+

+    return result;

+}

+

+signed long Pa_GetStreamReadAvailable( PaStream* stream )

+{

+    PaError error = PaUtil_ValidateStreamPointer( stream );

+    signed long result;

+

+    PA_LOGAPI_ENTER_PARAMS( "Pa_GetStreamReadAvailable" );

+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));

+

+    if( error != paNoError )

+    {

+        result = 0;

+

+        PA_LOGAPI(("Pa_GetStreamReadAvailable returned:\n" ));

+        PA_LOGAPI(("\tunsigned long: 0 [ PaError error: %d ( %s ) ]\n", error, Pa_GetErrorText( error ) ));

+

+    }

+    else

+    {

+        result = PA_STREAM_INTERFACE(stream)->GetReadAvailable( stream );

+

+        PA_LOGAPI(("Pa_GetStreamReadAvailable returned:\n" ));

+        PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));

+

+    }

+

+    return result;

+}

+

+

+signed long Pa_GetStreamWriteAvailable( PaStream* stream )

+{

+    PaError error = PaUtil_ValidateStreamPointer( stream );

+    signed long result;

+

+    PA_LOGAPI_ENTER_PARAMS( "Pa_GetStreamWriteAvailable" );

+    PA_LOGAPI(("\tPaStream* stream: 0x%p\n", stream ));

+

+    if( error != paNoError )

+    {

+        result = 0;

+

+        PA_LOGAPI(("Pa_GetStreamWriteAvailable returned:\n" ));

+        PA_LOGAPI(("\tunsigned long: 0 [ PaError error: %d ( %s ) ]\n", error, Pa_GetErrorText( error ) ));

+

+    }

+    else

+    {

+        result = PA_STREAM_INTERFACE(stream)->GetWriteAvailable( stream );

+

+        PA_LOGAPI(("Pa_GetStreamWriteAvailable returned:\n" ));

+        PA_LOGAPI(("\tPaError: %d ( %s )\n", result, Pa_GetErrorText( result ) ));

+

+    }

+

+    return result;

+}

+

+

+PaError Pa_GetSampleSize( PaSampleFormat format )

+{

+    int result;

+

+    PA_LOGAPI_ENTER_PARAMS( "Pa_GetSampleSize" );

+    PA_LOGAPI(("\tPaSampleFormat format: %d\n", format ));

+

+    switch( format & ~paNonInterleaved )

+    {

+

+    case paUInt8:

+    case paInt8:

+        result = 1;

+        break;

+

+    case paInt16:

+        result = 2;

+        break;

+

+    case paInt24:

+        result = 3;

+        break;

+

+    case paFloat32:

+    case paInt32:

+        result = 4;

+        break;

+

+    default:

+        result = paSampleFormatNotSupported;

+        break;

+    }

+

+    PA_LOGAPI_EXIT_PAERROR_OR_T_RESULT( "Pa_GetSampleSize", "int: %d", result );

+

+    return (PaError) result;

+}

+

diff --git a/src/engine/external/portaudio/pa_hostapi.h b/src/engine/external/portaudio/pa_hostapi.h
new file mode 100644
index 00000000..b8fbe1e1
--- /dev/null
+++ b/src/engine/external/portaudio/pa_hostapi.h
@@ -0,0 +1,253 @@
+#ifndef PA_HOSTAPI_H

+#define PA_HOSTAPI_H

+/*

+ * $Id: pa_hostapi.h 1097 2006-08-26 08:27:53Z rossb $

+ * Portable Audio I/O Library

+ * host api representation

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup common_src

+

+ @brief Interface used by pa_front to virtualize functions which operate on

+ host APIs.

+*/

+

+

+#include "portaudio.h"

+

+#ifdef __cplusplus

+extern "C"

+{

+#endif /* __cplusplus */

+

+

+/** **FOR THE USE OF pa_front.c ONLY**

+    Do NOT use fields in this structure, they my change at any time.

+    Use functions defined in pa_util.h if you think you need functionality

+    which can be derived from here.

+*/

+typedef struct PaUtilPrivatePaFrontHostApiInfo {

+

+

+    unsigned long baseDeviceIndex;

+}PaUtilPrivatePaFrontHostApiInfo;

+

+

+/** The common header for all data structures whose pointers are passed through

+ the hostApiSpecificStreamInfo field of the PaStreamParameters structure.

+ Note that in order to keep the public PortAudio interface clean, this structure

+ is not used explicitly when declaring hostApiSpecificStreamInfo data structures.

+ However, some code in pa_front depends on the first 3 members being equivalent

+ with this structure.

+ @see PaStreamParameters

+*/

+typedef struct PaUtilHostApiSpecificStreamInfoHeader

+{

+    unsigned long size;             /**< size of whole structure including this header */

+    PaHostApiTypeId hostApiType;    /**< host API for which this data is intended */

+    unsigned long version;          /**< structure version */

+} PaUtilHostApiSpecificStreamInfoHeader;

+

+

+

+/** A structure representing the interface to a host API. Contains both

+ concrete data and pointers to functions which implement the interface.

+*/

+typedef struct PaUtilHostApiRepresentation {

+    PaUtilPrivatePaFrontHostApiInfo privatePaFrontInfo;

+

+    /** The host api implementation should populate the info field. In the

+        case of info.defaultInputDevice and info.defaultOutputDevice the

+        values stored should be 0 based indices within the host api's own

+        device index range (0 to deviceCount). These values will be converted

+        to global device indices by pa_front after PaUtilHostApiInitializer()

+        returns.

+    */

+    PaHostApiInfo info;

+

+    PaDeviceInfo** deviceInfos;

+

+    /**

+        (*Terminate)() is guaranteed to be called with a valid <hostApi>

+        parameter, which was previously returned from the same implementation's

+        initializer.

+    */

+    void (*Terminate)( struct PaUtilHostApiRepresentation *hostApi );

+

+    /**

+        The inputParameters and outputParameters pointers should not be saved

+        as they will not remain valid after OpenStream is called.

+

+        

+        The following guarantees are made about parameters to (*OpenStream)():

+

+            [NOTE: the following list up to *END PA FRONT VALIDATIONS* should be

+                kept in sync with the one for ValidateOpenStreamParameters and

+                Pa_OpenStream in pa_front.c]

+                

+            PaHostApiRepresentation *hostApi

+                - is valid for this implementation

+

+            PaStream** stream

+                - is non-null

+

+            - at least one of inputParameters & outputParmeters is valid (not NULL)

+

+            - if inputParameters & outputParmeters are both valid, that

+                inputParameters->device & outputParmeters->device  both use the same host api

+ 

+            PaDeviceIndex inputParameters->device

+                - is within range (0 to Pa_CountDevices-1) Or:

+                - is paUseHostApiSpecificDeviceSpecification and

+                    inputParameters->hostApiSpecificStreamInfo is non-NULL and refers

+                    to a valid host api

+

+            int inputParameters->numChannels

+                - if inputParameters->device is not paUseHostApiSpecificDeviceSpecification, numInputChannels is > 0

+                - upper bound is NOT validated against device capabilities

+ 

+            PaSampleFormat inputParameters->sampleFormat

+                - is one of the sample formats defined in portaudio.h

+

+            void *inputParameters->hostApiSpecificStreamInfo

+                - if supplied its hostApi field matches the input device's host Api

+ 

+            PaDeviceIndex outputParmeters->device

+                - is within range (0 to Pa_CountDevices-1)

+ 

+            int outputParmeters->numChannels

+                - if inputDevice is valid, numInputChannels is > 0

+                - upper bound is NOT validated against device capabilities

+ 

+            PaSampleFormat outputParmeters->sampleFormat

+                - is one of the sample formats defined in portaudio.h

+        

+            void *outputParmeters->hostApiSpecificStreamInfo

+                - if supplied its hostApi field matches the output device's host Api

+ 

+            double sampleRate

+                - is not an 'absurd' rate (less than 1000. or greater than 200000.)

+                - sampleRate is NOT validated against device capabilities

+ 

+            PaStreamFlags streamFlags

+                - unused platform neutral flags are zero

+                - paNeverDropInput is only used for full-duplex callback streams

+                    with variable buffer size (paFramesPerBufferUnspecified)

+

+            [*END PA FRONT VALIDATIONS*]

+

+

+        The following validations MUST be performed by (*OpenStream)():

+

+            - check that input device can support numInputChannels

+            

+            - check that input device can support inputSampleFormat, or that

+                we have the capability to convert from outputSampleFormat to

+                a native format

+

+            - if inputStreamInfo is supplied, validate its contents,

+                or return an error if no inputStreamInfo is expected

+

+            - check that output device can support numOutputChannels

+            

+            - check that output device can support outputSampleFormat, or that

+                we have the capability to convert from outputSampleFormat to

+                a native format

+

+            - if outputStreamInfo is supplied, validate its contents,

+                or return an error if no outputStreamInfo is expected

+

+            - if a full duplex stream is requested, check that the combination

+                of input and output parameters is supported

+

+            - check that the device supports sampleRate

+

+            - alter sampleRate to a close allowable rate if necessary

+

+            - validate inputLatency and outputLatency

+

+            - validate any platform specific flags, if flags are supplied they

+                must be valid.

+    */

+    PaError (*OpenStream)( struct PaUtilHostApiRepresentation *hostApi,

+                           PaStream** stream,

+                           const PaStreamParameters *inputParameters,

+                           const PaStreamParameters *outputParameters,

+                           double sampleRate,

+                           unsigned long framesPerCallback,

+                           PaStreamFlags streamFlags,

+                           PaStreamCallback *streamCallback,

+                           void *userData );

+

+

+    PaError (*IsFormatSupported)( struct PaUtilHostApiRepresentation *hostApi,

+                                  const PaStreamParameters *inputParameters,

+                                  const PaStreamParameters *outputParameters,

+                                  double sampleRate );

+} PaUtilHostApiRepresentation;

+

+

+/** Prototype for the initialization function which must be implemented by every

+ host API.

+ 

+ @see paHostApiInitializers

+*/

+typedef PaError PaUtilHostApiInitializer( PaUtilHostApiRepresentation**, PaHostApiIndex );

+

+

+/** paHostApiInitializers is a NULL-terminated array of host API initialization

+ functions. These functions are called by pa_front to initialize the host APIs

+ when the client calls Pa_Initialize().

+

+ There is a platform specific file which defines paHostApiInitializers for that

+ platform, pa_win/pa_win_hostapis.c contains the Win32 definitions for example.

+*/

+extern PaUtilHostApiInitializer *paHostApiInitializers[];

+

+

+/** The index of the default host API in the paHostApiInitializers array.

+ 

+ There is a platform specific file which defines paDefaultHostApiIndex for that

+ platform, see pa_win/pa_win_hostapis.c for example.

+*/

+extern int paDefaultHostApiIndex;

+

+

+#ifdef __cplusplus

+}

+#endif /* __cplusplus */

+#endif /* PA_HOSTAPI_H */

diff --git a/src/engine/external/portaudio/pa_linux_alsa.c b/src/engine/external/portaudio/pa_linux_alsa.c
new file mode 100644
index 00000000..a1070637
--- /dev/null
+++ b/src/engine/external/portaudio/pa_linux_alsa.c
@@ -0,0 +1,3323 @@
+/*
+ * $Id: pa_linux_alsa.c 1105 2006-08-31 05:52:57Z aknudsen $
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ * ALSA implementation by Joshua Haberman and Arve Knudsen
+ *
+ * Copyright (c) 2002 Joshua Haberman <joshua@haberman.com>
+ * Copyright (c) 2005-2006 Arve Knudsen <aknuds-1@broadpark.no>
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/**
+ @file
+ @ingroup hostapi_src
+*/
+
+#define ALSA_PCM_NEW_HW_PARAMS_API
+#define ALSA_PCM_NEW_SW_PARAMS_API
+#include <alsa/asoundlib.h>
+#undef ALSA_PCM_NEW_HW_PARAMS_API
+#undef ALSA_PCM_NEW_SW_PARAMS_API
+
+#include <sys/poll.h>
+#include <string.h> /* strlen() */
+#include <limits.h>
+#include <math.h>
+#include <pthread.h>
+#include <signal.h>
+#include <time.h>
+#include <sys/mman.h>
+#include <signal.h> /* For sig_atomic_t */
+
+#include "portaudio.h"
+#include "pa_util.h"
+#include "pa_unix_util.h"
+#include "pa_allocation.h"
+#include "pa_hostapi.h"
+#include "pa_stream.h"
+#include "pa_cpuload.h"
+#include "pa_process.h"
+
+#include "pa_linux_alsa.h"
+
+/* Check return value of ALSA function, and map it to PaError */
+#define ENSURE_(expr, code) \
+    do { \
+        if( UNLIKELY( (aErr_ = (expr)) < 0 ) ) \
+        { \
+            /* PaUtil_SetLastHostErrorInfo should only be used in the main thread */ \
+            if( (code) == paUnanticipatedHostError && pthread_equal( pthread_self(), paUnixMainThread) ) \
+            { \
+                PaUtil_SetLastHostErrorInfo( paALSA, aErr_, snd_strerror( aErr_ ) ); \
+            } \
+            PaUtil_DebugPrint( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" ); \
+            if( (code) == paUnanticipatedHostError ) \
+                PA_DEBUG(( "Host error description: %s\n", snd_strerror( aErr_ ) )); \
+            result = (code); \
+            goto error; \
+        } \
+    } while( 0 );
+
+#define ASSERT_CALL_(expr, success) \
+    aErr_ = (expr); \
+    assert( success == aErr_ );
+
+static int aErr_;               /* Used with ENSURE_ */
+
+typedef enum
+{
+    StreamDirection_In,
+    StreamDirection_Out
+} StreamDirection;
+
+typedef struct
+{
+    PaSampleFormat hostSampleFormat;
+    unsigned long framesPerBuffer;
+    int numUserChannels, numHostChannels;
+    int userInterleaved, hostInterleaved;
+
+    snd_pcm_t *pcm;
+    snd_pcm_uframes_t bufferSize;
+    snd_pcm_format_t nativeFormat;
+    unsigned int nfds;
+    int ready;  /* Marked ready from poll */
+    void **userBuffers;
+    snd_pcm_uframes_t offset;
+    StreamDirection streamDir;
+
+    snd_pcm_channel_area_t *channelAreas;  /* Needed for channel adaption */
+} PaAlsaStreamComponent;
+
+/* Implementation specific stream structure */
+typedef struct PaAlsaStream
+{
+    PaUtilStreamRepresentation streamRepresentation;
+    PaUtilCpuLoadMeasurer cpuLoadMeasurer;
+    PaUtilBufferProcessor bufferProcessor;
+    PaUnixThread thread;
+
+    unsigned long framesPerUserBuffer, maxFramesPerHostBuffer;
+
+    int primeBuffers;
+    int callbackMode;              /* bool: are we running in callback mode? */
+    int pcmsSynced;	            /* Have we successfully synced pcms */
+
+    /* the callback thread uses these to poll the sound device(s), waiting
+     * for data to be ready/available */
+    struct pollfd* pfds;
+    int pollTimeout;
+
+    /* Used in communication between threads */
+    volatile sig_atomic_t callback_finished; /* bool: are we in the "callback finished" state? */
+    volatile sig_atomic_t callbackAbort;    /* Drop frames? */
+    volatile sig_atomic_t isActive;         /* Is stream in active state? (Between StartStream and StopStream || !paContinue) */
+    PaUnixMutex stateMtx;                   /* Used to synchronize access to stream state */
+
+    int neverDropInput;
+
+    PaTime underrun;
+    PaTime overrun;
+
+    PaAlsaStreamComponent capture, playback;
+}
+PaAlsaStream;
+
+/* PaAlsaHostApiRepresentation - host api datastructure specific to this implementation */
+
+typedef struct PaAlsaHostApiRepresentation
+{
+    PaUtilHostApiRepresentation baseHostApiRep;
+    PaUtilStreamInterface callbackStreamInterface;
+    PaUtilStreamInterface blockingStreamInterface;
+
+    PaUtilAllocationGroup *allocations;
+
+    PaHostApiIndex hostApiIndex;
+}
+PaAlsaHostApiRepresentation;
+
+typedef struct PaAlsaDeviceInfo
+{
+    PaDeviceInfo baseDeviceInfo;
+    char *alsaName;
+    int isPlug;
+    int minInputChannels;
+    int minOutputChannels;
+}
+PaAlsaDeviceInfo;
+
+/* prototypes for functions declared in this file */
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate );
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback *callback,
+                           void *userData );
+static PaError CloseStream( PaStream* stream );
+static PaError StartStream( PaStream *stream );
+static PaError StopStream( PaStream *stream );
+static PaError AbortStream( PaStream *stream );
+static PaError IsStreamStopped( PaStream *s );
+static PaError IsStreamActive( PaStream *stream );
+static PaTime GetStreamTime( PaStream *stream );
+static double GetStreamCpuLoad( PaStream* stream );
+static PaError BuildDeviceList( PaAlsaHostApiRepresentation *hostApi );
+static int SetApproximateSampleRate( snd_pcm_t *pcm, snd_pcm_hw_params_t *hwParams, double sampleRate );
+static int GetExactSampleRate( snd_pcm_hw_params_t *hwParams, double *sampleRate );
+
+/* Callback prototypes */
+static void *CallbackThreadFunc( void *userData );
+
+/* Blocking prototypes */
+static signed long GetStreamReadAvailable( PaStream* s );
+static signed long GetStreamWriteAvailable( PaStream* s );
+static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
+static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
+
+
+static const PaAlsaDeviceInfo *GetDeviceInfo( const PaUtilHostApiRepresentation *hostApi, int device )
+{
+    return (const PaAlsaDeviceInfo *)hostApi->deviceInfos[device];
+}
+
+static void AlsaErrorHandler(const char *file, int line, const char *function, int err, const char *fmt, ...)
+{
+}
+
+PaError PaAlsa_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
+{
+    PaError result = paNoError;
+    PaAlsaHostApiRepresentation *alsaHostApi = NULL;
+
+    PA_UNLESS( alsaHostApi = (PaAlsaHostApiRepresentation*) PaUtil_AllocateMemory(
+                sizeof(PaAlsaHostApiRepresentation) ), paInsufficientMemory );
+    PA_UNLESS( alsaHostApi->allocations = PaUtil_CreateAllocationGroup(), paInsufficientMemory );
+    alsaHostApi->hostApiIndex = hostApiIndex;
+
+    *hostApi = (PaUtilHostApiRepresentation*)alsaHostApi;
+    (*hostApi)->info.structVersion = 1;
+    (*hostApi)->info.type = paALSA;
+    (*hostApi)->info.name = "ALSA";
+
+    (*hostApi)->Terminate = Terminate;
+    (*hostApi)->OpenStream = OpenStream;
+    (*hostApi)->IsFormatSupported = IsFormatSupported;
+
+    ENSURE_( snd_lib_error_set_handler(AlsaErrorHandler), paUnanticipatedHostError );
+
+    PA_ENSURE( BuildDeviceList( alsaHostApi ) );
+
+    PaUtil_InitializeStreamInterface( &alsaHostApi->callbackStreamInterface,
+                                      CloseStream, StartStream,
+                                      StopStream, AbortStream,
+                                      IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, GetStreamCpuLoad,
+                                      PaUtil_DummyRead, PaUtil_DummyWrite,
+                                      PaUtil_DummyGetReadAvailable,
+                                      PaUtil_DummyGetWriteAvailable );
+
+    PaUtil_InitializeStreamInterface( &alsaHostApi->blockingStreamInterface,
+                                      CloseStream, StartStream,
+                                      StopStream, AbortStream,
+                                      IsStreamStopped, IsStreamActive,
+                                      GetStreamTime, PaUtil_DummyGetCpuLoad,
+                                      ReadStream, WriteStream,
+                                      GetStreamReadAvailable,
+                                      GetStreamWriteAvailable );
+
+    PA_ENSURE( PaUnixThreading_Initialize() );
+
+    return result;
+
+error:
+    if( alsaHostApi )
+    {
+        if( alsaHostApi->allocations )
+        {
+            PaUtil_FreeAllAllocations( alsaHostApi->allocations );
+            PaUtil_DestroyAllocationGroup( alsaHostApi->allocations );
+        }
+
+        PaUtil_FreeMemory( alsaHostApi );
+    }
+
+    return result;
+}
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
+{
+    PaAlsaHostApiRepresentation *alsaHostApi = (PaAlsaHostApiRepresentation*)hostApi;
+
+    assert( hostApi );
+
+    if( alsaHostApi->allocations )
+    {
+        PaUtil_FreeAllAllocations( alsaHostApi->allocations );
+        PaUtil_DestroyAllocationGroup( alsaHostApi->allocations );
+    }
+
+    PaUtil_FreeMemory( alsaHostApi );
+    snd_config_update_free_global();
+}
+
+/** Determine max channels and default latencies.
+ *
+ * This function provides functionality to grope an opened (might be opened for capture or playback) pcm device for 
+ * traits like max channels, suitable default latencies and default sample rate. Upon error, max channels is set to zero,
+ * and a suitable result returned. The device is closed before returning.
+ */
+static PaError GropeDevice( snd_pcm_t* pcm, int isPlug, StreamDirection mode, int openBlocking,
+        PaAlsaDeviceInfo* devInfo, int* canMmap )
+{
+    PaError result = paNoError;
+    snd_pcm_hw_params_t *hwParams;
+    snd_pcm_uframes_t lowLatency = 512, highLatency = 2048;
+    unsigned int minChans, maxChans;
+    int* minChannels, * maxChannels;
+    double * defaultLowLatency, * defaultHighLatency, * defaultSampleRate =
+        &devInfo->baseDeviceInfo.defaultSampleRate;
+    double defaultSr = *defaultSampleRate;
+
+    assert( pcm );
+
+    if( StreamDirection_In == mode )
+    {
+        minChannels = &devInfo->minInputChannels;
+        maxChannels = &devInfo->baseDeviceInfo.maxInputChannels;
+        defaultLowLatency = &devInfo->baseDeviceInfo.defaultLowInputLatency;
+        defaultHighLatency = &devInfo->baseDeviceInfo.defaultHighInputLatency;
+    }
+    else
+    {
+        minChannels = &devInfo->minOutputChannels;
+        maxChannels = &devInfo->baseDeviceInfo.maxOutputChannels;
+        defaultLowLatency = &devInfo->baseDeviceInfo.defaultLowOutputLatency;
+        defaultHighLatency = &devInfo->baseDeviceInfo.defaultHighOutputLatency;
+    }
+
+    ENSURE_( snd_pcm_nonblock( pcm, 0 ), paUnanticipatedHostError );
+
+    snd_pcm_hw_params_alloca( &hwParams );
+    snd_pcm_hw_params_any( pcm, hwParams );
+
+    *canMmap = snd_pcm_hw_params_test_access( pcm, hwParams, SND_PCM_ACCESS_MMAP_INTERLEAVED ) >= 0 ||
+            snd_pcm_hw_params_test_access( pcm, hwParams, SND_PCM_ACCESS_MMAP_NONINTERLEAVED ) >= 0;
+
+    if( defaultSr >= 0 )
+    {
+        /* Could be that the device opened in one mode supports samplerates that the other mode wont have,
+         * so try again .. */
+        if( SetApproximateSampleRate( pcm, hwParams, defaultSr ) < 0 )
+        {
+            defaultSr = -1.;
+            PA_DEBUG(( "%s: Original default samplerate failed, trying again ..\n", __FUNCTION__ ));
+        }
+    }
+
+    if( defaultSr < 0. )           /* Default sample rate not set */
+    {
+        unsigned int sampleRate = 44100;        /* Will contain approximate rate returned by alsa-lib */
+        if( snd_pcm_hw_params_set_rate_near( pcm, hwParams, &sampleRate, NULL ) < 0)
+        {
+            result = paUnanticipatedHostError;
+            goto error;
+        }
+        ENSURE_( GetExactSampleRate( hwParams, &defaultSr ), paUnanticipatedHostError );
+    }
+    
+    ENSURE_( snd_pcm_hw_params_get_channels_min( hwParams, &minChans ), paUnanticipatedHostError );
+    ENSURE_( snd_pcm_hw_params_get_channels_max( hwParams, &maxChans ), paUnanticipatedHostError );
+    assert( maxChans <= INT_MAX );
+    assert( maxChans > 0 );    /* Weird linking issue could cause wrong version of ALSA symbols to be called,
+                                   resulting in zeroed values */
+
+    /* XXX: Limit to sensible number (ALSA plugins accept a crazy amount of channels)? */
+    if( isPlug && maxChans > 128 )
+    {
+        maxChans = 128;
+        PA_DEBUG(( "%s: Limiting number of plugin channels to %u\n", __FUNCTION__, maxChans ));
+    }
+
+    /* TWEAKME:
+     *
+     * Giving values for default min and max latency is not
+     * straightforward.  Here are our objectives:
+     *
+     *         * for low latency, we want to give the lowest value
+     *         that will work reliably.  This varies based on the
+     *         sound card, kernel, CPU, etc.  I think it is better
+     *         to give sub-optimal latency than to give a number
+     *         too low and cause dropouts.  My conservative
+     *         estimate at this point is to base it on 4096-sample
+     *         latency at 44.1 kHz, which gives a latency of 23ms.
+     *         * for high latency we want to give a large enough
+     *         value that dropouts are basically impossible.  This
+     *         doesn't really require as much tweaking, since
+     *         providing too large a number will just cause us to
+     *         select the nearest setting that will work at stream
+     *         config time.
+     */
+    ENSURE_( snd_pcm_hw_params_set_buffer_size_near( pcm, hwParams, &lowLatency ), paUnanticipatedHostError );
+
+    /* Have to reset hwParams, to set new buffer size */
+    ENSURE_( snd_pcm_hw_params_any( pcm, hwParams ), paUnanticipatedHostError ); 
+    ENSURE_( snd_pcm_hw_params_set_buffer_size_near( pcm, hwParams, &highLatency ), paUnanticipatedHostError );
+
+    *minChannels = (int)minChans;
+    *maxChannels = (int)maxChans;
+    *defaultSampleRate = defaultSr;
+    *defaultLowLatency = (double) lowLatency / *defaultSampleRate;
+    *defaultHighLatency = (double) highLatency / *defaultSampleRate;
+
+end:
+    snd_pcm_close( pcm );
+    return result;
+
+error:
+    goto end;
+}
+
+/* Initialize device info with invalid values (maxInputChannels and maxOutputChannels are set to zero since these indicate
+ * wether input/output is available) */
+static void InitializeDeviceInfo( PaDeviceInfo *deviceInfo )
+{
+    deviceInfo->structVersion = -1;
+    deviceInfo->name = NULL;
+    deviceInfo->hostApi = -1;
+    deviceInfo->maxInputChannels = 0;
+    deviceInfo->maxOutputChannels = 0;
+    deviceInfo->defaultLowInputLatency = -1.;
+    deviceInfo->defaultLowOutputLatency = -1.;
+    deviceInfo->defaultHighInputLatency = -1.;
+    deviceInfo->defaultHighOutputLatency = -1.;
+    deviceInfo->defaultSampleRate = -1.;
+}
+
+/* Helper struct */
+typedef struct
+{
+    char *alsaName;
+    char *name;
+    int isPlug;
+    int hasPlayback;
+    int hasCapture;
+} DeviceNames;
+
+static PaError PaAlsa_StrDup( PaAlsaHostApiRepresentation *alsaApi,
+        char **dst,
+        const char *src)
+{
+    PaError result = paNoError;
+    int len = strlen( src ) + 1;
+
+    /* PA_DEBUG(("PaStrDup %s %d\n", src, len)); */
+
+    PA_UNLESS( *dst = (char *)PaUtil_GroupAllocateMemory( alsaApi->allocations, len ),
+            paInsufficientMemory );
+    strncpy( *dst, src, len );
+
+error:
+    return result;
+}
+
+/* Disregard some standard plugins
+ */
+static int IgnorePlugin( const char *pluginId )
+{
+    /* XXX: dmix and default ignored because after opening and closing, they seem to keep hogging resources.
+     */
+    static const char *ignoredPlugins[] = {"hw", "plughw", "plug", "dsnoop", "tee",
+        "file", "null", "shm", "cards", "dmix", "default", NULL};
+    int i = 0;
+    while( ignoredPlugins[i] )
+    {
+        if( !strcmp( pluginId, ignoredPlugins[i] ) )
+        {
+            return 1;
+        }
+        ++i;
+    }
+
+    return 0;
+}
+
+/* Build PaDeviceInfo list, ignore devices for which we cannot determine capabilities (possibly busy, sigh) */
+static PaError BuildDeviceList( PaAlsaHostApiRepresentation *alsaApi )
+{
+    PaUtilHostApiRepresentation *baseApi = &alsaApi->baseHostApiRep;
+    PaAlsaDeviceInfo *deviceInfoArray;
+    int cardIdx = -1, devIdx = 0;
+    snd_ctl_card_info_t *cardInfo;
+    PaError result = paNoError;
+    size_t numDeviceNames = 0, maxDeviceNames = 1, i;
+    DeviceNames *deviceNames = NULL;
+    snd_config_t *topNode = NULL;
+    snd_pcm_info_t *pcmInfo;
+    int res;
+    int blocking = SND_PCM_NONBLOCK;
+    char alsaCardName[50];
+    if( getenv( "PA_ALSA_INITIALIZE_BLOCK" ) && atoi( getenv( "PA_ALSA_INITIALIZE_BLOCK" ) ) )
+        blocking = 0;
+
+    /* These two will be set to the first working input and output device, respectively */
+    baseApi->info.defaultInputDevice = paNoDevice;
+    baseApi->info.defaultOutputDevice = paNoDevice;
+
+    /* count the devices by enumerating all the card numbers */
+
+    /* snd_card_next() modifies the integer passed to it to be:
+     *      the index of the first card if the parameter is -1
+     *      the index of the next card if the parameter is the index of a card
+     *      -1 if there are no more cards
+     *
+     * The function itself returns 0 if it succeeded. */
+    cardIdx = -1;
+    snd_ctl_card_info_alloca( &cardInfo );
+    snd_pcm_info_alloca( &pcmInfo );
+    while( snd_card_next( &cardIdx ) == 0 && cardIdx >= 0 )
+    {
+        char *cardName;
+        int devIdx = -1;
+        snd_ctl_t *ctl;
+        char buf[50];
+
+        snprintf( alsaCardName, sizeof (alsaCardName), "hw:%d", cardIdx );
+
+        /* Acquire name of card */
+        if( snd_ctl_open( &ctl, alsaCardName, 0 ) < 0 )
+        {
+            /* Unable to open card :( */
+            PA_DEBUG(( "%s: Unable to open device %s\n", __FUNCTION__, alsaCardName ));
+            continue;
+        }
+        snd_ctl_card_info( ctl, cardInfo );
+
+        PA_ENSURE( PaAlsa_StrDup( alsaApi, &cardName, snd_ctl_card_info_get_name( cardInfo )) );
+
+        while( snd_ctl_pcm_next_device( ctl, &devIdx ) == 0 && devIdx >= 0 )
+        {
+            char *alsaDeviceName, *deviceName;
+            size_t len;
+            int hasPlayback = 0, hasCapture = 0;
+            snprintf( buf, sizeof (buf), "%s:%d,%d", "hw", cardIdx, devIdx );
+
+            /* Obtain info about this particular device */
+            snd_pcm_info_set_device( pcmInfo, devIdx );
+            snd_pcm_info_set_subdevice( pcmInfo, 0 );
+            snd_pcm_info_set_stream( pcmInfo, SND_PCM_STREAM_CAPTURE );
+            if( snd_ctl_pcm_info( ctl, pcmInfo ) >= 0 )
+            {
+                hasCapture = 1;
+            }
+            
+            snd_pcm_info_set_stream( pcmInfo, SND_PCM_STREAM_PLAYBACK );
+            if( snd_ctl_pcm_info( ctl, pcmInfo ) >= 0 )
+            {
+                hasPlayback = 1;
+            }
+
+            if( !hasPlayback && !hasCapture )
+            {
+                continue;   /* Error */
+            }
+
+            /* The length of the string written by snprintf plus terminating 0 */
+            len = snprintf( NULL, 0, "%s: %s (%s)", cardName, snd_pcm_info_get_name( pcmInfo ), buf ) + 1;
+            PA_UNLESS( deviceName = (char *)PaUtil_GroupAllocateMemory( alsaApi->allocations, len ),
+                    paInsufficientMemory );
+            snprintf( deviceName, len, "%s: %s (%s)", cardName,
+                    snd_pcm_info_get_name( pcmInfo ), buf );
+
+            ++numDeviceNames;
+            if( !deviceNames || numDeviceNames > maxDeviceNames )
+            {
+                maxDeviceNames *= 2;
+                PA_UNLESS( deviceNames = (DeviceNames *) realloc( deviceNames, maxDeviceNames * sizeof (DeviceNames) ),
+                        paInsufficientMemory );
+            }
+
+            PA_ENSURE( PaAlsa_StrDup( alsaApi, &alsaDeviceName, buf ) );
+
+            deviceNames[ numDeviceNames - 1 ].alsaName = alsaDeviceName;
+            deviceNames[ numDeviceNames - 1 ].name = deviceName;
+            deviceNames[ numDeviceNames - 1 ].isPlug = 0;
+            deviceNames[ numDeviceNames - 1 ].hasPlayback = hasPlayback;
+            deviceNames[ numDeviceNames - 1 ].hasCapture = hasCapture;
+        }
+        snd_ctl_close( ctl );
+    }
+
+    /* Iterate over plugin devices */
+    if( NULL == snd_config )
+    {
+        /* snd_config_update is called implicitly by some functions, if this hasn't happened snd_config will be NULL (bleh) */
+        ENSURE_( snd_config_update(), paUnanticipatedHostError );
+        PA_DEBUG(( "Updating snd_config\n" ));
+    }
+    assert( snd_config );
+    if( (res = snd_config_search( snd_config, "pcm", &topNode )) >= 0 )
+    {
+        snd_config_iterator_t i, next;
+
+        snd_config_for_each( i, next, topNode )
+        {
+            const char *tpStr = "unknown", *idStr = NULL;
+            int err = 0;
+
+            char *alsaDeviceName, *deviceName;
+            snd_config_t *n = snd_config_iterator_entry( i ), * tp = NULL;;
+
+            if( (err = snd_config_search( n, "type", &tp )) < 0 )
+            {
+                if( -ENOENT != err )
+                {
+                    ENSURE_(err, paUnanticipatedHostError);
+                }
+            }
+            else 
+            {
+                ENSURE_( snd_config_get_string( tp, &tpStr ), paUnanticipatedHostError );
+            }
+            ENSURE_( snd_config_get_id( n, &idStr ), paUnanticipatedHostError );
+            if( IgnorePlugin( idStr ) )
+            {
+                PA_DEBUG(( "%s: Ignoring ALSA plugin device %s of type %s\n", __FUNCTION__, idStr, tpStr ));
+                continue;
+            }
+            PA_DEBUG(( "%s: Found plugin %s of type %s\n", __FUNCTION__, idStr, tpStr ));
+
+            PA_UNLESS( alsaDeviceName = (char*)PaUtil_GroupAllocateMemory( alsaApi->allocations,
+                                                            strlen(idStr) + 6 ), paInsufficientMemory );
+            strcpy( alsaDeviceName, idStr );
+            PA_UNLESS( deviceName = (char*)PaUtil_GroupAllocateMemory( alsaApi->allocations,
+                                                            strlen(idStr) + 1 ), paInsufficientMemory );
+            strcpy( deviceName, idStr );
+
+            ++numDeviceNames;
+            if( !deviceNames || numDeviceNames > maxDeviceNames )
+            {
+                maxDeviceNames *= 2;
+                PA_UNLESS( deviceNames = (DeviceNames *) realloc( deviceNames, maxDeviceNames * sizeof (DeviceNames) ),
+                        paInsufficientMemory );
+            }
+
+            deviceNames[numDeviceNames - 1].alsaName = alsaDeviceName;
+            deviceNames[numDeviceNames - 1].name = deviceName;
+            deviceNames[numDeviceNames - 1].isPlug = 1;
+            deviceNames[numDeviceNames - 1].hasPlayback = 1;
+            deviceNames[numDeviceNames - 1].hasCapture = 1;
+        }
+    }
+    else
+        PA_DEBUG(( "%s: Iterating over ALSA plugins failed: %s\n", __FUNCTION__, snd_strerror( res ) ));
+
+    /* allocate deviceInfo memory based on the number of devices */
+    PA_UNLESS( baseApi->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
+            alsaApi->allocations, sizeof(PaDeviceInfo*) * (numDeviceNames) ), paInsufficientMemory );
+
+    /* allocate all device info structs in a contiguous block */
+    PA_UNLESS( deviceInfoArray = (PaAlsaDeviceInfo*)PaUtil_GroupAllocateMemory(
+            alsaApi->allocations, sizeof(PaAlsaDeviceInfo) * numDeviceNames ), paInsufficientMemory );
+
+    /* Loop over list of cards, filling in info, if a device is deemed unavailable (can't get name),
+     * it's ignored.
+     */
+    /* while( snd_card_next( &cardIdx ) == 0 && cardIdx >= 0 ) */
+    for( i = 0, devIdx = 0; i < numDeviceNames; ++i )
+    {
+        snd_pcm_t *pcm;
+        PaAlsaDeviceInfo *deviceInfo = &deviceInfoArray[devIdx];
+        PaDeviceInfo *baseDeviceInfo = &deviceInfo->baseDeviceInfo;
+        int canMmap = -1;
+
+        /* Zero fields */
+        InitializeDeviceInfo( baseDeviceInfo );
+
+        /* to determine device capabilities, we must open the device and query the
+         * hardware parameter configuration space */
+
+        /* Query capture */
+        if( deviceNames[i].hasCapture &&
+                snd_pcm_open( &pcm, deviceNames[i].alsaName, SND_PCM_STREAM_CAPTURE, blocking ) >= 0 )
+        {
+            if( GropeDevice( pcm, deviceNames[i].isPlug, StreamDirection_In, blocking, deviceInfo,
+                        &canMmap ) != paNoError )
+            {
+                /* Error */
+                PA_DEBUG(("%s: Failed groping %s for capture\n", __FUNCTION__, deviceNames[i].alsaName));
+                continue;
+            }
+        }
+
+        /* Query playback */
+        if( deviceNames[i].hasPlayback &&
+                snd_pcm_open( &pcm, deviceNames[i].alsaName, SND_PCM_STREAM_PLAYBACK, blocking ) >= 0 )
+        {
+            if( GropeDevice( pcm, deviceNames[i].isPlug, StreamDirection_Out, blocking, deviceInfo,
+                        &canMmap ) != paNoError )
+            {
+                /* Error */
+                PA_DEBUG(("%s: Failed groping %s for playback\n", __FUNCTION__, deviceNames[i].alsaName));
+                continue;
+            }
+        }
+
+        if( 0 == canMmap )
+        {
+            PA_DEBUG(("%s: Device %s doesn't support mmap\n", __FUNCTION__, deviceNames[i].alsaName));
+            continue;
+        }
+
+        baseDeviceInfo->structVersion = 2;
+        baseDeviceInfo->hostApi = alsaApi->hostApiIndex;
+        baseDeviceInfo->name = deviceNames[i].name;
+        deviceInfo->alsaName = deviceNames[i].alsaName;
+        deviceInfo->isPlug = deviceNames[i].isPlug;
+
+        /* A: Storing pointer to PaAlsaDeviceInfo object as pointer to PaDeviceInfo object.
+         * Should now be safe to add device info, unless the device supports neither capture nor playback
+         */
+        if( baseDeviceInfo->maxInputChannels > 0 || baseDeviceInfo->maxOutputChannels > 0 )
+        {
+            if( baseApi->info.defaultInputDevice == paNoDevice && baseDeviceInfo->maxInputChannels > 0 )
+                baseApi->info.defaultInputDevice = devIdx;
+            if(  baseApi->info.defaultOutputDevice == paNoDevice && baseDeviceInfo->maxOutputChannels > 0 )
+                baseApi->info.defaultOutputDevice = devIdx;
+            PA_DEBUG(("%s: Adding device %s\n", __FUNCTION__, deviceNames[i].name));
+            baseApi->deviceInfos[devIdx++] = (PaDeviceInfo *) deviceInfo;
+        }
+    }
+    free( deviceNames );
+
+    baseApi->info.deviceCount = devIdx;   /* Number of successfully queried devices */
+
+end:
+    return result;
+
+error:
+    /* No particular action */
+    goto end;
+}
+
+/* Check against known device capabilities */
+static PaError ValidateParameters( const PaStreamParameters *parameters, PaUtilHostApiRepresentation *hostApi, StreamDirection mode )
+{
+    PaError result = paNoError;
+    int maxChans;
+    const PaAlsaDeviceInfo *deviceInfo = NULL;
+    assert( parameters );
+
+    if( parameters->device != paUseHostApiSpecificDeviceSpecification )
+    {
+        assert( parameters->device < hostApi->info.deviceCount );
+        PA_UNLESS( parameters->hostApiSpecificStreamInfo == NULL, paBadIODeviceCombination );
+        deviceInfo = GetDeviceInfo( hostApi, parameters->device );
+    }
+    else
+    {
+        const PaAlsaStreamInfo *streamInfo = parameters->hostApiSpecificStreamInfo;
+
+        PA_UNLESS( parameters->device == paUseHostApiSpecificDeviceSpecification, paInvalidDevice );
+        PA_UNLESS( streamInfo->size == sizeof (PaAlsaStreamInfo) && streamInfo->version == 1,
+                paIncompatibleHostApiSpecificStreamInfo );
+        PA_UNLESS( streamInfo->deviceString != NULL, paInvalidDevice );
+
+        /* Skip further checking */
+        return paNoError;
+    }
+
+    assert( deviceInfo );
+    assert( parameters->hostApiSpecificStreamInfo == NULL );
+    maxChans = (StreamDirection_In == mode ? deviceInfo->baseDeviceInfo.maxInputChannels :
+        deviceInfo->baseDeviceInfo.maxOutputChannels);
+    PA_UNLESS( parameters->channelCount <= maxChans, paInvalidChannelCount );
+
+error:
+    return result;
+}
+
+/* Given an open stream, what sample formats are available? */
+static PaSampleFormat GetAvailableFormats( snd_pcm_t *pcm )
+{
+    PaSampleFormat available = 0;
+    snd_pcm_hw_params_t *hwParams;
+    snd_pcm_hw_params_alloca( &hwParams );
+
+    snd_pcm_hw_params_any( pcm, hwParams );
+
+    if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_FLOAT ) >= 0)
+        available |= paFloat32;
+
+    if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S32 ) >= 0)
+        available |= paInt32;
+
+    if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S24 ) >= 0)
+        available |= paInt24;
+
+    if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S16 ) >= 0)
+        available |= paInt16;
+
+    if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_U8 ) >= 0)
+        available |= paUInt8;
+
+    if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S8 ) >= 0)
+        available |= paInt8;
+
+    return available;
+}
+
+static snd_pcm_format_t Pa2AlsaFormat( PaSampleFormat paFormat )
+{
+    switch( paFormat )
+    {
+        case paFloat32:
+            return SND_PCM_FORMAT_FLOAT;
+
+        case paInt16:
+            return SND_PCM_FORMAT_S16;
+
+        case paInt24:
+            return SND_PCM_FORMAT_S24;
+
+        case paInt32:
+            return SND_PCM_FORMAT_S32;
+
+        case paInt8:
+            return SND_PCM_FORMAT_S8;
+
+        case paUInt8:
+            return SND_PCM_FORMAT_U8;
+
+        default:
+            return SND_PCM_FORMAT_UNKNOWN;
+    }
+}
+
+/** Open an ALSA pcm handle.
+ * 
+ * The device to be open can be specified in a custom PaAlsaStreamInfo struct, or it will be a device number. In case of a
+ * device number, it maybe specified through an env variable (PA_ALSA_PLUGHW) that we should open the corresponding plugin
+ * device.
+ */
+static PaError AlsaOpen( const PaUtilHostApiRepresentation *hostApi, const PaStreamParameters *params, StreamDirection
+        streamDir, snd_pcm_t **pcm )
+{
+    PaError result = paNoError;
+    int ret;
+    char dnameArray[50];
+    const char* deviceName = dnameArray;
+    const PaAlsaDeviceInfo *deviceInfo = NULL;
+    PaAlsaStreamInfo *streamInfo = (PaAlsaStreamInfo *)params->hostApiSpecificStreamInfo;
+
+    if( !streamInfo )
+    {
+        int usePlug = 0;
+        deviceInfo = GetDeviceInfo( hostApi, params->device );
+        
+        /* If device name starts with hw: and PA_ALSA_PLUGHW is 1, we open the plughw device instead */
+        if( !strncmp( "hw:", deviceInfo->alsaName, 3 ) && getenv( "PA_ALSA_PLUGHW" ) )
+            usePlug = atoi( getenv( "PA_ALSA_PLUGHW" ) );
+        if( usePlug )
+            snprintf( dnameArray, 50, "plug%s", deviceInfo->alsaName );
+        else
+            deviceName = deviceInfo->alsaName;
+    }
+    else
+        deviceName = streamInfo->deviceString;
+
+    PA_DEBUG(( "%s: Opening device %s\n", __FUNCTION__, deviceName ));
+    if( (ret = snd_pcm_open( pcm, deviceName, streamDir == StreamDirection_In ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
+                    SND_PCM_NONBLOCK )) < 0 )
+    {
+        /* Not to be closed */
+        *pcm = NULL;
+        ENSURE_( ret, ret == -EBUSY ? paDeviceUnavailable : paBadIODeviceCombination );
+    }
+    ENSURE_( snd_pcm_nonblock( *pcm, 0 ), paUnanticipatedHostError );
+
+end:
+    return result;
+
+error:
+    goto end;
+}
+
+static PaError TestParameters( const PaUtilHostApiRepresentation *hostApi, const PaStreamParameters *parameters,
+        double sampleRate, StreamDirection streamDir )
+{
+    PaError result = paNoError;
+    snd_pcm_t *pcm = NULL;
+    PaSampleFormat availableFormats;
+    /* We are able to adapt to a number of channels less than what the device supports */
+    unsigned int numHostChannels;
+    PaSampleFormat hostFormat;
+    snd_pcm_hw_params_t *hwParams;
+    snd_pcm_hw_params_alloca( &hwParams );
+    
+    if( !parameters->hostApiSpecificStreamInfo )
+    {
+        const PaAlsaDeviceInfo *devInfo = GetDeviceInfo( hostApi, parameters->device );
+        numHostChannels = PA_MAX( parameters->channelCount, StreamDirection_In == streamDir ?
+                devInfo->minInputChannels : devInfo->minOutputChannels );
+    }
+    else
+        numHostChannels = parameters->channelCount;
+
+    PA_ENSURE( AlsaOpen( hostApi, parameters, streamDir, &pcm ) );
+
+    snd_pcm_hw_params_any( pcm, hwParams );
+
+    if( SetApproximateSampleRate( pcm, hwParams, sampleRate ) < 0 )
+    {
+        result = paInvalidSampleRate;
+        goto error;
+    }
+
+    if( snd_pcm_hw_params_set_channels( pcm, hwParams, numHostChannels ) < 0 )
+    {
+        result = paInvalidChannelCount;
+        goto error;
+    }
+
+    /* See if we can find a best possible match */
+    availableFormats = GetAvailableFormats( pcm );
+    PA_ENSURE( hostFormat = PaUtil_SelectClosestAvailableFormat( availableFormats, parameters->sampleFormat ) );
+    ENSURE_( snd_pcm_hw_params_set_format( pcm, hwParams, Pa2AlsaFormat( hostFormat ) ), paUnanticipatedHostError );
+
+    {
+        /* It happens that this call fails because the device is busy */
+        int ret = 0;
+        if( (ret = snd_pcm_hw_params( pcm, hwParams )) < 0)
+        {
+            ENSURE_( ret, ret == -EBUSY ? paDeviceUnavailable : paUnanticipatedHostError );
+        }
+    }
+
+end:
+    if( pcm )
+    {
+        snd_pcm_close( pcm );
+    }
+    return result;
+
+error:
+    goto end;
+}
+
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+                                  const PaStreamParameters *inputParameters,
+                                  const PaStreamParameters *outputParameters,
+                                  double sampleRate )
+{
+    int inputChannelCount = 0, outputChannelCount = 0;
+    PaSampleFormat inputSampleFormat, outputSampleFormat;
+    PaError result = paFormatIsSupported;
+
+    if( inputParameters )
+    {
+        PA_ENSURE( ValidateParameters( inputParameters, hostApi, StreamDirection_In ) );
+
+        inputChannelCount = inputParameters->channelCount;
+        inputSampleFormat = inputParameters->sampleFormat;
+    }
+
+    if( outputParameters )
+    {
+        PA_ENSURE( ValidateParameters( outputParameters, hostApi, StreamDirection_Out ) );
+
+        outputChannelCount = outputParameters->channelCount;
+        outputSampleFormat = outputParameters->sampleFormat;
+    }
+
+    if( inputChannelCount )
+    {
+        if( (result = TestParameters( hostApi, inputParameters, sampleRate, StreamDirection_In ))
+                != paNoError )
+            goto error;
+    }
+    if ( outputChannelCount )
+    {
+        if( (result = TestParameters( hostApi, outputParameters, sampleRate, StreamDirection_Out ))
+                != paNoError )
+            goto error;
+    }
+
+    return paFormatIsSupported;
+
+error:
+    return result;
+}
+
+static PaError PaAlsaStreamComponent_Initialize( PaAlsaStreamComponent *self, PaAlsaHostApiRepresentation *alsaApi,
+        const PaStreamParameters *params, StreamDirection streamDir, int callbackMode )
+{
+    PaError result = paNoError;
+    PaSampleFormat userSampleFormat = params->sampleFormat, hostSampleFormat;
+    assert( params->channelCount > 0 );
+
+    /* Make sure things have an initial value */
+    memset( self, 0, sizeof (PaAlsaStreamComponent) );
+
+    if( NULL == params->hostApiSpecificStreamInfo )
+    {
+        const PaAlsaDeviceInfo *devInfo = GetDeviceInfo( &alsaApi->baseHostApiRep, params->device );
+        self->numHostChannels = PA_MAX( params->channelCount, StreamDirection_In == streamDir ? devInfo->minInputChannels
+                : devInfo->minOutputChannels );
+    }
+    else
+    {
+        /* We're blissfully unaware of the minimum channelCount */
+        self->numHostChannels = params->channelCount;
+    }
+
+    PA_ENSURE( AlsaOpen( &alsaApi->baseHostApiRep, params, streamDir, &self->pcm ) );
+    self->nfds = snd_pcm_poll_descriptors_count( self->pcm );
+    hostSampleFormat = PaUtil_SelectClosestAvailableFormat( GetAvailableFormats( self->pcm ), userSampleFormat );
+
+    self->hostSampleFormat = hostSampleFormat;
+    self->nativeFormat = Pa2AlsaFormat( hostSampleFormat );
+    self->hostInterleaved = self->userInterleaved = !(userSampleFormat & paNonInterleaved);
+    self->numUserChannels = params->channelCount;
+    self->streamDir = streamDir;
+
+    if( !callbackMode && !self->userInterleaved )
+    {
+        /* Pre-allocate non-interleaved user provided buffers */
+        PA_UNLESS( self->userBuffers = PaUtil_AllocateMemory( sizeof (void *) * self->numUserChannels ),
+                paInsufficientMemory );
+    }
+
+error:
+    return result;
+}
+
+static void PaAlsaStreamComponent_Terminate( PaAlsaStreamComponent *self )
+{
+    snd_pcm_close( self->pcm );
+    if( self->userBuffers )
+        PaUtil_FreeMemory( self->userBuffers );
+}
+
+int nearbyint_(float value) {
+    if(  value - (int)value > .5 )
+        return (int)ceil( value );
+    return (int)floor( value );
+}
+
+/** Initiate configuration, preparing for determining a period size suitable for both capture and playback components.
+ *
+ */
+static PaError PaAlsaStreamComponent_InitialConfigure( PaAlsaStreamComponent *self, const PaStreamParameters *params,
+        int primeBuffers, snd_pcm_hw_params_t *hwParams, double *sampleRate )
+{
+    /* Configuration consists of setting all of ALSA's parameters.
+     * These parameters come in two flavors: hardware parameters
+     * and software paramters.  Hardware parameters will affect
+     * the way the device is initialized, software parameters
+     * affect the way ALSA interacts with me, the user-level client.
+     */
+
+    PaError result = paNoError;
+    snd_pcm_access_t accessMode, alternateAccessMode;
+    int dir = 0;
+    snd_pcm_t *pcm = self->pcm;
+    double sr = *sampleRate;
+    unsigned int minPeriods = 2;
+
+    /* self->framesPerBuffer = framesPerHostBuffer; */
+
+    /* ... fill up the configuration space with all possibile
+     * combinations of parameters this device will accept */
+    ENSURE_( snd_pcm_hw_params_any( pcm, hwParams ), paUnanticipatedHostError );
+
+    ENSURE_( snd_pcm_hw_params_set_periods_integer( pcm, hwParams ), paUnanticipatedHostError );
+    /* I think there should be at least 2 periods (even though ALSA doesn't appear to enforce this) */
+    dir = 0;
+    ENSURE_( snd_pcm_hw_params_set_periods_min( pcm, hwParams, &minPeriods, &dir ), paUnanticipatedHostError );
+
+    if( self->userInterleaved )
+    {
+        accessMode = SND_PCM_ACCESS_MMAP_INTERLEAVED;
+        alternateAccessMode = SND_PCM_ACCESS_MMAP_NONINTERLEAVED;
+    }
+    else
+    {
+        accessMode = SND_PCM_ACCESS_MMAP_NONINTERLEAVED;
+        alternateAccessMode = SND_PCM_ACCESS_MMAP_INTERLEAVED;
+    }
+    /* If requested access mode fails, try alternate mode */
+    if( snd_pcm_hw_params_set_access( pcm, hwParams, accessMode ) < 0 )
+    {
+        int err = 0;
+        if( (err = snd_pcm_hw_params_set_access( pcm, hwParams, alternateAccessMode )) < 0)
+        {
+            result = paUnanticipatedHostError;
+            if( -EINVAL == err )
+            {
+                PaUtil_SetLastHostErrorInfo( paALSA, err, "PA ALSA requires that a device supports mmap access" );
+            }
+            else
+            {
+                PaUtil_SetLastHostErrorInfo( paALSA, err, snd_strerror( err ) );
+            }
+            goto error;
+        }
+        /* Flip mode */
+        self->hostInterleaved = !self->userInterleaved;
+    }
+
+    ENSURE_( snd_pcm_hw_params_set_format( pcm, hwParams, self->nativeFormat ), paUnanticipatedHostError );
+
+    ENSURE_( SetApproximateSampleRate( pcm, hwParams, sr ), paInvalidSampleRate );
+    ENSURE_( GetExactSampleRate( hwParams, &sr ), paUnanticipatedHostError );
+    /* reject if there's no sample rate within 1% of the one requested */
+    if( (fabs( *sampleRate - sr ) / *sampleRate) > 0.01 )
+    {
+        PA_DEBUG(("%s: Wanted %f, closest sample rate was %d\n", __FUNCTION__, sampleRate, sr ));                 
+        PA_ENSURE( paInvalidSampleRate );
+    }
+
+    ENSURE_( snd_pcm_hw_params_set_channels( pcm, hwParams, self->numHostChannels ), paInvalidChannelCount );
+
+    *sampleRate = sr;
+
+end:
+    return result;
+
+error:
+    /* No particular action */
+    goto end;
+}
+
+/** Finish the configuration of the component's ALSA device.
+ *
+ * As part of this method, the component's bufferSize attribute will be set.
+ * @param latency: The latency for this component.
+ */
+static PaError PaAlsaStreamComponent_FinishConfigure( PaAlsaStreamComponent *self, snd_pcm_hw_params_t* hwParams,
+        const PaStreamParameters *params, int primeBuffers, double sampleRate, PaTime* latency )
+{
+    PaError result = paNoError;
+    snd_pcm_sw_params_t* swParams;
+    snd_pcm_uframes_t bufSz = 0;
+    *latency = -1.;
+
+    snd_pcm_sw_params_alloca( &swParams );
+
+    bufSz = (params->suggestedLatency * sampleRate) + self->framesPerBuffer;    /* One period does not count as latency */
+    ENSURE_( snd_pcm_hw_params_set_buffer_size_near( self->pcm, hwParams, &bufSz ), paUnanticipatedHostError );
+
+    /* Set the parameters! */
+    ENSURE_( snd_pcm_hw_params( self->pcm, hwParams ), paUnanticipatedHostError );
+    ENSURE_( snd_pcm_hw_params_get_buffer_size( hwParams, &self->bufferSize ), paUnanticipatedHostError );
+    /* Latency in seconds, one period is not counted as latency */
+    *latency = (self->bufferSize - self->framesPerBuffer) / sampleRate;
+
+    /* Now software parameters... */
+    ENSURE_( snd_pcm_sw_params_current( self->pcm, swParams ), paUnanticipatedHostError );
+
+    ENSURE_( snd_pcm_sw_params_set_start_threshold( self->pcm, swParams, self->framesPerBuffer ), paUnanticipatedHostError );
+    ENSURE_( snd_pcm_sw_params_set_stop_threshold( self->pcm, swParams, self->bufferSize ), paUnanticipatedHostError );
+
+    /* Silence buffer in the case of underrun */
+    if( !primeBuffers ) /* XXX: Make sense? */
+    {
+        snd_pcm_uframes_t boundary;
+        ENSURE_( snd_pcm_sw_params_get_boundary( swParams, &boundary ), paUnanticipatedHostError );
+        ENSURE_( snd_pcm_sw_params_set_silence_threshold( self->pcm, swParams, 0 ), paUnanticipatedHostError );
+        ENSURE_( snd_pcm_sw_params_set_silence_size( self->pcm, swParams, boundary ), paUnanticipatedHostError );
+    }
+        
+    ENSURE_( snd_pcm_sw_params_set_avail_min( self->pcm, swParams, self->framesPerBuffer ), paUnanticipatedHostError );
+    ENSURE_( snd_pcm_sw_params_set_xfer_align( self->pcm, swParams, 1 ), paUnanticipatedHostError );
+    ENSURE_( snd_pcm_sw_params_set_tstamp_mode( self->pcm, swParams, SND_PCM_TSTAMP_MMAP ), paUnanticipatedHostError );
+
+    /* Set the parameters! */
+    ENSURE_( snd_pcm_sw_params( self->pcm, swParams ), paUnanticipatedHostError );
+
+error:
+    return result;
+}
+
+static PaError PaAlsaStream_Initialize( PaAlsaStream *self, PaAlsaHostApiRepresentation *alsaApi, const PaStreamParameters *inParams,
+        const PaStreamParameters *outParams, double sampleRate, unsigned long framesPerUserBuffer, PaStreamCallback callback,
+        PaStreamFlags streamFlags, void *userData )
+{
+    PaError result = paNoError;
+    assert( self );
+
+    memset( self, 0, sizeof (PaAlsaStream) );
+
+    if( NULL != callback )
+    {
+        PaUtil_InitializeStreamRepresentation( &self->streamRepresentation,
+                                               &alsaApi->callbackStreamInterface,
+                                               callback, userData );
+        self->callbackMode = 1;
+    }
+    else
+    {
+        PaUtil_InitializeStreamRepresentation( &self->streamRepresentation,
+                                               &alsaApi->blockingStreamInterface,
+                                               NULL, userData );
+    }
+
+    self->framesPerUserBuffer = framesPerUserBuffer;
+    self->neverDropInput = streamFlags & paNeverDropInput;
+    /* XXX: Ignore paPrimeOutputBuffersUsingStreamCallback untill buffer priming is fully supported in pa_process.c */
+    /*
+    if( outParams & streamFlags & paPrimeOutputBuffersUsingStreamCallback )
+        self->primeBuffers = 1;
+        */
+    memset( &self->capture, 0, sizeof (PaAlsaStreamComponent) );
+    memset( &self->playback, 0, sizeof (PaAlsaStreamComponent) );
+    if( inParams )
+    {
+        PA_ENSURE( PaAlsaStreamComponent_Initialize( &self->capture, alsaApi, inParams, StreamDirection_In, NULL != callback ) );
+    }
+    if( outParams )
+    {
+        PA_ENSURE( PaAlsaStreamComponent_Initialize( &self->playback, alsaApi, outParams, StreamDirection_Out, NULL != callback ) );
+    }
+
+    assert( self->capture.nfds || self->playback.nfds );
+
+    PA_UNLESS( self->pfds = (struct pollfd*)PaUtil_AllocateMemory( (self->capture.nfds +
+                    self->playback.nfds) * sizeof (struct pollfd) ), paInsufficientMemory );
+
+    PaUtil_InitializeCpuLoadMeasurer( &self->cpuLoadMeasurer, sampleRate );
+    ASSERT_CALL_( PaUnixMutex_Initialize( &self->stateMtx ), paNoError );
+
+error:
+    return result;
+}
+
+/** Free resources associated with stream, and eventually stream itself.
+ *
+ * Frees allocated memory, and terminates individual StreamComponents.
+ */
+static void PaAlsaStream_Terminate( PaAlsaStream *self )
+{
+    assert( self );
+
+    if( self->capture.pcm )
+    {
+        PaAlsaStreamComponent_Terminate( &self->capture );
+    }
+    if( self->playback.pcm )
+    {
+        PaAlsaStreamComponent_Terminate( &self->playback );
+    }
+
+    PaUtil_FreeMemory( self->pfds );
+    ASSERT_CALL_( PaUnixMutex_Terminate( &self->stateMtx ), paNoError );
+
+    PaUtil_FreeMemory( self );
+}
+
+/** Calculate polling timeout
+ *
+ * @param frames Time to wait
+ * @return Polling timeout in milliseconds
+ */
+static int CalculatePollTimeout( const PaAlsaStream *stream, unsigned long frames )
+{
+    assert( stream->streamRepresentation.streamInfo.sampleRate > 0.0 );
+    /* Period in msecs, rounded up */
+    return (int)ceil( 1000 * frames / stream->streamRepresentation.streamInfo.sampleRate );
+}
+
+/** Determine size per host buffer.
+ *
+ * During this method call, the component's framesPerBuffer attribute gets computed, and the corresponding period size
+ * gets configured for the device.
+ * @param accurate: If the configured period size is non-integer, this will be set to 0.
+ */
+static PaError PaAlsaStreamComponent_DetermineFramesPerBuffer( PaAlsaStreamComponent* self, const PaStreamParameters* params,
+        unsigned long framesPerUserBuffer, double sampleRate, snd_pcm_hw_params_t* hwParams, int* accurate )
+{
+    PaError result = paNoError;
+    unsigned long bufferSize = params->suggestedLatency * sampleRate, framesPerHostBuffer;
+    int dir = 0;
+    
+    {
+        snd_pcm_uframes_t tmp;
+        snd_pcm_hw_params_get_buffer_size_min( hwParams, &tmp );
+        bufferSize = PA_MAX( bufferSize, tmp );
+        snd_pcm_hw_params_get_buffer_size_max( hwParams, &tmp );
+        bufferSize = PA_MIN( bufferSize, tmp );
+    }
+
+    assert( bufferSize > 0 );
+
+    if( framesPerUserBuffer != paFramesPerBufferUnspecified )
+    {
+        /* Preferably the host buffer size should be a multiple of the user buffer size */
+
+        if( bufferSize > framesPerUserBuffer )
+        {
+            snd_pcm_uframes_t remainder = bufferSize % framesPerUserBuffer;
+            if( remainder > framesPerUserBuffer / 2. )
+                bufferSize += framesPerUserBuffer - remainder;
+            else
+                bufferSize -= remainder;
+
+            assert( bufferSize % framesPerUserBuffer == 0 );
+        }
+        else if( framesPerUserBuffer % bufferSize != 0 )
+        {
+            /*  Find a good compromise between user specified latency and buffer size */
+            if( bufferSize > framesPerUserBuffer * .75 )
+            {
+                bufferSize = framesPerUserBuffer;
+            }
+            else
+            {
+                snd_pcm_uframes_t newSz = framesPerUserBuffer;
+                while( newSz / 2 >= bufferSize )
+                {
+                    if( framesPerUserBuffer % (newSz / 2) != 0 )
+                    {
+                        /* No use dividing any further */
+                        break;
+                    }
+                    newSz /= 2;
+                }
+                bufferSize = newSz;
+            }
+
+            assert( framesPerUserBuffer % bufferSize == 0 );
+        }
+    }
+
+    /* Using 5 as a base number of periods, we try to approximate the suggested latency (+1 period),
+       finding a combination of period/buffer size which best fits these constraints */
+    {
+        unsigned numPeriods = 4, maxPeriods = 0;
+        /* It may be that the device only supports 2 periods for instance */
+        dir = 0;
+        ENSURE_( snd_pcm_hw_params_get_periods_max( hwParams, &maxPeriods, &dir ), paUnanticipatedHostError );
+        assert( maxPeriods > 1 );
+        /* One period is not counted as latency */
+        maxPeriods -= 1;
+        numPeriods = PA_MIN( maxPeriods, numPeriods );
+
+        if( framesPerUserBuffer != paFramesPerBufferUnspecified )
+        {
+            framesPerHostBuffer = framesPerUserBuffer;
+            if( framesPerHostBuffer < bufferSize )
+            {
+                while( bufferSize / framesPerHostBuffer > numPeriods )
+                {
+                    framesPerHostBuffer *= 2;
+                }
+            }
+            else
+            {
+                while( bufferSize / framesPerHostBuffer < numPeriods )
+                {
+                    if( framesPerUserBuffer % (framesPerHostBuffer / 2) != 0 )
+                    {
+                        /* Can't be divided any further */
+                        break;
+                    }
+                    framesPerHostBuffer /= 2;
+                }
+            }
+
+            if( framesPerHostBuffer < framesPerUserBuffer )
+            {
+                assert( framesPerUserBuffer % framesPerHostBuffer == 0 );
+                if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer, 0 ) < 0 )
+                {
+                    if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer * 2, 0 ) == 0 )
+                        framesPerHostBuffer *= 2;
+                    else if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer / 2, 0 ) == 0 )
+                        framesPerHostBuffer /= 2;
+                }
+            }
+            else
+            {
+                assert( framesPerHostBuffer % framesPerUserBuffer == 0 );
+                if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer, 0 ) < 0 )
+                {
+                    if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer + framesPerUserBuffer, 0 ) == 0 )
+                        framesPerHostBuffer += framesPerUserBuffer;
+                    else if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer - framesPerUserBuffer, 0 ) == 0 )
+                        framesPerHostBuffer -= framesPerUserBuffer;
+                }
+            }
+        }
+        else
+        {
+            framesPerHostBuffer = bufferSize / numPeriods;
+        }
+    }
+
+    assert( framesPerHostBuffer > 0 );
+    {
+        snd_pcm_uframes_t min = 0, max = 0;
+        ENSURE_( snd_pcm_hw_params_get_period_size_min( hwParams, &min, NULL ), paUnanticipatedHostError );
+        ENSURE_( snd_pcm_hw_params_get_period_size_max( hwParams, &max, NULL ), paUnanticipatedHostError );
+
+        if( framesPerHostBuffer < min )
+        {
+            framesPerHostBuffer = min;
+            PA_DEBUG(( "%s: The determined period size (%lu) is less than minimum (%lu)\n", __FUNCTION__,
+                        framesPerHostBuffer, min ));
+        }
+        else if( framesPerHostBuffer > max )
+        {
+            framesPerHostBuffer = max;
+            PA_DEBUG(( "%s: The determined period size (%lu) is greater than maximum (%lu)\n", __FUNCTION__,
+                        framesPerHostBuffer, max ));
+        }
+
+        assert( framesPerHostBuffer >= min && framesPerHostBuffer <= max );
+        dir = 0;
+        ENSURE_( snd_pcm_hw_params_set_period_size_near( self->pcm, hwParams, &framesPerHostBuffer, &dir ),
+                paUnanticipatedHostError );
+        if( dir != 0 )
+        {
+            PA_DEBUG(( "%s: The configured period size is non-integer.\n", __FUNCTION__, dir ));
+            *accurate = 0;
+        }
+    }
+    self->framesPerBuffer = framesPerHostBuffer;
+
+error:
+    return result;
+}
+
+/* We need to determine how many frames per host buffer (period) to use.  Our
+ * goals are to provide the best possible performance, but also to
+ * honor the requested latency settings as closely as we can. Therefore this
+ * decision is based on:
+ *
+ *   - the period sizes that playback and/or capture support.  The
+ *     host buffer size has to be one of these.
+ *   - the number of periods that playback and/or capture support.
+ *
+ * We want to make period_size*(num_periods-1) to be as close as possible
+ * to latency*rate for both playback and capture.
+ *
+ * This method will determine suitable period sizes for capture and playback handles, and report the maximum number of
+ * frames per host buffer. The latter is relevant, in case we should be so unfortunate that the period size differs
+ * between capture and playback. If this should happen, the stream's hostBufferSizeMode attribute will be set to
+ * paUtilBoundedHostBufferSize, because the best we can do is limit the size of individual host buffers to the upper
+ * bound. The size of host buffers scheduled for processing should only matter if the user has specified a buffer size,
+ * but when he/she does we must strive for an optimal configuration. By default we'll opt for a fixed host buffer size,
+ * which should be fine if the period size is the same for capture and playback. In general, if there is a specified user
+ * buffer size, this method tries it best to determine a period size which is a multiple of the user buffer size.
+ *
+ * The framesPerBuffer attributes of the individual capture and playback components of the stream are set to corresponding
+ * values determined here. Since these should be reported as 
+ *
+ * This is one of those blocks of code that will just take a lot of
+ * refinement to be any good.
+ *
+ * In the full-duplex case it is possible that the routine was unable
+ * to find a number of frames per buffer acceptable to both devices
+ * TODO: Implement an algorithm to find the value closest to acceptance
+ * by both devices, to minimize difference between period sizes?
+ *
+ * @param determinedFramesPerHostBuffer: The determined host buffer size.
+ */
+static PaError PaAlsaStream_DetermineFramesPerBuffer( PaAlsaStream* self, double sampleRate, const PaStreamParameters* inputParameters,
+        const PaStreamParameters* outputParameters, unsigned long framesPerUserBuffer, snd_pcm_hw_params_t* hwParamsCapture,
+        snd_pcm_hw_params_t* hwParamsPlayback, PaUtilHostBufferSizeMode* hostBufferSizeMode )
+{
+    PaError result = paNoError;
+    unsigned long framesPerHostBuffer = 0;
+    int dir = 0;
+    int accurate = 1;
+
+    if( self->capture.pcm && self->playback.pcm )
+    {
+        if( framesPerUserBuffer == paFramesPerBufferUnspecified )
+        {
+            snd_pcm_uframes_t desiredLatency, e, minPeriodSize, maxPeriodSize, optimalPeriodSize, periodSize,
+                              minCapture, minPlayback, maxCapture, maxPlayback;
+
+            /* Come up with a common desired latency */
+
+            dir = 0;
+            ENSURE_( snd_pcm_hw_params_get_period_size_min( hwParamsCapture, &minCapture, &dir ), paUnanticipatedHostError );
+            dir = 0;
+            ENSURE_( snd_pcm_hw_params_get_period_size_min( hwParamsPlayback, &minPlayback, &dir ), paUnanticipatedHostError );
+            dir = 0;
+            ENSURE_( snd_pcm_hw_params_get_period_size_max( hwParamsCapture, &maxCapture, &dir ), paUnanticipatedHostError );
+            dir = 0;
+            ENSURE_( snd_pcm_hw_params_get_period_size_max( hwParamsPlayback, &maxPlayback, &dir ), paUnanticipatedHostError );
+            minPeriodSize = PA_MAX( minPlayback, minCapture );
+            maxPeriodSize = PA_MIN( maxPlayback, maxCapture );
+            PA_UNLESS( minPeriodSize <= maxPeriodSize, paBadIODeviceCombination );
+
+            desiredLatency = (snd_pcm_uframes_t)(PA_MIN( outputParameters->suggestedLatency, inputParameters->suggestedLatency )
+                    * sampleRate);
+            /* Clamp desiredLatency */
+            {
+                snd_pcm_uframes_t maxBufferSize;
+                snd_pcm_uframes_t maxBufferSizeCapture, maxBufferSizePlayback;
+                ENSURE_( snd_pcm_hw_params_get_buffer_size_max( hwParamsCapture, &maxBufferSizeCapture ), paUnanticipatedHostError );
+                ENSURE_( snd_pcm_hw_params_get_buffer_size_max( hwParamsPlayback, &maxBufferSizePlayback ), paUnanticipatedHostError );
+                maxBufferSize = PA_MIN( maxBufferSizeCapture, maxBufferSizePlayback );
+
+                desiredLatency = PA_MIN( desiredLatency, maxBufferSize );
+            }
+
+            /* Find the closest power of 2 */
+            e = ilogb( minPeriodSize );
+            if( minPeriodSize & (minPeriodSize - 1) )
+                e += 1;
+            periodSize = (snd_pcm_uframes_t)pow( 2, e );
+
+            while( periodSize <= maxPeriodSize )
+            {
+                if( snd_pcm_hw_params_test_period_size( self->playback.pcm, hwParamsPlayback, periodSize, 0 ) >= 0 &&
+                        snd_pcm_hw_params_test_period_size( self->capture.pcm, hwParamsCapture, periodSize, 0 ) >= 0 )
+                    break;  /* Ok! */
+
+                periodSize *= 2;
+            }
+
+            /* 4 periods considered optimal */
+            optimalPeriodSize = PA_MAX( desiredLatency / 4, minPeriodSize );
+            optimalPeriodSize = PA_MIN( optimalPeriodSize, maxPeriodSize );
+
+            /* Find the closest power of 2 */
+            e = ilogb( optimalPeriodSize );
+            if( optimalPeriodSize & (optimalPeriodSize - 1) )
+                e += 1;
+            optimalPeriodSize = (snd_pcm_uframes_t)pow( 2, e );
+
+            while( optimalPeriodSize >= periodSize )
+            {
+                if( snd_pcm_hw_params_test_period_size( self->capture.pcm, hwParamsCapture, optimalPeriodSize, 0 ) < 0 )
+                    continue;
+                if( snd_pcm_hw_params_test_period_size( self->playback.pcm, hwParamsPlayback, optimalPeriodSize, 0 ) >= 0 )
+                    break;
+                optimalPeriodSize /= 2;
+            }
+            if( optimalPeriodSize > periodSize )
+                periodSize = optimalPeriodSize;
+
+            if( periodSize <= maxPeriodSize )
+            {
+                /* Looks good, the periodSize _should_ be acceptable by both devices */
+                ENSURE_( snd_pcm_hw_params_set_period_size( self->capture.pcm, hwParamsCapture, periodSize, 0 ),
+                        paUnanticipatedHostError );
+                ENSURE_( snd_pcm_hw_params_set_period_size( self->playback.pcm, hwParamsPlayback, periodSize, 0 ),
+                        paUnanticipatedHostError );
+                self->capture.framesPerBuffer = self->playback.framesPerBuffer = periodSize;
+                framesPerHostBuffer = periodSize;
+            }
+            else
+            {
+                /* Unable to find a common period size, oh well */
+                optimalPeriodSize = PA_MAX( desiredLatency / 4, minPeriodSize );
+                optimalPeriodSize = PA_MIN( optimalPeriodSize, maxPeriodSize );
+
+                self->capture.framesPerBuffer = optimalPeriodSize;
+                dir = 0;
+                ENSURE_( snd_pcm_hw_params_set_period_size_near( self->capture.pcm, hwParamsCapture, &self->capture.framesPerBuffer, &dir ),
+                        paUnanticipatedHostError );
+                self->playback.framesPerBuffer = optimalPeriodSize;
+                dir = 0;
+                ENSURE_( snd_pcm_hw_params_set_period_size_near( self->playback.pcm, hwParamsPlayback, &self->playback.framesPerBuffer, &dir ),
+                        paUnanticipatedHostError );
+                framesPerHostBuffer = PA_MAX( self->capture.framesPerBuffer, self->playback.framesPerBuffer );
+                *hostBufferSizeMode = paUtilBoundedHostBufferSize;
+            }
+        }
+        else
+        {
+            /* We choose the simple route and determine a suitable number of frames per buffer for one component of
+             * the stream, then we hope that this will work for the other component too (it should!).
+             */
+
+            unsigned maxPeriods = 0;
+            PaAlsaStreamComponent* first = &self->capture, * second = &self->playback;
+            const PaStreamParameters* firstStreamParams = inputParameters;
+            snd_pcm_hw_params_t* firstHwParams = hwParamsCapture, * secondHwParams = hwParamsPlayback;
+
+            dir = 0;
+            ENSURE_( snd_pcm_hw_params_get_periods_max( hwParamsPlayback, &maxPeriods, &dir ), paUnanticipatedHostError );
+            if( maxPeriods < 4 )
+            {
+                /* The playback component is trickier to get right, try that first */
+                first = &self->playback;
+                second = &self->capture;
+                firstStreamParams = outputParameters;
+                firstHwParams = hwParamsPlayback;
+                secondHwParams = hwParamsCapture;
+            }
+
+            PA_ENSURE( PaAlsaStreamComponent_DetermineFramesPerBuffer( first, firstStreamParams, framesPerUserBuffer,
+                        sampleRate, firstHwParams, &accurate ) );
+
+            second->framesPerBuffer = first->framesPerBuffer;
+            dir = 0;
+            ENSURE_( snd_pcm_hw_params_set_period_size_near( second->pcm, secondHwParams, &second->framesPerBuffer, &dir ),
+                    paUnanticipatedHostError );
+            if( self->capture.framesPerBuffer == self->playback.framesPerBuffer )
+            {
+                framesPerHostBuffer = self->capture.framesPerBuffer;
+            }
+            else
+            {
+                framesPerHostBuffer = PA_MAX( self->capture.framesPerBuffer, self->playback.framesPerBuffer );
+                *hostBufferSizeMode = paUtilBoundedHostBufferSize;
+            }
+        }
+    }
+    else    /* half-duplex is a slightly simpler case */
+    {
+        if( self->capture.pcm )
+        {
+            PA_ENSURE( PaAlsaStreamComponent_DetermineFramesPerBuffer( &self->capture, inputParameters, framesPerUserBuffer,
+                        sampleRate, hwParamsCapture, &accurate) );
+            framesPerHostBuffer = self->capture.framesPerBuffer;
+        }
+        else
+        {
+            assert( self->playback.pcm );
+            PA_ENSURE( PaAlsaStreamComponent_DetermineFramesPerBuffer( &self->playback, outputParameters, framesPerUserBuffer,
+                        sampleRate, hwParamsPlayback, &accurate ) );
+            framesPerHostBuffer = self->playback.framesPerBuffer;
+        }
+    }
+
+    PA_UNLESS( framesPerHostBuffer != 0, paInternalError );
+    self->maxFramesPerHostBuffer = framesPerHostBuffer;
+
+    if( !accurate )
+    {
+        /* Don't know the exact size per host buffer */
+        *hostBufferSizeMode = paUtilBoundedHostBufferSize;
+        /* Raise upper bound */
+        ++self->maxFramesPerHostBuffer;
+    }
+
+error:
+    return result;
+}
+
+/** Set up ALSA stream parameters.
+ *
+ */
+static PaError PaAlsaStream_Configure( PaAlsaStream *self, const PaStreamParameters *inParams, const PaStreamParameters*
+        outParams, double sampleRate, unsigned long framesPerUserBuffer, double* inputLatency, double* outputLatency,
+        PaUtilHostBufferSizeMode* hostBufferSizeMode )
+{
+    PaError result = paNoError;
+    double realSr = sampleRate;
+    snd_pcm_hw_params_t* hwParamsCapture, * hwParamsPlayback;
+
+    snd_pcm_hw_params_alloca( &hwParamsCapture );
+    snd_pcm_hw_params_alloca( &hwParamsPlayback );
+
+    if( self->capture.pcm )
+        PA_ENSURE( PaAlsaStreamComponent_InitialConfigure( &self->capture, inParams, self->primeBuffers, hwParamsCapture,
+                    &realSr ) );
+    if( self->playback.pcm )
+        PA_ENSURE( PaAlsaStreamComponent_InitialConfigure( &self->playback, outParams, self->primeBuffers, hwParamsPlayback,
+                    &realSr ) );
+
+    PA_ENSURE( PaAlsaStream_DetermineFramesPerBuffer( self, realSr, inParams, outParams, framesPerUserBuffer,
+                hwParamsCapture, hwParamsPlayback, hostBufferSizeMode ) );
+
+    if( self->capture.pcm )
+    {
+        assert( self->capture.framesPerBuffer != 0 );
+        PA_ENSURE( PaAlsaStreamComponent_FinishConfigure( &self->capture, hwParamsCapture, inParams, self->primeBuffers, realSr,
+                    inputLatency ) );
+        PA_DEBUG(( "%s: Capture period size: %lu, latency: %f\n", __FUNCTION__, self->capture.framesPerBuffer, *inputLatency ));
+    }
+    if( self->playback.pcm )
+    {
+        assert( self->playback.framesPerBuffer != 0 );
+        PA_ENSURE( PaAlsaStreamComponent_FinishConfigure( &self->playback, hwParamsPlayback, outParams, self->primeBuffers, realSr,
+                    outputLatency ) );
+        PA_DEBUG(( "%s: Playback period size: %lu, latency: %f\n", __FUNCTION__, self->playback.framesPerBuffer, *outputLatency ));
+    }
+
+    /* Should be exact now */
+    self->streamRepresentation.streamInfo.sampleRate = realSr;
+
+    /* this will cause the two streams to automatically start/stop/prepare in sync.
+     * We only need to execute these operations on one of the pair.
+     * A: We don't want to do this on a blocking stream.
+     */
+    if( self->callbackMode && self->capture.pcm && self->playback.pcm )
+    {
+        int err = snd_pcm_link( self->capture.pcm, self->playback.pcm );
+        if( err == 0 )
+            self->pcmsSynced = 1;
+        else
+            PA_DEBUG(( "%s: Unable to sync pcms: %s\n", __FUNCTION__, snd_strerror( err ) ));
+    }
+
+    {
+        unsigned long minFramesPerHostBuffer = PA_MIN( self->capture.pcm ? self->capture.framesPerBuffer : ULONG_MAX,
+            self->playback.pcm ? self->playback.framesPerBuffer : ULONG_MAX );
+        self->pollTimeout = CalculatePollTimeout( self, minFramesPerHostBuffer );    /* Period in msecs, rounded up */
+
+        /* Time before watchdog unthrottles realtime thread == 1/4 of period time in msecs */
+        /* self->threading.throttledSleepTime = (unsigned long) (minFramesPerHostBuffer / sampleRate / 4 * 1000); */
+    }
+
+    if( self->callbackMode )
+    {
+        /* If the user expects a certain number of frames per callback we will either have to rely on block adaption
+         * (framesPerHostBuffer is not an integer multiple of framesPerBuffer) or we can simply align the number
+         * of host buffer frames with what the user specified */
+        if( self->framesPerUserBuffer != paFramesPerBufferUnspecified )
+        {
+            /* self->alignFrames = 1; */
+
+            /* Unless the ratio between number of host and user buffer frames is an integer we will have to rely
+             * on block adaption */
+        /*
+            if( framesPerHostBuffer % framesPerBuffer != 0 || (self->capture.pcm && self->playback.pcm &&
+                        self->capture.framesPerBuffer != self->playback.framesPerBuffer) )
+                self->useBlockAdaption = 1;
+            else
+                self->alignFrames = 1;
+        */
+        }
+    }
+
+error:
+    return result;
+}
+
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+                           PaStream** s,
+                           const PaStreamParameters *inputParameters,
+                           const PaStreamParameters *outputParameters,
+                           double sampleRate,
+                           unsigned long framesPerBuffer,
+                           PaStreamFlags streamFlags,
+                           PaStreamCallback* callback,
+                           void *userData )
+{
+    PaError result = paNoError;
+    PaAlsaHostApiRepresentation *alsaHostApi = (PaAlsaHostApiRepresentation*)hostApi;
+    PaAlsaStream *stream = NULL;
+    PaSampleFormat hostInputSampleFormat = 0, hostOutputSampleFormat = 0;
+    PaSampleFormat inputSampleFormat = 0, outputSampleFormat = 0;
+    int numInputChannels = 0, numOutputChannels = 0;
+    PaTime inputLatency, outputLatency;
+    /* Operate with fixed host buffer size by default, since other modes will invariably lead to block adaption */
+    /* XXX: Use Bounded by default? Output tends to get stuttery with Fixed ... */
+    PaUtilHostBufferSizeMode hostBufferSizeMode = paUtilFixedHostBufferSize;
+
+    if( (streamFlags & paPlatformSpecificFlags) != 0 )
+        return paInvalidFlag;
+
+    if( inputParameters )
+    {
+        PA_ENSURE( ValidateParameters( inputParameters, hostApi, StreamDirection_In ) );
+
+        numInputChannels = inputParameters->channelCount;
+        inputSampleFormat = inputParameters->sampleFormat;
+    }
+    if( outputParameters )
+    {
+        PA_ENSURE( ValidateParameters( outputParameters, hostApi, StreamDirection_Out ) );
+
+        numOutputChannels = outputParameters->channelCount;
+        outputSampleFormat = outputParameters->sampleFormat;
+    }
+
+    /* XXX: Why do we support this anyway? */
+    if( framesPerBuffer == paFramesPerBufferUnspecified && getenv( "PA_ALSA_PERIODSIZE" ) != NULL )
+    {
+        PA_DEBUG(( "%s: Getting framesPerBuffer from environment\n", __FUNCTION__ ));
+        framesPerBuffer = atoi( getenv("PA_ALSA_PERIODSIZE") );
+    }
+
+    PA_UNLESS( stream = (PaAlsaStream*)PaUtil_AllocateMemory( sizeof(PaAlsaStream) ), paInsufficientMemory );
+    PA_ENSURE( PaAlsaStream_Initialize( stream, alsaHostApi, inputParameters, outputParameters, sampleRate,
+                framesPerBuffer, callback, streamFlags, userData ) );
+
+    PA_ENSURE( PaAlsaStream_Configure( stream, inputParameters, outputParameters, sampleRate, framesPerBuffer,
+                &inputLatency, &outputLatency, &hostBufferSizeMode ) );
+    hostInputSampleFormat = stream->capture.hostSampleFormat;
+    hostOutputSampleFormat = stream->playback.hostSampleFormat;
+
+    PA_ENSURE( PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
+                    numInputChannels, inputSampleFormat, hostInputSampleFormat,
+                    numOutputChannels, outputSampleFormat, hostOutputSampleFormat,
+                    sampleRate, streamFlags, framesPerBuffer, stream->maxFramesPerHostBuffer,
+                    hostBufferSizeMode, callback, userData ) );
+
+    /* Ok, buffer processor is initialized, now we can deduce it's latency */
+    if( numInputChannels > 0 )
+        stream->streamRepresentation.streamInfo.inputLatency = inputLatency + PaUtil_GetBufferProcessorInputLatency(
+                &stream->bufferProcessor );
+    if( numOutputChannels > 0 )
+        stream->streamRepresentation.streamInfo.outputLatency = outputLatency + PaUtil_GetBufferProcessorOutputLatency(
+                &stream->bufferProcessor );
+
+    *s = (PaStream*)stream;
+
+    return result;
+
+error:
+    if( stream )
+    {
+        PA_DEBUG(( "%s: Stream in error, terminating\n", __FUNCTION__ ));
+        PaAlsaStream_Terminate( stream );
+    }
+
+    return result;
+}
+
+static PaError CloseStream( PaStream* s )
+{
+    PaError result = paNoError;
+    PaAlsaStream *stream = (PaAlsaStream*)s;
+
+    PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+    PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
+
+    PaAlsaStream_Terminate( stream );
+
+    return result;
+}
+
+static void SilenceBuffer( PaAlsaStream *stream )
+{
+    const snd_pcm_channel_area_t *areas;
+    snd_pcm_uframes_t frames = (snd_pcm_uframes_t)snd_pcm_avail_update( stream->playback.pcm ), offset;
+
+    snd_pcm_mmap_begin( stream->playback.pcm, &areas, &offset, &frames );
+    snd_pcm_areas_silence( areas, offset, stream->playback.numHostChannels, frames, stream->playback.nativeFormat );
+    snd_pcm_mmap_commit( stream->playback.pcm, offset, frames );
+}
+
+/** Start/prepare pcm(s) for streaming.
+ *
+ * Depending on wether the stream is in callback or blocking mode, we will respectively start or simply
+ * prepare the playback pcm. If the buffer has _not_ been primed, we will in callback mode prepare and
+ * silence the buffer before starting playback. In blocking mode we simply prepare, as the playback will
+ * be started automatically as the user writes to output. 
+ *
+ * The capture pcm, however, will simply be prepared and started.
+ */
+static PaError AlsaStart( PaAlsaStream *stream, int priming )
+{
+    PaError result = paNoError;
+
+    if( stream->playback.pcm )
+    {
+        if( stream->callbackMode )
+        {
+            if( !priming )
+            {
+                /* Buffer isn't primed, so prepare and silence */
+                ENSURE_( snd_pcm_prepare( stream->playback.pcm ), paUnanticipatedHostError );
+                SilenceBuffer( stream );
+            }
+            ENSURE_( snd_pcm_start( stream->playback.pcm ), paUnanticipatedHostError );
+        }
+        else
+            ENSURE_( snd_pcm_prepare( stream->playback.pcm ), paUnanticipatedHostError );
+    }
+    if( stream->capture.pcm && !stream->pcmsSynced )
+    {
+        ENSURE_( snd_pcm_prepare( stream->capture.pcm ), paUnanticipatedHostError );
+        /* For a blocking stream we want to start capture as well, since nothing will happen otherwise */
+        ENSURE_( snd_pcm_start( stream->capture.pcm ), paUnanticipatedHostError );
+    }
+
+end:
+    return result;
+error:
+    goto end;
+}
+
+/** Utility function for determining if pcms are in running state.
+ *
+ */
+#if 0
+static int IsRunning( PaAlsaStream *stream )
+{
+    int result = 0;
+
+    PA_ENSURE( PaUnixMutex_Lock( &stream->stateMtx ) );
+    if( stream->capture.pcm )
+    {
+        snd_pcm_state_t capture_state = snd_pcm_state( stream->capture.pcm );
+
+        if( capture_state == SND_PCM_STATE_RUNNING || capture_state == SND_PCM_STATE_XRUN
+                || capture_state == SND_PCM_STATE_DRAINING )
+        {
+            result = 1;
+            goto end;
+        }
+    }
+
+    if( stream->playback.pcm )
+    {
+        snd_pcm_state_t playback_state = snd_pcm_state( stream->playback.pcm );
+
+        if( playback_state == SND_PCM_STATE_RUNNING || playback_state == SND_PCM_STATE_XRUN
+                || playback_state == SND_PCM_STATE_DRAINING )
+        {
+            result = 1;
+            goto end;
+        }
+    }
+
+end:
+    ASSERT_CALL_( PaUnixMutex_Unlock( &stream->stateMtx ), paNoError );
+    return result;
+error:
+    goto error;
+}
+#endif
+
+static PaError StartStream( PaStream *s )
+{
+    PaError result = paNoError;
+    PaAlsaStream* stream = (PaAlsaStream*)s;
+    int streamStarted = 0;  /* So we can know wether we need to take the stream down */
+
+    /* Ready the processor */
+    PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
+
+    /* Set now, so we can test for activity further down */
+    stream->isActive = 1;
+
+    if( stream->callbackMode )
+    {
+        PA_ENSURE( PaUnixThread_New( &stream->thread, &CallbackThreadFunc, stream, 1., 0 ) );
+    }
+    else
+    {
+        PA_ENSURE( AlsaStart( stream, 0 ) );
+        streamStarted = 1;
+    }
+
+end:
+    return result;
+error:
+    if( streamStarted )
+    {
+        AbortStream( stream );
+    }
+    stream->isActive = 0;
+    
+    goto end;
+}
+
+/** Stop PCM handle, either softly or abruptly.
+ */
+static PaError AlsaStop( PaAlsaStream *stream, int abort )
+{
+    PaError result = paNoError;
+
+    if( abort )
+    {
+        if( stream->playback.pcm )
+        {
+            ENSURE_( snd_pcm_drop( stream->playback.pcm ), paUnanticipatedHostError );
+        }
+        if( stream->capture.pcm && !stream->pcmsSynced )
+        {
+            ENSURE_( snd_pcm_drop( stream->capture.pcm ), paUnanticipatedHostError );
+        }
+
+        PA_DEBUG(( "%s: Dropped frames\n", __FUNCTION__ ));
+    }
+    else
+    {
+        if( stream->playback.pcm )
+        {
+            ENSURE_( snd_pcm_nonblock( stream->playback.pcm, 0 ), paUnanticipatedHostError );
+            if( snd_pcm_drain( stream->playback.pcm ) < 0 )
+            {
+                PA_DEBUG(( "%s: Draining playback handle failed!\n", __FUNCTION__ ));
+            }
+        }
+        if( stream->capture.pcm && !stream->pcmsSynced )
+        {
+            /* We don't need to retrieve any remaining frames */
+            if( snd_pcm_drop( stream->capture.pcm ) < 0 )
+            {
+                PA_DEBUG(( "%s: Draining capture handle failed!\n", __FUNCTION__ ));
+            }
+        }
+    }
+
+end:
+    return result;
+error:
+    goto end;
+}
+
+/** Stop or abort stream.
+ *
+ * If a stream is in callback mode we will have to inspect wether the background thread has
+ * finished, or we will have to take it out. In either case we join the thread before
+ * returning. In blocking mode, we simply tell ALSA to stop abruptly (abort) or finish
+ * buffers (drain)
+ *
+ * Stream will be considered inactive (!PaAlsaStream::isActive) after a call to this function
+ */
+static PaError RealStop( PaAlsaStream *stream, int abort )
+{
+    PaError result = paNoError;
+
+    /* First deal with the callback thread, cancelling and/or joining
+     * it if necessary
+     */
+    if( stream->callbackMode )
+    {
+        PaError threadRes;
+        stream->callbackAbort = abort;
+
+        if( !abort )
+        {
+            PA_DEBUG(( "Stopping callback\n" ));
+        }
+        PA_ENSURE( PaUnixThread_Terminate( &stream->thread, !abort, &threadRes ) );
+        if( threadRes != paNoError )
+        {
+            PA_DEBUG(( "Callback thread returned: %d\n", threadRes ));
+        }
+#if 0
+        if( watchdogRes != paNoError )
+            PA_DEBUG(( "Watchdog thread returned: %d\n", watchdogRes ));
+#endif
+
+        stream->callback_finished = 0;
+    }
+    else
+    {
+        PA_ENSURE( AlsaStop( stream, abort ) );
+    }
+
+    stream->isActive = 0;
+
+end:
+    return result;
+
+error:
+    goto end;
+}
+
+static PaError StopStream( PaStream *s )
+{
+    return RealStop( (PaAlsaStream *) s, 0 );
+}
+
+static PaError AbortStream( PaStream *s )
+{
+    return RealStop( (PaAlsaStream * ) s, 1 );
+}
+
+/** The stream is considered stopped before StartStream, or AFTER a call to Abort/StopStream (callback
+ * returning !paContinue is not considered)
+ *
+ */
+static PaError IsStreamStopped( PaStream *s )
+{
+    PaAlsaStream *stream = (PaAlsaStream *)s;
+
+    /* callback_finished indicates we need to join callback thread (ie. in Abort/StopStream) */
+    return !IsStreamActive( s ) && !stream->callback_finished;
+}
+
+static PaError IsStreamActive( PaStream *s )
+{
+    PaAlsaStream *stream = (PaAlsaStream*)s;
+    return stream->isActive;
+}
+
+static PaTime GetStreamTime( PaStream *s )
+{
+    PaAlsaStream *stream = (PaAlsaStream*)s;
+
+    snd_timestamp_t timestamp;
+    snd_pcm_status_t* status;
+    snd_pcm_status_alloca( &status );
+
+    /* TODO: what if we have both?  does it really matter? */
+
+    /* TODO: if running in callback mode, this will mean
+     * libasound routines are being called from multiple threads.
+     * need to verify that libasound is thread-safe. */
+
+    if( stream->capture.pcm )
+    {
+        snd_pcm_status( stream->capture.pcm, status );
+    }
+    else if( stream->playback.pcm )
+    {
+        snd_pcm_status( stream->playback.pcm, status );
+    }
+
+    snd_pcm_status_get_tstamp( status, &timestamp );
+    return timestamp.tv_sec + (PaTime)timestamp.tv_usec / 1e6;
+}
+
+static double GetStreamCpuLoad( PaStream* s )
+{
+    PaAlsaStream *stream = (PaAlsaStream*)s;
+
+    return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
+}
+
+static int SetApproximateSampleRate( snd_pcm_t *pcm, snd_pcm_hw_params_t *hwParams, double sampleRate )
+{
+    unsigned long approx = (unsigned long) sampleRate;
+    int dir = 0;
+    double fraction = sampleRate - approx;
+
+    assert( pcm && hwParams );
+
+    if( fraction > 0.0 )
+    {
+        if( fraction > 0.5 )
+        {
+            ++approx;
+            dir = -1;
+        }
+        else
+            dir = 1;
+    }
+
+    return snd_pcm_hw_params_set_rate( pcm, hwParams, approx, dir );
+}
+
+/* Return exact sample rate in param sampleRate */
+static int GetExactSampleRate( snd_pcm_hw_params_t *hwParams, double *sampleRate )
+{
+    unsigned int num, den;
+    int err; 
+
+    assert( hwParams );
+
+    err = snd_pcm_hw_params_get_rate_numden( hwParams, &num, &den );
+    *sampleRate = (double) num / den;
+
+    return err;
+}
+
+/* Utility functions for blocking/callback interfaces */
+
+/* Atomic restart of stream (we don't want the intermediate state visible) */
+static PaError AlsaRestart( PaAlsaStream *stream )
+{
+    PaError result = paNoError;
+
+    PA_ENSURE( PaUnixMutex_Lock( &stream->stateMtx ) );
+    PA_ENSURE( AlsaStop( stream, 0 ) );
+    PA_ENSURE( AlsaStart( stream, 0 ) );
+
+    PA_DEBUG(( "%s: Restarted audio\n", __FUNCTION__ ));
+
+error:
+    PA_ENSURE( PaUnixMutex_Unlock( &stream->stateMtx ) );
+
+    return result;
+}
+
+/** Recover from xrun state.
+ *
+ */
+static PaError PaAlsaStream_HandleXrun( PaAlsaStream *self )
+{
+    PaError result = paNoError;
+    snd_pcm_status_t *st;
+    PaTime now = PaUtil_GetTime();
+    snd_timestamp_t t;
+
+    snd_pcm_status_alloca( &st );
+
+    if( self->playback.pcm )
+    {
+        snd_pcm_status( self->playback.pcm, st );
+        if( snd_pcm_status_get_state( st ) == SND_PCM_STATE_XRUN )
+        {
+            snd_pcm_status_get_trigger_tstamp( st, &t );
+            self->underrun = now * 1000 - ((PaTime) t.tv_sec * 1000 + (PaTime) t.tv_usec / 1000);
+        }
+    }
+    if( self->capture.pcm )
+    {
+        snd_pcm_status( self->capture.pcm, st );
+        if( snd_pcm_status_get_state( st ) == SND_PCM_STATE_XRUN )
+        {
+            snd_pcm_status_get_trigger_tstamp( st, &t );
+            self->overrun = now * 1000 - ((PaTime) t.tv_sec * 1000 + (PaTime) t.tv_usec / 1000);
+        }
+    }
+
+    PA_ENSURE( AlsaRestart( self ) );
+
+end:
+    return result;
+error:
+    goto end;
+}
+
+/** Decide if we should continue polling for specified direction, eventually adjust the poll timeout.
+ * 
+ */
+static PaError ContinuePoll( const PaAlsaStream *stream, StreamDirection streamDir, int *pollTimeout, int *continuePoll )
+{
+    PaError result = paNoError;
+    snd_pcm_sframes_t delay, margin;
+    int err;
+    const PaAlsaStreamComponent *component = NULL, *otherComponent = NULL;
+
+    *continuePoll = 1;
+
+    if( StreamDirection_In == streamDir )
+    {
+        component = &stream->capture;
+        otherComponent = &stream->playback;
+    }
+    else
+    {
+        component = &stream->playback;
+        otherComponent = &stream->capture;
+    }
+
+    /* ALSA docs say that negative delay should indicate xrun, but in my experience snd_pcm_delay returns -EPIPE */
+    if( (err = snd_pcm_delay( otherComponent->pcm, &delay )) < 0 )
+    {
+        if( err == -EPIPE )
+        {
+            /* Xrun */
+            *continuePoll = 0;
+            goto error;
+        }
+
+        ENSURE_( err, paUnanticipatedHostError );
+    }
+
+    if( StreamDirection_Out == streamDir )
+    {
+        /* Number of eligible frames before capture overrun */
+        delay = otherComponent->bufferSize - delay;
+    }
+    margin = delay - otherComponent->framesPerBuffer / 2;
+
+    if( margin < 0 )
+    {
+        PA_DEBUG(( "%s: Stopping poll for %s\n", __FUNCTION__, StreamDirection_In == streamDir ? "capture" : "playback" ));
+        *continuePoll = 0;
+    }
+    else if( margin < otherComponent->framesPerBuffer )
+    {
+        *pollTimeout = CalculatePollTimeout( stream, margin );
+        PA_DEBUG(( "%s: Trying to poll again for %s frames, pollTimeout: %d\n",
+                    __FUNCTION__, StreamDirection_In == streamDir ? "capture" : "playback", *pollTimeout ));
+    }
+
+error:
+    return result;
+}
+
+/* Callback interface */
+
+static void OnExit( void *data )
+{
+    PaAlsaStream *stream = (PaAlsaStream *) data;
+
+    assert( data );
+
+    PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer );
+
+    stream->callback_finished = 1;  /* Let the outside world know stream was stopped in callback */
+    PA_DEBUG(( "%s: Stopping ALSA handles\n", __FUNCTION__ ));
+    AlsaStop( stream, stream->callbackAbort );
+    
+    PA_DEBUG(( "%s: Stoppage\n", __FUNCTION__ ));
+
+    /* Eventually notify user all buffers have played */
+    if( stream->streamRepresentation.streamFinishedCallback )
+    {
+        stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
+    }
+    stream->isActive = 0;
+}
+
+static void CalculateTimeInfo( PaAlsaStream *stream, PaStreamCallbackTimeInfo *timeInfo )
+{
+    snd_pcm_status_t *capture_status, *playback_status;
+    snd_timestamp_t capture_timestamp, playback_timestamp;
+    PaTime capture_time = 0., playback_time = 0.;
+
+    snd_pcm_status_alloca( &capture_status );
+    snd_pcm_status_alloca( &playback_status );
+
+    if( stream->capture.pcm )
+    {
+        snd_pcm_sframes_t capture_delay;
+
+        snd_pcm_status( stream->capture.pcm, capture_status );
+        snd_pcm_status_get_tstamp( capture_status, &capture_timestamp );
+
+        capture_time = capture_timestamp.tv_sec +
+            ((PaTime)capture_timestamp.tv_usec / 1000000.0);
+        timeInfo->currentTime = capture_time;
+
+        capture_delay = snd_pcm_status_get_delay( capture_status );
+        timeInfo->inputBufferAdcTime = timeInfo->currentTime -
+            (PaTime)capture_delay / stream->streamRepresentation.streamInfo.sampleRate;
+    }
+    if( stream->playback.pcm )
+    {
+        snd_pcm_sframes_t playback_delay;
+
+        snd_pcm_status( stream->playback.pcm, playback_status );
+        snd_pcm_status_get_tstamp( playback_status, &playback_timestamp );
+
+        playback_time = playback_timestamp.tv_sec +
+            ((PaTime)playback_timestamp.tv_usec / 1000000.0);
+
+        if( stream->capture.pcm ) /* Full duplex */
+        {
+            /* Hmm, we have both a playback and a capture timestamp.
+             * Hopefully they are the same... */
+            if( fabs( capture_time - playback_time ) > 0.01 )
+                PA_DEBUG(("Capture time and playback time differ by %f\n", fabs(capture_time-playback_time)));
+        }
+        else
+            timeInfo->currentTime = playback_time;
+
+        playback_delay = snd_pcm_status_get_delay( playback_status );
+        timeInfo->outputBufferDacTime = timeInfo->currentTime +
+            (PaTime)playback_delay / stream->streamRepresentation.streamInfo.sampleRate;
+    }
+}
+
+/** Called after buffer processing is finished.
+ *
+ * A number of mmapped frames is committed, it is possible that an xrun has occurred in the meantime.
+ *
+ * @param numFrames The number of frames that has been processed
+ * @param xrun Return whether an xrun has occurred
+ */
+static PaError PaAlsaStreamComponent_EndProcessing( PaAlsaStreamComponent *self, unsigned long numFrames, int *xrun )
+{
+    PaError result = paNoError;
+    int res;
+
+    /* @concern FullDuplex It is possible that only one direction is marked ready after polling, and processed
+     * afterwards
+     */
+    if( !self->ready )
+        goto end;
+
+    res = snd_pcm_mmap_commit( self->pcm, self->offset, numFrames );
+    if( res == -EPIPE || res == -ESTRPIPE )
+    {
+        *xrun = 1;
+    }
+    else
+    {
+        ENSURE_( res, paUnanticipatedHostError );
+    }
+
+end:
+error:
+    return result;
+}
+
+/* Extract buffer from channel area */
+static unsigned char *ExtractAddress( const snd_pcm_channel_area_t *area, snd_pcm_uframes_t offset )
+{
+    return (unsigned char *) area->addr + (area->first + offset * area->step) / 8;
+}
+
+/** Do necessary adaption between user and host channels.
+ *
+    @concern ChannelAdaption Adapting between user and host channels can involve silencing unused channels and
+    duplicating mono information if host outputs come in pairs.
+ */
+static PaError PaAlsaStreamComponent_DoChannelAdaption( PaAlsaStreamComponent *self, PaUtilBufferProcessor *bp, int numFrames )
+{
+    PaError result = paNoError;
+    unsigned char *p;
+    int i;
+    int unusedChans = self->numHostChannels - self->numUserChannels;
+    unsigned char *src, *dst;
+    int convertMono = (self->numHostChannels % 2) == 0 && (self->numUserChannels % 2) != 0;
+
+    assert( StreamDirection_Out == self->streamDir );
+
+    if( self->hostInterleaved )
+    {
+        int swidth = snd_pcm_format_size( self->nativeFormat, 1 );
+        unsigned char *buffer = ExtractAddress( self->channelAreas, self->offset );
+
+        /* Start after the last user channel */
+        p = buffer + self->numUserChannels * swidth;
+
+        if( convertMono )
+        {
+            /* Convert the last user channel into stereo pair */
+            src = buffer + (self->numUserChannels - 1) * swidth;
+            for( i = 0; i < numFrames; ++i )
+            {
+                dst = src + swidth;
+                memcpy( dst, src, swidth );
+                src += self->numHostChannels * swidth;
+            }
+
+            /* Don't touch the channel we just wrote to */
+            p += swidth;
+            --unusedChans;
+        }
+
+        if( unusedChans > 0 )
+        {
+            /* Silence unused output channels */
+            for( i = 0; i < numFrames; ++i )
+            {
+                memset( p, 0, swidth * unusedChans );
+                p += self->numHostChannels * swidth;
+            }
+        }
+    }
+    else
+    {
+        /* We extract the last user channel */
+        if( convertMono )
+        {
+            ENSURE_( snd_pcm_area_copy( self->channelAreas + self->numUserChannels, self->offset, self->channelAreas +
+                    (self->numUserChannels - 1), self->offset, numFrames, self->nativeFormat ), paUnanticipatedHostError );
+            --unusedChans;
+        }
+        if( unusedChans > 0 )
+        {
+            snd_pcm_areas_silence( self->channelAreas + (self->numHostChannels - unusedChans), self->offset, unusedChans, numFrames,
+                    self->nativeFormat );
+        }
+    }
+
+error:
+    return result;
+}
+
+static PaError PaAlsaStream_EndProcessing( PaAlsaStream *self, unsigned long numFrames, int *xrunOccurred )
+{
+    PaError result = paNoError;
+    int xrun = 0;
+
+    if( self->capture.pcm )
+    {
+        PA_ENSURE( PaAlsaStreamComponent_EndProcessing( &self->capture, numFrames, &xrun ) );
+    }
+    if( self->playback.pcm )
+    {
+        if( self->playback.numHostChannels > self->playback.numUserChannels )
+        {
+            PA_ENSURE( PaAlsaStreamComponent_DoChannelAdaption( &self->playback, &self->bufferProcessor, numFrames ) );
+        }
+        PA_ENSURE( PaAlsaStreamComponent_EndProcessing( &self->playback, numFrames, &xrun ) );
+    }
+
+error:
+    *xrunOccurred = xrun;
+    return result;
+}
+
+/** Update the number of available frames.
+ *
+ */
+static PaError PaAlsaStreamComponent_GetAvailableFrames( PaAlsaStreamComponent *self, unsigned long *numFrames, int *xrunOccurred )
+{
+    PaError result = paNoError;
+    snd_pcm_sframes_t framesAvail = snd_pcm_avail_update( self->pcm );
+    *xrunOccurred = 0;
+
+    if( -EPIPE == framesAvail )
+    {
+        *xrunOccurred = 1;
+        framesAvail = 0;
+    }
+    else
+    {
+        ENSURE_( framesAvail, paUnanticipatedHostError );
+    }
+
+    *numFrames = framesAvail;
+
+error:
+    return result;
+}
+
+/** Fill in pollfd objects.
+ */
+static PaError PaAlsaStreamComponent_BeginPolling( PaAlsaStreamComponent* self, struct pollfd* pfds )
+{
+    PaError result = paNoError;
+    int ret = snd_pcm_poll_descriptors( self->pcm, pfds, self->nfds );
+    (void)ret;  /* Prevent unused variable warning if asserts are turned off */
+    assert( ret == self->nfds );
+
+    self->ready = 0;
+
+    return result;
+}
+
+/** Examine results from poll().
+ *
+ * @param pfds pollfds to inspect
+ * @param shouldPoll Should we continue to poll
+ * @param xrun Has an xrun occurred
+ */
+static PaError PaAlsaStreamComponent_EndPolling( PaAlsaStreamComponent* self, struct pollfd* pfds, int* shouldPoll, int* xrun )
+{
+    PaError result = paNoError;
+    unsigned short revents;
+
+    ENSURE_( snd_pcm_poll_descriptors_revents( self->pcm, pfds, self->nfds, &revents ), paUnanticipatedHostError );
+    if( revents != 0 )
+    {
+        if( revents & POLLERR )
+        {
+            *xrun = 1;
+        }
+        else
+            self->ready = 1;
+
+        *shouldPoll = 0;
+    }
+
+error:
+    return result;
+}
+
+/** Return the number of available frames for this stream.
+ *
+ * @concern FullDuplex The minimum available for the two directions is calculated, it might be desirable to ignore
+ * one direction however (not marked ready from poll), so this is controlled by queryCapture and queryPlayback.
+ *
+ * @param queryCapture Check available for capture
+ * @param queryPlayback Check available for playback
+ * @param available The returned number of frames
+ * @param xrunOccurred Return whether an xrun has occurred
+ */
+static PaError PaAlsaStream_GetAvailableFrames( PaAlsaStream *self, int queryCapture, int queryPlayback, unsigned long
+        *available, int *xrunOccurred )
+{
+    PaError result = paNoError;
+    unsigned long captureFrames, playbackFrames;
+    *xrunOccurred = 0;
+
+    assert( queryCapture || queryPlayback );
+
+    if( queryCapture )
+    {
+        assert( self->capture.pcm );
+        PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &self->capture, &captureFrames, xrunOccurred ) );
+        if( *xrunOccurred )
+        {
+            goto end;
+        }
+    }
+    if( queryPlayback )
+    {
+        assert( self->playback.pcm );
+        PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &self->playback, &playbackFrames, xrunOccurred ) );
+        if( *xrunOccurred )
+        {
+            goto end;
+        }
+    }
+
+    if( queryCapture && queryPlayback )
+    {
+        *available = PA_MIN( captureFrames, playbackFrames );
+        /*PA_DEBUG(("capture: %lu, playback: %lu, combined: %lu\n", captureFrames, playbackFrames, *available));*/
+    }
+    else if( queryCapture )
+    {
+        *available = captureFrames;
+    }
+    else
+    {
+        *available = playbackFrames;
+    }
+
+end:
+error:
+    return result;
+}
+
+/** Wait for and report available buffer space from ALSA.
+ *
+ * Unless ALSA reports a minimum of frames available for I/O, we poll the ALSA filedescriptors for more.
+ * Both of these operations can uncover xrun conditions.
+ *
+ * @concern Xruns Both polling and querying available frames can report an xrun condition.
+ *
+ * @param framesAvail Return the number of available frames
+ * @param xrunOccurred Return whether an xrun has occurred
+ */ 
+static PaError PaAlsaStream_WaitForFrames( PaAlsaStream *self, unsigned long *framesAvail, int *xrunOccurred )
+{
+    PaError result = paNoError;
+    int pollPlayback = self->playback.pcm != NULL, pollCapture = self->capture.pcm != NULL;
+    int pollTimeout = self->pollTimeout;
+    int xrun = 0;
+
+    assert( self );
+    assert( framesAvail );
+
+    if( !self->callbackMode )
+    {
+        /* In blocking mode we will only wait if necessary */
+        PA_ENSURE( PaAlsaStream_GetAvailableFrames( self, self->capture.pcm != NULL, self->playback.pcm != NULL,
+                    framesAvail, &xrun ) );
+        if( xrun )
+        {
+            goto end;
+        }
+
+        if( *framesAvail > 0 )
+        {
+            /* Mark pcms ready from poll */
+            if( self->capture.pcm )
+                self->capture.ready = 1;
+            if( self->playback.pcm )
+                self->playback.ready = 1;
+
+            goto end;
+        }
+    }
+
+    while( pollPlayback || pollCapture )
+    {
+        int totalFds = 0;
+        struct pollfd *capturePfds = NULL, *playbackPfds = NULL;
+
+        pthread_testcancel();
+
+        if( pollCapture )
+        {
+            capturePfds = self->pfds;
+            PA_ENSURE( PaAlsaStreamComponent_BeginPolling( &self->capture, capturePfds ) );
+            totalFds += self->capture.nfds;
+        }
+        if( pollPlayback )
+        {
+            playbackPfds = self->pfds + (self->capture.pcm ? self->capture.nfds : 0);
+            PA_ENSURE( PaAlsaStreamComponent_BeginPolling( &self->playback, playbackPfds ) );
+            totalFds += self->playback.nfds;
+        }
+        
+        if( poll( self->pfds, totalFds, pollTimeout ) < 0 )
+        {
+            /*  XXX: Depend on preprocessor condition? */
+            if( errno == EINTR )
+            {
+                /* gdb */
+                continue;
+            }
+
+            /* TODO: Add macro for checking system calls */
+            PA_ENSURE( paInternalError );
+        }
+
+        /* check the return status of our pfds */
+        if( pollCapture )
+        {
+            PA_ENSURE( PaAlsaStreamComponent_EndPolling( &self->capture, capturePfds, &pollCapture, &xrun ) );
+        }
+        if( pollPlayback )
+        {
+            PA_ENSURE( PaAlsaStreamComponent_EndPolling( &self->playback, playbackPfds, &pollPlayback, &xrun ) );
+        }
+        if( xrun )
+        {
+            break;
+        }
+
+        /* @concern FullDuplex If only one of two pcms is ready we may want to compromise between the two.
+         * If there is less than half a period's worth of samples left of frames in the other pcm's buffer we will
+         * stop polling.
+         */
+        if( self->capture.pcm && self->playback.pcm )
+        {
+            if( pollCapture && !pollPlayback )
+            {
+                PA_ENSURE( ContinuePoll( self, StreamDirection_In, &pollTimeout, &pollCapture ) );
+            }
+            else if( pollPlayback && !pollCapture )
+            {
+                PA_ENSURE( ContinuePoll( self, StreamDirection_Out, &pollTimeout, &pollPlayback ) );
+            }
+        }
+    }
+
+    if( !xrun )
+    {
+        /* Get the number of available frames for the pcms that are marked ready.
+         * @concern FullDuplex If only one direction is marked ready (from poll), the number of frames available for
+         * the other direction is returned. Output is normally preferred over capture however, so capture frames may be
+         * discarded to avoid overrun unless paNeverDropInput is specified.
+         */
+        int captureReady = self->capture.pcm ? self->capture.ready : 0,
+            playbackReady = self->playback.pcm ? self->playback.ready : 0;
+        PA_ENSURE( PaAlsaStream_GetAvailableFrames( self, captureReady, playbackReady, framesAvail, &xrun ) );
+
+        if( self->capture.pcm && self->playback.pcm )
+        {
+            if( !self->playback.ready && !self->neverDropInput )
+            {
+                /* Drop input, a period's worth */
+                assert( self->capture.ready );
+                PaAlsaStreamComponent_EndProcessing( &self->capture, PA_MIN( self->capture.framesPerBuffer,
+                            *framesAvail ), &xrun );
+                *framesAvail = 0;
+                self->capture.ready = 0;
+            }
+        }
+        else if( self->capture.pcm )
+            assert( self->capture.ready );
+        else
+            assert( self->playback.ready );
+    }
+
+end:
+error:
+    if( xrun )
+    {
+        /* Recover from the xrun state */
+        PA_ENSURE( PaAlsaStream_HandleXrun( self ) );
+        *framesAvail = 0;
+    }
+    else
+    {
+        if( 0 != *framesAvail )
+        {
+            /* If we're reporting frames eligible for processing, one of the handles better be ready */
+            PA_UNLESS( self->capture.ready || self->playback.ready, paInternalError );
+        }
+    }
+    *xrunOccurred = xrun;
+
+    return result;
+}
+
+/** Register per-channel ALSA buffer information with buffer processor.
+ *
+ * Mmapped buffer space is acquired from ALSA, and registered with the buffer processor. Differences between the
+ * number of host and user channels is taken into account.
+ * 
+ * @param numFrames On entrance the number of requested frames, on exit the number of contiguously accessible frames.
+ */
+static PaError PaAlsaStreamComponent_RegisterChannels( PaAlsaStreamComponent* self, PaUtilBufferProcessor* bp,
+        unsigned long* numFrames, int* xrun )
+{
+    PaError result = paNoError;
+    const snd_pcm_channel_area_t *areas, *area;
+    void (*setChannel)(PaUtilBufferProcessor *, unsigned int, void *, unsigned int) =
+        StreamDirection_In == self->streamDir ? PaUtil_SetInputChannel : PaUtil_SetOutputChannel;
+    unsigned char *buffer, *p;
+    int i;
+    unsigned long framesAvail;
+
+    /* This _must_ be called before mmap_begin */
+    PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( self, &framesAvail, xrun ) );
+    if( *xrun )
+    {
+        *numFrames = 0;
+        goto end;
+    }
+
+    ENSURE_( snd_pcm_mmap_begin( self->pcm, &areas, &self->offset, numFrames ), paUnanticipatedHostError );
+
+    if( self->hostInterleaved )
+    {
+        int swidth = snd_pcm_format_size( self->nativeFormat, 1 );
+
+        p = buffer = ExtractAddress( areas, self->offset );
+        for( i = 0; i < self->numUserChannels; ++i )
+        {
+            /* We're setting the channels up to userChannels, but the stride will be hostChannels samples */
+            setChannel( bp, i, p, self->numHostChannels );
+            p += swidth;
+        }
+    }
+    else
+    {
+        for( i = 0; i < self->numUserChannels; ++i )
+        {
+            area = areas + i;
+            buffer = ExtractAddress( area, self->offset );
+            setChannel( bp, i, buffer, 1 );
+        }
+    }
+
+    /* @concern ChannelAdaption Buffer address is recorded so we can do some channel adaption later */
+    self->channelAreas = (snd_pcm_channel_area_t *)areas;
+
+end:
+error:
+    return result;
+}
+
+/** Initiate buffer processing.
+ *
+ * ALSA buffers are registered with the PA buffer processor and the buffer size (in frames) set.
+ *
+ * @concern FullDuplex If both directions are being processed, the minimum amount of frames for the two directions is
+ * calculated.
+ *
+ * @param numFrames On entrance the number of available frames, on exit the number of received frames
+ * @param xrunOccurred Return whether an xrun has occurred
+ */
+static PaError PaAlsaStream_SetUpBuffers( PaAlsaStream* self, unsigned long* numFrames, int* xrunOccurred )
+{
+    PaError result = paNoError;
+    unsigned long captureFrames = ULONG_MAX, playbackFrames = ULONG_MAX, commonFrames = 0;
+    int xrun = 0;
+
+    if( *xrunOccurred )
+    {
+        *numFrames = 0;
+        return result;
+    }
+    /* If we got here at least one of the pcm's should be marked ready */
+    PA_UNLESS( self->capture.ready || self->playback.ready, paInternalError );
+
+    /* Extract per-channel ALSA buffer pointers and register them with the buffer processor.
+     * It is possible that a direction is not marked ready however, because it is out of sync with the other.
+     */
+    if( self->capture.pcm && self->capture.ready )
+    {
+        captureFrames = *numFrames;
+        PA_ENSURE( PaAlsaStreamComponent_RegisterChannels( &self->capture, &self->bufferProcessor, &captureFrames, 
+                    &xrun ) );
+    }
+    if( self->playback.pcm && self->playback.ready )
+    {
+        playbackFrames = *numFrames;
+        PA_ENSURE( PaAlsaStreamComponent_RegisterChannels( &self->playback, &self->bufferProcessor, &playbackFrames, 
+                    &xrun ) );
+    }
+    if( xrun )
+    {
+        /* Nothing more to do */
+        assert( 0 == commonFrames );
+        goto end;
+    }
+
+    commonFrames = PA_MIN( captureFrames, playbackFrames );
+    /* assert( commonFrames <= *numFrames ); */
+    if( commonFrames > *numFrames )
+    {
+        /* Hmmm ... how come there are more frames available than we requested!? Blah. */
+        PA_DEBUG(( "%s: Common available frames are reported to be more than number requested: %lu, %lu, callbackMode: %d\n", __FUNCTION__,
+                    commonFrames, *numFrames, self->callbackMode ));
+        if( self->capture.pcm )
+        {
+            PA_DEBUG(( "%s: captureFrames: %lu, capture.ready: %d\n", __FUNCTION__, captureFrames, self->capture.ready ));
+        }
+        if( self->playback.pcm )
+        {
+            PA_DEBUG(( "%s: playbackFrames: %lu, playback.ready: %d\n", __FUNCTION__, playbackFrames, self->playback.ready ));
+        }
+        
+        commonFrames = 0;
+        goto end;
+    }
+
+    /* Inform PortAudio of the number of frames we got.
+     * @concern FullDuplex We might be experiencing underflow in either end; if its an input underflow, we go on
+     * with output. If its output underflow however, depending on the paNeverDropInput flag, we may want to simply
+     * discard the excess input or call the callback with paOutputOverflow flagged.
+     */
+    if( self->capture.pcm )
+    {
+        if( self->capture.ready )
+        {
+            PaUtil_SetInputFrameCount( &self->bufferProcessor, commonFrames );
+        }
+        else
+        {
+            /* We have input underflow */
+            PaUtil_SetNoInput( &self->bufferProcessor );
+        }
+    }
+    if( self->playback.pcm )
+    {
+        if( self->playback.ready )
+        {
+            PaUtil_SetOutputFrameCount( &self->bufferProcessor, commonFrames );
+        }
+        else
+        {
+            /* We have output underflow, but keeping input data (paNeverDropInput) */
+            assert( self->neverDropInput );
+            assert( self->capture.pcm != NULL );
+            PA_DEBUG(( "%s: Setting output buffers to NULL\n", __FUNCTION__ ));
+            PaUtil_SetNoOutput( &self->bufferProcessor );
+        }
+    }
+    
+end:
+    *numFrames = commonFrames;
+error:
+    if( xrun )
+    {
+        PA_ENSURE( PaAlsaStream_HandleXrun( self ) );
+        *numFrames = 0;
+    }
+    *xrunOccurred = xrun;
+
+    return result;
+}
+
+/** Callback thread's function.
+ *
+ * Roughly, the workflow can be described in the following way: The number of available frames that can be processed
+ * directly is obtained from ALSA, we then request as much directly accessible memory as possible within this amount
+ * from ALSA. The buffer memory is registered with the PA buffer processor and processing is carried out with
+ * PaUtil_EndBufferProcessing. Finally, the number of processed frames is reported to ALSA. The processing can
+ * happen in several iterations untill we have consumed the known number of available frames (or an xrun is detected).
+ */
+static void *CallbackThreadFunc( void *userData )
+{
+    PaError result = paNoError;
+    PaAlsaStream *stream = (PaAlsaStream*) userData;
+    PaStreamCallbackTimeInfo timeInfo = {0, 0, 0};
+    snd_pcm_sframes_t startThreshold = 0;
+    int callbackResult = paContinue;
+    PaStreamCallbackFlags cbFlags = 0;  /* We might want to keep state across iterations */
+    int streamStarted = 0;
+
+    assert( stream );
+
+    /* Execute OnExit when exiting */
+    pthread_cleanup_push( &OnExit, stream );
+
+    /* Not implemented */
+    assert( !stream->primeBuffers );
+
+    /* @concern StreamStart If the output is being primed the output pcm needs to be prepared, otherwise the
+     * stream is started immediately. The latter involves signaling the waiting main thread.
+     */
+    if( stream->primeBuffers )
+    {
+        snd_pcm_sframes_t avail;
+        
+        if( stream->playback.pcm )
+            ENSURE_( snd_pcm_prepare( stream->playback.pcm ), paUnanticipatedHostError );
+        if( stream->capture.pcm && !stream->pcmsSynced )
+            ENSURE_( snd_pcm_prepare( stream->capture.pcm ), paUnanticipatedHostError );
+
+        /* We can't be certain that the whole ring buffer is available for priming, but there should be
+         * at least one period */
+        avail = snd_pcm_avail_update( stream->playback.pcm );
+        startThreshold = avail - (avail % stream->playback.framesPerBuffer);
+        assert( startThreshold >= stream->playback.framesPerBuffer );
+    }
+    else
+    {
+        PA_ENSURE( PaUnixThread_PrepareNotify( &stream->thread ) );
+        /* Buffer will be zeroed */
+        PA_ENSURE( AlsaStart( stream, 0 ) );
+        PA_ENSURE( PaUnixThread_NotifyParent( &stream->thread ) );
+
+        streamStarted = 1;
+    }
+
+    while( 1 )
+    {
+        unsigned long framesAvail, framesGot;
+        int xrun = 0;
+
+        pthread_testcancel();
+
+        /* @concern StreamStop if the main thread has requested a stop and the stream has not been effectively
+         * stopped we signal this condition by modifying callbackResult (we'll want to flush buffered output).
+         */
+        if( PaUnixThread_StopRequested( &stream->thread ) && paContinue == callbackResult )
+        {
+            PA_DEBUG(( "Setting callbackResult to paComplete\n" ));
+            callbackResult = paComplete;
+        }
+
+        if( paContinue != callbackResult )
+        {
+            stream->callbackAbort = (paAbort == callbackResult);
+            if( stream->callbackAbort ||
+                    /** @concern BlockAdaption: Go on if adaption buffers are empty */
+                    PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) ) 
+            {
+                goto end;
+            }
+
+            PA_DEBUG(( "%s: Flushing buffer processor\n", __FUNCTION__ ));
+            /* There is still buffered output that needs to be processed */
+        }
+
+        /* Wait for data to become available, this comes down to polling the ALSA file descriptors untill we have
+         * a number of available frames.
+         */
+        PA_ENSURE( PaAlsaStream_WaitForFrames( stream, &framesAvail, &xrun ) );
+        if( xrun )
+        {
+            assert( 0 == framesAvail );
+            continue;
+
+            /* XXX: Report xruns to the user? A situation is conceivable where the callback is never invoked due
+             * to constant xruns, it might be desirable to notify the user of this.
+             */
+        }
+
+        /* Consume buffer space. Once we have a number of frames available for consumption we must retrieve the
+         * mmapped buffers from ALSA, this is contiguously accessible memory however, so we may receive smaller
+         * portions at a time than is available as a whole. Therefore we should be prepared to process several
+         * chunks successively. The buffers are passed to the PA buffer processor.
+         */
+        while( framesAvail > 0 )
+        {
+            xrun = 0;
+
+            pthread_testcancel();
+
+            /** @concern Xruns Under/overflows are to be reported to the callback */
+            if( stream->underrun > 0.0 )
+            {
+                cbFlags |= paOutputUnderflow;
+                stream->underrun = 0.0;
+            }
+            if( stream->overrun > 0.0 )
+            {
+                cbFlags |= paInputOverflow;
+                stream->overrun = 0.0;
+            }
+            if( stream->capture.pcm && stream->playback.pcm )
+            {
+                /** @concern FullDuplex It's possible that only one direction is being processed to avoid an
+                 * under- or overflow, this should be reported correspondingly */
+                if( !stream->capture.ready )
+                {
+                    cbFlags |= paInputUnderflow;
+                    PA_DEBUG(( "%s: Input underflow\n", __FUNCTION__ ));
+                }
+                else if( !stream->playback.ready )
+                {
+                    cbFlags |= paOutputOverflow;
+                    PA_DEBUG(( "%s: Output overflow\n", __FUNCTION__ ));
+                }
+            }
+
+#if 0
+            CallbackUpdate( &stream->threading );
+#endif
+            CalculateTimeInfo( stream, &timeInfo );
+            PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, cbFlags );
+            cbFlags = 0;
+
+            /* CPU load measurement should include processing activivity external to the stream callback */
+            PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
+
+            framesGot = framesAvail;
+            if( paUtilFixedHostBufferSize == stream->bufferProcessor.hostBufferSizeMode )
+            {
+                /* We've committed to a fixed host buffer size, stick to that */
+                framesGot = framesGot >= stream->maxFramesPerHostBuffer ? stream->maxFramesPerHostBuffer : 0;
+            }
+            else
+            {
+                /* We've committed to an upper bound on the size of host buffers */
+                assert( paUtilBoundedHostBufferSize == stream->bufferProcessor.hostBufferSizeMode );
+                framesGot = PA_MIN( framesGot, stream->maxFramesPerHostBuffer );
+            }
+            PA_ENSURE( PaAlsaStream_SetUpBuffers( stream, &framesGot, &xrun ) );
+            /* Check the host buffer size against the buffer processor configuration */
+            framesAvail -= framesGot;
+
+            if( framesGot > 0 )
+            {
+                assert( !xrun );
+                PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult );
+                PA_ENSURE( PaAlsaStream_EndProcessing( stream, framesGot, &xrun ) );
+            }
+            PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesGot );
+
+            if( 0 == framesGot )
+            {
+                /* Go back to polling for more frames */
+                break;
+
+            }
+
+            if( paContinue != callbackResult )
+                break;
+        }
+    }
+
+    /* Match pthread_cleanup_push */
+    pthread_cleanup_pop( 1 );
+
+end:
+    PA_DEBUG(( "%s: Thread %d exiting\n ", __FUNCTION__, pthread_self() ));
+    PaUnixThreading_EXIT( result );
+error:
+    goto end;
+}
+
+/* Blocking interface */
+
+static PaError ReadStream( PaStream* s, void *buffer, unsigned long frames )
+{
+    PaError result = paNoError;
+    PaAlsaStream *stream = (PaAlsaStream*)s;
+    unsigned long framesGot, framesAvail;
+    void *userBuffer;
+    snd_pcm_t *save = stream->playback.pcm;
+
+    assert( stream );
+
+    PA_UNLESS( stream->capture.pcm, paCanNotReadFromAnOutputOnlyStream );
+
+    /* Disregard playback */
+    stream->playback.pcm = NULL;
+
+    if( stream->overrun > 0. )
+    {
+        result = paInputOverflowed;
+        stream->overrun = 0.0;
+    }
+
+    if( stream->capture.userInterleaved )
+    {
+        userBuffer = buffer;
+    }
+    else
+    {
+        /* Copy channels into local array */
+        userBuffer = stream->capture.userBuffers;
+        memcpy( userBuffer, buffer, sizeof (void *) * stream->capture.numUserChannels );
+    }
+
+    /* Start stream if in prepared state */
+    if( snd_pcm_state( stream->capture.pcm ) == SND_PCM_STATE_PREPARED )
+    {
+        ENSURE_( snd_pcm_start( stream->capture.pcm ), paUnanticipatedHostError );
+    }
+
+    while( frames > 0 )
+    {
+        int xrun = 0;
+        PA_ENSURE( PaAlsaStream_WaitForFrames( stream, &framesAvail, &xrun ) );
+        framesGot = PA_MIN( framesAvail, frames );
+
+        PA_ENSURE( PaAlsaStream_SetUpBuffers( stream, &framesGot, &xrun ) );
+        if( framesGot > 0 )
+        {
+            framesGot = PaUtil_CopyInput( &stream->bufferProcessor, &userBuffer, framesGot );
+            PA_ENSURE( PaAlsaStream_EndProcessing( stream, framesGot, &xrun ) );
+            frames -= framesGot;
+        }
+    }
+
+end:
+    stream->playback.pcm = save;
+    return result;
+error:
+    goto end;
+}
+
+static PaError WriteStream( PaStream* s, const void *buffer, unsigned long frames )
+{
+    PaError result = paNoError;
+    signed long err;
+    PaAlsaStream *stream = (PaAlsaStream*)s;
+    snd_pcm_uframes_t framesGot, framesAvail;
+    const void *userBuffer;
+    snd_pcm_t *save = stream->capture.pcm;
+    
+    assert( stream );
+
+    PA_UNLESS( stream->playback.pcm, paCanNotWriteToAnInputOnlyStream );
+
+    /* Disregard capture */
+    stream->capture.pcm = NULL;
+
+    if( stream->underrun > 0. )
+    {
+        result = paOutputUnderflowed;
+        stream->underrun = 0.0;
+    }
+
+    if( stream->playback.userInterleaved )
+        userBuffer = buffer;
+    else /* Copy channels into local array */
+    {
+        userBuffer = stream->playback.userBuffers;
+        memcpy( (void *)userBuffer, buffer, sizeof (void *) * stream->playback.numUserChannels );
+    }
+
+    while( frames > 0 )
+    {
+        int xrun = 0;
+        snd_pcm_uframes_t hwAvail;
+
+        PA_ENSURE( PaAlsaStream_WaitForFrames( stream, &framesAvail, &xrun ) );
+        framesGot = PA_MIN( framesAvail, frames );
+
+        PA_ENSURE( PaAlsaStream_SetUpBuffers( stream, &framesGot, &xrun ) );
+        if( framesGot > 0 )
+        {
+            framesGot = PaUtil_CopyOutput( &stream->bufferProcessor, &userBuffer, framesGot );
+            PA_ENSURE( PaAlsaStream_EndProcessing( stream, framesGot, &xrun ) );
+            frames -= framesGot;
+        }
+
+        /* Start stream after one period of samples worth */
+
+        /* Frames residing in buffer */
+        PA_ENSURE( err = GetStreamWriteAvailable( stream ) );
+        framesAvail = err;
+        hwAvail = stream->playback.bufferSize - framesAvail;
+
+        if( snd_pcm_state( stream->playback.pcm ) == SND_PCM_STATE_PREPARED &&
+                hwAvail >= stream->playback.framesPerBuffer )
+        {
+            ENSURE_( snd_pcm_start( stream->playback.pcm ), paUnanticipatedHostError );
+        }
+    }
+
+end:
+    stream->capture.pcm = save;
+    return result;
+error:
+    goto end;
+}
+
+/* Return frames available for reading. In the event of an overflow, the capture pcm will be restarted */
+static signed long GetStreamReadAvailable( PaStream* s )
+{
+    PaError result = paNoError;
+    PaAlsaStream *stream = (PaAlsaStream*)s;
+    unsigned long avail;
+    int xrun;
+
+    PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &stream->capture, &avail, &xrun ) );
+    if( xrun )
+    {
+        PA_ENSURE( PaAlsaStream_HandleXrun( stream ) );
+        PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &stream->capture, &avail, &xrun ) );
+        if( xrun )
+            PA_ENSURE( paInputOverflowed );
+    }
+
+    return (signed long)avail;
+
+error:
+    return result;
+}
+
+static signed long GetStreamWriteAvailable( PaStream* s )
+{
+    PaError result = paNoError;
+    PaAlsaStream *stream = (PaAlsaStream*)s;
+    unsigned long avail;
+    int xrun;
+
+    PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &stream->playback, &avail, &xrun ) );
+    if( xrun )
+    {
+        snd_pcm_sframes_t savail;
+
+        PA_ENSURE( PaAlsaStream_HandleXrun( stream ) );
+        savail = snd_pcm_avail_update( stream->playback.pcm );
+
+        /* savail should not contain -EPIPE now, since PaAlsaStream_HandleXrun will only prepare the pcm */
+        ENSURE_( savail, paUnanticipatedHostError );
+
+        avail = (unsigned long) savail;
+    }
+
+    return (signed long)avail;
+
+error:
+    return result;
+}
+
+/* Extensions */
+
+/* Initialize host api specific structure */
+void PaAlsa_InitializeStreamInfo( PaAlsaStreamInfo *info )
+{
+    info->size = sizeof (PaAlsaStreamInfo);
+    info->hostApiType = paALSA;
+    info->version = 1;
+    info->deviceString = NULL;
+}
+
+void PaAlsa_EnableRealtimeScheduling( PaStream *s, int enable )
+{
+#if 0
+    PaAlsaStream *stream = (PaAlsaStream *) s;
+    stream->threading.rtSched = enable;
+#endif
+}
+
+void PaAlsa_EnableWatchdog( PaStream *s, int enable )
+{
+#if 0
+    PaAlsaStream *stream = (PaAlsaStream *) s;
+    stream->threading.useWatchdog = enable;
+#endif
+}
diff --git a/src/engine/external/portaudio/pa_linux_alsa.h b/src/engine/external/portaudio/pa_linux_alsa.h
new file mode 100644
index 00000000..2818c01b
--- /dev/null
+++ b/src/engine/external/portaudio/pa_linux_alsa.h
@@ -0,0 +1,70 @@
+#ifndef PA_LINUX_ALSA_H
+#define PA_LINUX_ALSA_H
+
+/*
+ * $Id: pa_linux_alsa.h 1083 2006-08-23 07:30:49Z rossb $
+ * PortAudio Portable Real-Time Audio Library
+ * ALSA-specific extensions
+ *
+ * Copyright (c) 1999-2000 Ross Bencina and Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however, 
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also 
+ * requested that these non-binding requests be included along with the 
+ * license above.
+ */
+
+/** @file
+ * ALSA-specific PortAudio API extension header file.
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct PaAlsaStreamInfo
+{
+    unsigned long size;
+    PaHostApiTypeId hostApiType;
+    unsigned long version;
+
+    const char *deviceString;
+}
+PaAlsaStreamInfo;
+
+void PaAlsa_InitializeStreamInfo( PaAlsaStreamInfo *info );
+
+void PaAlsa_EnableRealtimeScheduling( PaStream *s, int enable );
+
+void PaAlsa_EnableWatchdog( PaStream *s, int enable );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/engine/external/portaudio/pa_mac_core.c b/src/engine/external/portaudio/pa_mac_core.c
new file mode 100644
index 00000000..1c40c7a8
--- /dev/null
+++ b/src/engine/external/portaudio/pa_mac_core.c
@@ -0,0 +1,2238 @@
+/*

+ * Implementation of the PortAudio API for Apple AUHAL

+ *

+ * PortAudio Portable Real-Time Audio Library

+ * Latest Version at: http://www.portaudio.com

+ *

+ * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.

+ * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)

+ *

+ * Dominic's code was based on code by Phil Burk, Darren Gibbs,

+ * Gord Peters, Stephane Letz, and Greg Pfiel.

+ *

+ * The following people also deserve acknowledgements:

+ *

+ * Olivier Tristan for feedback and testing

+ * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O

+ * interface.

+ * 

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/**

+ @file pa_mac_core

+ @ingroup hostapi_src

+ @author Bjorn Roche

+ @brief AUHAL implementation of PortAudio

+*/

+

+/* FIXME: not all error conditions call PaUtil_SetLastHostErrorInfo()

+ * PaMacCore_SetError() will do this.

+ */

+

+#include "pa_mac_core_internal.h"

+

+#include <string.h> /* strlen(), memcmp() etc. */

+

+#include "pa_mac_core.h"

+#include "pa_mac_core_utilities.h"

+#include "pa_mac_core_blocking.h"

+

+

+#ifdef __cplusplus

+extern "C"

+{

+#endif /* __cplusplus */

+

+/* prototypes for functions declared in this file */

+

+PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );

+

+/*

+ * Function declared in pa_mac_core.h. Sets up a PaMacCoreStreamInfoStruct

+ * with the requested flags and initializes channel map.

+ */

+void PaMacCore_SetupStreamInfo(  PaMacCoreStreamInfo *data, const unsigned long flags )

+{

+   bzero( data, sizeof( PaMacCoreStreamInfo ) );

+   data->size = sizeof( PaMacCoreStreamInfo );

+   data->hostApiType = paCoreAudio;

+   data->version = 0x01;

+   data->flags = flags;

+   data->channelMap = NULL;

+   data->channelMapSize = 0;

+}

+

+/*

+ * Function declared in pa_mac_core.h. Adds channel mapping to a PaMacCoreStreamInfoStruct

+ */

+void PaMacCore_SetupChannelMap( PaMacCoreStreamInfo *data, const SInt32 * const channelMap, const unsigned long channelMapSize )

+{

+   data->channelMap = channelMap;

+   data->channelMapSize = channelMapSize;

+}

+static char *channelName = NULL;

+static int channelNameSize = 0;

+static bool ensureChannelNameSize( int size )

+{

+   if( size >= channelNameSize ) {

+      free( channelName );

+      channelName = (char *) malloc( ( channelNameSize = size ) + 1 );

+      if( !channelName ) {

+         channelNameSize = 0;

+         return false;

+      }

+   }

+   return true;

+}

+/*

+ * Function declared in pa_mac_core.h. retrives channel names.

+ */

+const char *PaMacCore_GetChannelName( int device, int channelIndex, bool input )

+{

+   struct PaUtilHostApiRepresentation *hostApi;

+   PaError err;

+   OSStatus error;

+   err = PaUtil_GetHostApiRepresentation( &hostApi, paCoreAudio );

+   assert(err == paNoError);

+   PaMacAUHAL *macCoreHostApi = (PaMacAUHAL*)hostApi;

+   AudioDeviceID hostApiDevice = macCoreHostApi->devIds[device];

+

+   UInt32 size = 0;

+

+   error = AudioDeviceGetPropertyInfo( hostApiDevice,

+                                       channelIndex + 1,

+                                       input,

+                                       kAudioDevicePropertyChannelName,

+                                       &size,

+                                       NULL );

+   if( error ) {

+      //try the CFString

+      CFStringRef name;

+      bool isDeviceName = false;

+      size = sizeof( name );

+      error = AudioDeviceGetProperty( hostApiDevice,

+                                      channelIndex + 1,

+                                      input,

+                                      kAudioDevicePropertyChannelNameCFString,

+                                      &size,

+                                      &name );

+      if( error ) { //as a last-ditch effort, get the device name. Later we'll append the channel number.

+         size = sizeof( name );

+         error = AudioDeviceGetProperty( hostApiDevice,

+                                      channelIndex + 1,

+                                      input,

+                                      kAudioDevicePropertyDeviceNameCFString,

+                                      &size,

+                                      &name );

+         if( error )

+            return NULL;

+         isDeviceName = true;

+      }

+      if( isDeviceName ) {

+         name = CFStringCreateWithFormat( NULL, NULL, CFSTR( "%@: %d"), name, channelIndex + 1 );

+      }

+

+      CFIndex length = CFStringGetLength(name);

+      while( ensureChannelNameSize( length * sizeof(UniChar) + 1 ) ) {

+         if( CFStringGetCString( name, channelName, channelNameSize, kCFStringEncodingUTF8 ) ) {

+            if( isDeviceName )

+               CFRelease( name );

+            return channelName;

+         }

+         if( length == 0 )

+            ++length;

+         length *= 2;

+      }

+      if( isDeviceName )

+         CFRelease( name );

+      return NULL;

+   }

+

+   //continue with C string:

+   if( !ensureChannelNameSize( size ) )

+      return NULL;

+

+   error = AudioDeviceGetProperty( hostApiDevice,

+                                   channelIndex + 1,

+                                   input,

+                                   kAudioDevicePropertyChannelName,

+                                   &size,

+                                   channelName );

+

+   if( error ) {

+      ERR( error );

+      return NULL;

+   }

+   return channelName;

+}

+

+

+

+

+

+AudioDeviceID PaMacCore_GetStreamInputDevice( PaStream* s )

+{

+    PaMacCoreStream *stream = (PaMacCoreStream*)s;

+    VVDBUG(("PaMacCore_GetStreamInputHandle()\n"));

+

+    return ( stream->inputDevice );

+}

+

+AudioDeviceID PaMacCore_GetStreamOutputDevice( PaStream* s )

+{

+    PaMacCoreStream *stream = (PaMacCoreStream*)s;

+    VVDBUG(("PaMacCore_GetStreamOutputHandle()\n"));

+

+    return ( stream->outputDevice );

+}

+

+#ifdef __cplusplus

+}

+#endif /* __cplusplus */

+

+#define RING_BUFFER_ADVANCE_DENOMINATOR (4)

+

+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );

+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,

+                                  const PaStreamParameters *inputParameters,

+                                  const PaStreamParameters *outputParameters,

+                                  double sampleRate );

+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,

+                           PaStream** s,

+                           const PaStreamParameters *inputParameters,

+                           const PaStreamParameters *outputParameters,

+                           double sampleRate,

+                           unsigned long framesPerBuffer,

+                           PaStreamFlags streamFlags,

+                           PaStreamCallback *streamCallback,

+                           void *userData );

+static PaError CloseStream( PaStream* stream );

+static PaError StartStream( PaStream *stream );

+static PaError StopStream( PaStream *stream );

+static PaError AbortStream( PaStream *stream );

+static PaError IsStreamStopped( PaStream *s );

+static PaError IsStreamActive( PaStream *stream );

+static PaTime GetStreamTime( PaStream *stream );

+static void setStreamStartTime( PaStream *stream );

+static OSStatus AudioIOProc( void *inRefCon,

+                               AudioUnitRenderActionFlags *ioActionFlags,

+                               const AudioTimeStamp *inTimeStamp,

+                               UInt32 inBusNumber,

+                               UInt32 inNumberFrames,

+                               AudioBufferList *ioData );

+static double GetStreamCpuLoad( PaStream* stream );

+

+static PaError GetChannelInfo( PaMacAUHAL *auhalHostApi,

+                               PaDeviceInfo *deviceInfo,

+                               AudioDeviceID macCoreDeviceId,

+                               int isInput);

+

+static PaError OpenAndSetupOneAudioUnit(

+                                   const PaStreamParameters *inStreamParams,

+                                   const PaStreamParameters *outStreamParams,

+                                   const unsigned long requestedFramesPerBuffer,

+                                   unsigned long *actualInputFramesPerBuffer,

+                                   unsigned long *actualOutputFramesPerBuffer,

+                                   const PaMacAUHAL *auhalHostApi,

+                                   AudioUnit *audioUnit,

+                                   AudioConverterRef *srConverter,

+                                   AudioDeviceID *audioDevice,

+                                   const double sampleRate,

+                                   void *refCon );

+

+/* for setting errors. */

+#define PA_AUHAL_SET_LAST_HOST_ERROR( errorCode, errorText ) \

+    PaUtil_SetLastHostErrorInfo( paInDevelopment, errorCode, errorText )

+

+/*currently, this is only used in initialization, but it might be modified

+  to be used when the list of devices changes.*/

+static PaError gatherDeviceInfo(PaMacAUHAL *auhalHostApi)

+{

+    UInt32 size;

+    UInt32 propsize;

+    VVDBUG(("gatherDeviceInfo()\n"));

+    /* -- free any previous allocations -- */

+    if( auhalHostApi->devIds )

+        PaUtil_GroupFreeMemory(auhalHostApi->allocations, auhalHostApi->devIds);

+    auhalHostApi->devIds = NULL;

+

+    /* -- figure out how many devices there are -- */

+    AudioHardwareGetPropertyInfo( kAudioHardwarePropertyDevices,

+                                  &propsize,

+                                  NULL );

+    auhalHostApi->devCount = propsize / sizeof( AudioDeviceID );

+

+    VDBUG( ( "Found %ld device(s).\n", auhalHostApi->devCount ) );

+

+    /* -- copy the device IDs -- */

+    auhalHostApi->devIds = (AudioDeviceID *)PaUtil_GroupAllocateMemory(

+                             auhalHostApi->allocations,

+                             propsize );

+    if( !auhalHostApi->devIds )

+        return paInsufficientMemory;

+    AudioHardwareGetProperty( kAudioHardwarePropertyDevices,

+                                  &propsize,

+                                  auhalHostApi->devIds );

+#ifdef MAC_CORE_VERBOSE_DEBUG

+    {

+       int i;

+       for( i=0; i<auhalHostApi->devCount; ++i )

+          printf( "Device %d\t: %ld\n", i, auhalHostApi->devIds[i] );

+    }

+#endif

+

+    size = sizeof(AudioDeviceID);

+    auhalHostApi->defaultIn  = kAudioDeviceUnknown;

+    auhalHostApi->defaultOut = kAudioDeviceUnknown;

+

+    /* determine the default device. */

+    /* I am not sure how these calls to AudioHardwareGetProperty()

+       could fail, but in case they do, we use the first available

+       device as the default. */

+    if( 0 != AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice,

+                     &size,

+                     &auhalHostApi->defaultIn) ) {

+       int i;

+       auhalHostApi->defaultIn  = kAudioDeviceUnknown;

+       VDBUG(("Failed to get default input device from OS."));

+       VDBUG((" I will substitute the first available input Device."));

+       for( i=0; i<auhalHostApi->devCount; ++i ) {

+          PaDeviceInfo devInfo;

+          if( 0 != GetChannelInfo( auhalHostApi, &devInfo,

+                                   auhalHostApi->devIds[i], TRUE ) )

+             if( devInfo.maxInputChannels ) {

+                auhalHostApi->defaultIn = auhalHostApi->devIds[i];

+                break;

+             }

+       }

+    }   

+    if( 0 != AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice,

+                     &size,

+                     &auhalHostApi->defaultOut) ) {

+       int i;

+       auhalHostApi->defaultIn  = kAudioDeviceUnknown;

+       VDBUG(("Failed to get default output device from OS."));

+       VDBUG((" I will substitute the first available output Device."));

+       for( i=0; i<auhalHostApi->devCount; ++i ) {

+          PaDeviceInfo devInfo;

+          if( 0 != GetChannelInfo( auhalHostApi, &devInfo,

+                                   auhalHostApi->devIds[i], FALSE ) )

+             if( devInfo.maxOutputChannels ) {

+                auhalHostApi->defaultOut = auhalHostApi->devIds[i];

+                break;

+             }

+       }

+    }   

+

+    VDBUG( ( "Default in : %ld\n", auhalHostApi->defaultIn  ) );

+    VDBUG( ( "Default out: %ld\n", auhalHostApi->defaultOut ) );

+

+    return paNoError;

+}

+

+static PaError GetChannelInfo( PaMacAUHAL *auhalHostApi,

+                               PaDeviceInfo *deviceInfo,

+                               AudioDeviceID macCoreDeviceId,

+                               int isInput)

+{

+    UInt32 propSize;

+    PaError err = paNoError;

+    UInt32 i;

+    int numChannels = 0;

+    AudioBufferList *buflist = NULL;

+    UInt32 frameLatency;

+

+    VVDBUG(("GetChannelInfo()\n"));

+

+    /* Get the number of channels from the stream configuration.

+       Fail if we can't get this. */

+

+    err = ERR(AudioDeviceGetPropertyInfo(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreamConfiguration, &propSize, NULL));

+    if (err)

+        return err;

+

+    buflist = PaUtil_AllocateMemory(propSize);

+    if( !buflist )

+       return paInsufficientMemory;

+    err = ERR(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreamConfiguration, &propSize, buflist));

+    if (err)

+        goto error;

+

+    for (i = 0; i < buflist->mNumberBuffers; ++i)

+        numChannels += buflist->mBuffers[i].mNumberChannels;

+

+    if (isInput)

+        deviceInfo->maxInputChannels = numChannels;

+    else

+        deviceInfo->maxOutputChannels = numChannels;

+      

+    if (numChannels > 0) /* do not try to retrieve the latency if there is no channels. */

+    {

+       /* Get the latency.  Don't fail if we can't get this. */

+       /* default to something reasonable */

+       deviceInfo->defaultLowInputLatency = .01;

+       deviceInfo->defaultHighInputLatency = .10;

+       deviceInfo->defaultLowOutputLatency = .01;

+       deviceInfo->defaultHighOutputLatency = .10;

+       propSize = sizeof(UInt32);

+       err = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyLatency, &propSize, &frameLatency));

+       if (!err)

+       {

+          /** FEEDBACK:

+           * This code was arrived at by trial and error, and some extentive, but not exhaustive

+           * testing. Sebastien Beaulieu <seb@plogue.com> has suggested using

+           * kAudioDevicePropertyLatency + kAudioDevicePropertySafetyOffset + buffer size instead.

+           * At the time this code was written, many users were reporting dropouts with audio

+           * programs that probably used this formula. This was probably

+           * around 10.4.4, and the problem is probably fixed now. So perhaps

+           * his formula should be reviewed and used.

+           * */

+          double secondLatency = frameLatency / deviceInfo->defaultSampleRate;

+          if (isInput)

+          {

+             deviceInfo->defaultLowInputLatency = 3 * secondLatency;

+             deviceInfo->defaultHighInputLatency = 3 * 10 * secondLatency;

+          }

+          else

+          {

+             deviceInfo->defaultLowOutputLatency = 3 * secondLatency;

+             deviceInfo->defaultHighOutputLatency = 3 * 10 * secondLatency;

+          }

+       }

+    }

+    PaUtil_FreeMemory( buflist );

+    return paNoError;

+ error:

+    PaUtil_FreeMemory( buflist );

+    return err;

+}

+

+static PaError InitializeDeviceInfo( PaMacAUHAL *auhalHostApi,

+                                     PaDeviceInfo *deviceInfo,

+                                     AudioDeviceID macCoreDeviceId,

+                                     PaHostApiIndex hostApiIndex )

+{

+    Float64 sampleRate;

+    char *name;

+    PaError err = paNoError;

+    UInt32 propSize;

+

+    VVDBUG(("InitializeDeviceInfo(): macCoreDeviceId=%ld\n", macCoreDeviceId));

+

+    memset(deviceInfo, 0, sizeof(deviceInfo));

+

+    deviceInfo->structVersion = 2;

+    deviceInfo->hostApi = hostApiIndex;

+

+    /* Get the device name.  Fail if we can't get it. */

+    err = ERR(AudioDeviceGetPropertyInfo(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceName, &propSize, NULL));

+    if (err)

+        return err;

+

+    name = PaUtil_GroupAllocateMemory(auhalHostApi->allocations,propSize);

+    if ( !name )

+        return paInsufficientMemory;

+    err = ERR(AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceName, &propSize, name));

+    if (err)

+        return err;

+    deviceInfo->name = name;

+

+    /* Try to get the default sample rate.  Don't fail if we can't get this. */

+    propSize = sizeof(Float64);

+    err = ERR(AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyNominalSampleRate, &propSize, &sampleRate));

+    if (err)

+        deviceInfo->defaultSampleRate = 0.0;

+    else

+        deviceInfo->defaultSampleRate = sampleRate;

+

+    /* Get the maximum number of input and output channels.  Fail if we can't get this. */

+

+    err = GetChannelInfo(auhalHostApi, deviceInfo, macCoreDeviceId, 1);

+    if (err)

+        return err;

+

+    err = GetChannelInfo(auhalHostApi, deviceInfo, macCoreDeviceId, 0);

+    if (err)

+        return err;

+

+    return paNoError;

+}

+

+PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )

+{

+    PaError result = paNoError;

+    int i;

+    PaMacAUHAL *auhalHostApi;

+    PaDeviceInfo *deviceInfoArray;

+

+    VVDBUG(("PaMacCore_Initialize(): hostApiIndex=%d\n", hostApiIndex));

+

+    auhalHostApi = (PaMacAUHAL*)PaUtil_AllocateMemory( sizeof(PaMacAUHAL) );

+    if( !auhalHostApi )

+    {

+        result = paInsufficientMemory;

+        goto error;

+    }

+

+    auhalHostApi->allocations = PaUtil_CreateAllocationGroup();

+    if( !auhalHostApi->allocations )

+    {

+        result = paInsufficientMemory;

+        goto error;

+    }

+

+    auhalHostApi->devIds = NULL;

+    auhalHostApi->devCount = 0;

+

+    /* get the info we need about the devices */

+    result = gatherDeviceInfo( auhalHostApi );

+    if( result != paNoError )

+       goto error;

+

+    *hostApi = &auhalHostApi->inheritedHostApiRep;

+    (*hostApi)->info.structVersion = 1;

+    (*hostApi)->info.type = paCoreAudio;

+    (*hostApi)->info.name = "Core Audio";

+

+    (*hostApi)->info.defaultInputDevice = paNoDevice;

+    (*hostApi)->info.defaultOutputDevice = paNoDevice;

+

+    (*hostApi)->info.deviceCount = 0;  

+

+    if( auhalHostApi->devCount > 0 )

+    {

+        (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(

+                auhalHostApi->allocations, sizeof(PaDeviceInfo*) * auhalHostApi->devCount);

+        if( !(*hostApi)->deviceInfos )

+        {

+            result = paInsufficientMemory;

+            goto error;

+        }

+

+        /* allocate all device info structs in a contiguous block */

+        deviceInfoArray = (PaDeviceInfo*)PaUtil_GroupAllocateMemory(

+                auhalHostApi->allocations, sizeof(PaDeviceInfo) * auhalHostApi->devCount );

+        if( !deviceInfoArray )

+        {

+            result = paInsufficientMemory;

+            goto error;

+        }

+

+        for( i=0; i < auhalHostApi->devCount; ++i )

+        {

+            int err;

+            err = InitializeDeviceInfo( auhalHostApi, &deviceInfoArray[i],

+                                      auhalHostApi->devIds[i],

+                                      hostApiIndex );

+            if (err == paNoError)

+            { /* copy some info and set the defaults */

+                (*hostApi)->deviceInfos[(*hostApi)->info.deviceCount] = &deviceInfoArray[i];

+                if (auhalHostApi->devIds[i] == auhalHostApi->defaultIn)

+                    (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount;

+                if (auhalHostApi->devIds[i] == auhalHostApi->defaultOut)

+                    (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount;

+                (*hostApi)->info.deviceCount++;

+            }

+            else

+            { /* there was an error. we need to shift the devices down, so we ignore this one */

+                int j;

+                auhalHostApi->devCount--;

+                for( j=i; j<auhalHostApi->devCount; ++j )

+                   auhalHostApi->devIds[j] = auhalHostApi->devIds[j+1];

+                i--;

+            }

+        }

+    }

+

+    (*hostApi)->Terminate = Terminate;

+    (*hostApi)->OpenStream = OpenStream;

+    (*hostApi)->IsFormatSupported = IsFormatSupported;

+

+    PaUtil_InitializeStreamInterface( &auhalHostApi->callbackStreamInterface,

+                                      CloseStream, StartStream,

+                                      StopStream, AbortStream, IsStreamStopped,

+                                      IsStreamActive,

+                                      GetStreamTime, GetStreamCpuLoad,

+                                      PaUtil_DummyRead, PaUtil_DummyWrite,

+                                      PaUtil_DummyGetReadAvailable,

+                                      PaUtil_DummyGetWriteAvailable );

+

+    PaUtil_InitializeStreamInterface( &auhalHostApi->blockingStreamInterface,

+                                      CloseStream, StartStream,

+                                      StopStream, AbortStream, IsStreamStopped,

+                                      IsStreamActive,

+                                      GetStreamTime, PaUtil_DummyGetCpuLoad,

+                                      ReadStream, WriteStream,

+                                      GetStreamReadAvailable,

+                                      GetStreamWriteAvailable );

+

+    return result;

+

+error:

+    if( auhalHostApi )

+    {

+        if( auhalHostApi->allocations )

+        {

+            PaUtil_FreeAllAllocations( auhalHostApi->allocations );

+            PaUtil_DestroyAllocationGroup( auhalHostApi->allocations );

+        }

+                

+        PaUtil_FreeMemory( auhalHostApi );

+    }

+    return result;

+}

+

+

+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )

+{

+    PaMacAUHAL *auhalHostApi = (PaMacAUHAL*)hostApi;

+

+    VVDBUG(("Terminate()\n"));

+

+    /*

+        IMPLEMENT ME:

+            - clean up any resources not handled by the allocation group

+        TODO: Double check that everything is handled by alloc group

+    */

+

+    if( auhalHostApi->allocations )

+    {

+        PaUtil_FreeAllAllocations( auhalHostApi->allocations );

+        PaUtil_DestroyAllocationGroup( auhalHostApi->allocations );

+    }

+

+    PaUtil_FreeMemory( auhalHostApi );

+}

+

+

+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,

+                                  const PaStreamParameters *inputParameters,

+                                  const PaStreamParameters *outputParameters,

+                                  double sampleRate )

+{

+    int inputChannelCount, outputChannelCount;

+    PaSampleFormat inputSampleFormat, outputSampleFormat;

+

+    VVDBUG(("IsFormatSupported(): in chan=%d, in fmt=%ld, out chan=%d, out fmt=%ld sampleRate=%g\n",

+                inputParameters  ? inputParameters->channelCount  : -1,

+                inputParameters  ? inputParameters->sampleFormat  : -1,

+                outputParameters ? outputParameters->channelCount : -1,

+                outputParameters ? outputParameters->sampleFormat : -1,

+                (float) sampleRate ));

+ 

+    /** These first checks are standard PA checks. We do some fancier checks

+        later. */

+    if( inputParameters )

+    {

+        inputChannelCount = inputParameters->channelCount;

+        inputSampleFormat = inputParameters->sampleFormat;

+

+        /* all standard sample formats are supported by the buffer adapter,

+            this implementation doesn't support any custom sample formats */

+        if( inputSampleFormat & paCustomFormat )

+            return paSampleFormatNotSupported;

+            

+        /* unless alternate device specification is supported, reject the use of

+            paUseHostApiSpecificDeviceSpecification */

+

+        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )

+            return paInvalidDevice;

+

+        /* check that input device can support inputChannelCount */

+        if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )

+            return paInvalidChannelCount;

+    }

+    else

+    {

+        inputChannelCount = 0;

+    }

+

+    if( outputParameters )

+    {

+        outputChannelCount = outputParameters->channelCount;

+        outputSampleFormat = outputParameters->sampleFormat;

+

+        /* all standard sample formats are supported by the buffer adapter,

+            this implementation doesn't support any custom sample formats */

+        if( outputSampleFormat & paCustomFormat )

+            return paSampleFormatNotSupported;

+            

+        /* unless alternate device specification is supported, reject the use of

+            paUseHostApiSpecificDeviceSpecification */

+

+        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )

+            return paInvalidDevice;

+

+        /* check that output device can support outputChannelCount */

+        if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )

+            return paInvalidChannelCount;

+

+    }

+    else

+    {

+        outputChannelCount = 0;

+    }

+ 

+    /* FEEDBACK */

+    /*        I think the only way to check a given format SR combo is     */

+    /*        to try opening it. This could be disruptive, is that Okay?   */

+    /*        The alternative is to just read off available sample rates,  */

+    /*        but this will not work %100 of the time (eg, a device that   */

+    /*        supports N output at one rate but only N/2 at a higher rate.)*/

+

+    /* The following code opens the device with the requested parameters to

+       see if it works. */

+    {

+       PaError err;

+       PaStream *s;

+       err = OpenStream( hostApi, &s, inputParameters, outputParameters,

+                           sampleRate, 1024, 0, (PaStreamCallback *)1, NULL );

+       if( err != paNoError && err != paInvalidSampleRate )

+          DBUG( ( "OpenStream @ %g returned: %d: %s\n",

+                  (float) sampleRate, err, Pa_GetErrorText( err ) ) );

+       if( err ) 

+          return err;

+       err = CloseStream( s );

+       if( err ) {

+          /* FEEDBACK: is this more serious? should we assert? */

+          DBUG( ( "WARNING: could not close Stream. %d: %s\n",

+                  err, Pa_GetErrorText( err ) ) );

+       }

+    }

+

+    return paFormatIsSupported;

+}

+

+static PaError OpenAndSetupOneAudioUnit(

+                                   const PaStreamParameters *inStreamParams,

+                                   const PaStreamParameters *outStreamParams,

+                                   const unsigned long requestedFramesPerBuffer,

+                                   unsigned long *actualInputFramesPerBuffer,

+                                   unsigned long *actualOutputFramesPerBuffer,

+                                   const PaMacAUHAL *auhalHostApi,

+                                   AudioUnit *audioUnit,

+                                   AudioConverterRef *srConverter,

+                                   AudioDeviceID *audioDevice,

+                                   const double sampleRate,

+                                   void *refCon )

+{

+    ComponentDescription desc;

+    Component comp;

+    /*An Apple TN suggests using CAStreamBasicDescription, but that is C++*/

+    AudioStreamBasicDescription desiredFormat;

+    OSErr result = noErr;

+    PaError paResult = paNoError;

+    int line = 0;

+    UInt32 callbackKey;

+    AURenderCallbackStruct rcbs;

+    unsigned long macInputStreamFlags  = paMacCorePlayNice;

+    unsigned long macOutputStreamFlags = paMacCorePlayNice;

+    SInt32 const *inChannelMap = NULL;

+    SInt32 const *outChannelMap = NULL;

+    unsigned long inChannelMapSize = 0;

+    unsigned long outChannelMapSize = 0;

+

+    VVDBUG(("OpenAndSetupOneAudioUnit(): in chan=%d, in fmt=%ld, out chan=%d, out fmt=%ld, requestedFramesPerBuffer=%ld\n",

+                inStreamParams  ? inStreamParams->channelCount  : -1,

+                inStreamParams  ? inStreamParams->sampleFormat  : -1,

+                outStreamParams ? outStreamParams->channelCount : -1,

+                outStreamParams ? outStreamParams->sampleFormat : -1,

+                requestedFramesPerBuffer ));

+

+    /* -- handle the degenerate case  -- */

+    if( !inStreamParams && !outStreamParams ) {

+       *audioUnit = NULL;

+       *audioDevice = kAudioDeviceUnknown;

+       return paNoError;

+    }

+

+    /* -- get the user's api specific info, if they set any -- */

+    if( inStreamParams && inStreamParams->hostApiSpecificStreamInfo )

+    {

+       macInputStreamFlags=

+            ((PaMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo)

+                  ->flags;

+       inChannelMap = ((PaMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo)

+                  ->channelMap;

+       inChannelMapSize = ((PaMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo)

+                  ->channelMapSize;

+    }

+    if( outStreamParams && outStreamParams->hostApiSpecificStreamInfo )

+    {

+       macOutputStreamFlags=

+            ((PaMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo)

+                  ->flags;

+       outChannelMap = ((PaMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo)

+                  ->channelMap;

+       outChannelMapSize = ((PaMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo)

+                  ->channelMapSize; 

+    }

+    /* Override user's flags here, if desired for testing. */

+

+    /*

+     * The HAL AU is a Mac OS style "component".

+     * the first few steps deal with that.

+     * Later steps work on a combination of Mac OS

+     * components and the slightly lower level

+     * HAL.

+     */

+

+    /* -- describe the output type AudioUnit -- */

+    /*  Note: for the default AudioUnit, we could use the

+     *  componentSubType value kAudioUnitSubType_DefaultOutput;

+     *  but I don't think that's relevant here.

+     */

+    desc.componentType         = kAudioUnitType_Output;

+    desc.componentSubType      = kAudioUnitSubType_HALOutput;

+    desc.componentManufacturer = kAudioUnitManufacturer_Apple;

+    desc.componentFlags        = 0;

+    desc.componentFlagsMask    = 0;

+    /* -- find the component -- */

+    comp = FindNextComponent( NULL, &desc );

+    if( !comp )

+    {

+       DBUG( ( "AUHAL component not found." ) );

+       *audioUnit = NULL;

+       *audioDevice = kAudioDeviceUnknown;

+       return paUnanticipatedHostError;

+    }

+    /* -- open it -- */

+    result = OpenAComponent( comp, audioUnit );

+    if( result )

+    {

+       DBUG( ( "Failed to open AUHAL component." ) );

+       *audioUnit = NULL;

+       *audioDevice = kAudioDeviceUnknown;

+       return ERR( result );

+    }

+    /* -- prepare a little error handling logic / hackery -- */

+#define ERR_WRAP(mac_err) do { result = mac_err ; line = __LINE__ ; if ( result != noErr ) goto error ; } while(0)

+

+    /* -- if there is input, we have to explicitly enable input -- */

+    if( inStreamParams )

+    {

+       UInt32 enableIO = 1;

+       ERR_WRAP( AudioUnitSetProperty( *audioUnit,

+                 kAudioOutputUnitProperty_EnableIO,

+                 kAudioUnitScope_Input,

+                 INPUT_ELEMENT,

+                 &enableIO,

+                 sizeof(enableIO) ) );

+    }

+    /* -- if there is no output, we must explicitly disable output -- */

+    if( !outStreamParams )

+    {

+       UInt32 enableIO = 0;

+       ERR_WRAP( AudioUnitSetProperty( *audioUnit,

+                 kAudioOutputUnitProperty_EnableIO,

+                 kAudioUnitScope_Output,

+                 OUTPUT_ELEMENT,

+                 &enableIO,

+                 sizeof(enableIO) ) );

+    }

+

+    /* -- set the devices -- */

+    /* make sure input and output are the same device if we are doing input and

+       output. */

+    if( inStreamParams && outStreamParams )

+    {

+       assert( outStreamParams->device == inStreamParams->device );

+    }

+    if( inStreamParams )

+    {

+       *audioDevice = auhalHostApi->devIds[inStreamParams->device] ;

+       ERR_WRAP( AudioUnitSetProperty( *audioUnit,

+                    kAudioOutputUnitProperty_CurrentDevice,

+                    kAudioUnitScope_Global,

+                    INPUT_ELEMENT,

+                    audioDevice,

+                    sizeof(AudioDeviceID) ) );

+    }

+    if( outStreamParams )

+    {

+       *audioDevice = auhalHostApi->devIds[outStreamParams->device] ;

+       ERR_WRAP( AudioUnitSetProperty( *audioUnit,

+                    kAudioOutputUnitProperty_CurrentDevice,

+                    kAudioUnitScope_Global,

+                    OUTPUT_ELEMENT,

+                    audioDevice,

+                    sizeof(AudioDeviceID) ) );

+    }

+

+    /* -- set format -- */

+    bzero( &desiredFormat, sizeof(desiredFormat) );

+    desiredFormat.mFormatID         = kAudioFormatLinearPCM ;

+    desiredFormat.mFormatFlags      = kAudioFormatFlagsNativeFloatPacked;

+    desiredFormat.mFramesPerPacket  = 1;

+    desiredFormat.mBitsPerChannel   = sizeof( float ) * 8;

+

+    result = 0;

+    /*  set device format first, but only touch the device if the user asked */

+    if( inStreamParams ) {

+       /*The callback never calls back if we don't set the FPB */

+       /*This seems wierd, because I would think setting anything on the device

+         would be disruptive.*/

+       paResult = setBestFramesPerBuffer( *audioDevice, FALSE,

+                                          requestedFramesPerBuffer,

+                                          actualInputFramesPerBuffer );

+       if( paResult ) goto error;

+       if( macInputStreamFlags & paMacCoreChangeDeviceParameters ) {

+          bool requireExact;

+          requireExact=macInputStreamFlags & paMacCoreFailIfConversionRequired;

+          paResult = setBestSampleRateForDevice( *audioDevice, FALSE,

+                                                 requireExact, sampleRate );

+          if( paResult ) goto error;

+       }

+       if( actualInputFramesPerBuffer && actualOutputFramesPerBuffer )

+          *actualOutputFramesPerBuffer = *actualInputFramesPerBuffer ;

+    }

+    if( outStreamParams && !inStreamParams ) {

+       /*The callback never calls back if we don't set the FPB */

+       /*This seems wierd, because I would think setting anything on the device

+         would be disruptive.*/

+       paResult = setBestFramesPerBuffer( *audioDevice, TRUE,

+                                          requestedFramesPerBuffer,

+                                          actualOutputFramesPerBuffer );

+       if( paResult ) goto error;

+       if( macOutputStreamFlags & paMacCoreChangeDeviceParameters ) {

+          bool requireExact;

+          requireExact=macOutputStreamFlags & paMacCoreFailIfConversionRequired;

+          paResult = setBestSampleRateForDevice( *audioDevice, TRUE,

+                                                 requireExact, sampleRate );

+          if( paResult ) goto error;

+       }

+    }

+

+    /* -- set the quality of the output converter -- */

+    if( outStreamParams ) {

+       UInt32 value = kAudioConverterQuality_Max;

+       switch( macOutputStreamFlags & 0x0700 ) {

+       case 0x0100: /*paMacCore_ConversionQualityMin:*/

+          value=kRenderQuality_Min;

+          break;

+       case 0x0200: /*paMacCore_ConversionQualityLow:*/

+          value=kRenderQuality_Low;

+          break;

+       case 0x0300: /*paMacCore_ConversionQualityMedium:*/

+          value=kRenderQuality_Medium;

+          break;

+       case 0x0400: /*paMacCore_ConversionQualityHigh:*/

+          value=kRenderQuality_High;

+          break;

+       }

+       ERR_WRAP( AudioUnitSetProperty( *audioUnit,

+                    kAudioUnitProperty_RenderQuality,

+                    kAudioUnitScope_Global,

+                    OUTPUT_ELEMENT,

+                    &value,

+                    sizeof(value) ) );

+    }

+    /* now set the format on the Audio Units. */

+    if( outStreamParams )

+    {

+       desiredFormat.mSampleRate    =sampleRate;

+       desiredFormat.mBytesPerPacket=sizeof(float)*outStreamParams->channelCount;

+       desiredFormat.mBytesPerFrame =sizeof(float)*outStreamParams->channelCount;

+       desiredFormat.mChannelsPerFrame = outStreamParams->channelCount;

+       ERR_WRAP( AudioUnitSetProperty( *audioUnit,

+                            kAudioUnitProperty_StreamFormat,

+                            kAudioUnitScope_Input,

+                            OUTPUT_ELEMENT,

+                            &desiredFormat,

+                            sizeof(AudioStreamBasicDescription) ) );

+    }

+    if( inStreamParams )

+    {

+       AudioStreamBasicDescription sourceFormat;

+       UInt32 size = sizeof( AudioStreamBasicDescription );

+

+       /* keep the sample rate of the device, or we confuse AUHAL */

+       ERR_WRAP( AudioUnitGetProperty( *audioUnit,

+                            kAudioUnitProperty_StreamFormat,

+                            kAudioUnitScope_Input,

+                            INPUT_ELEMENT,

+                            &sourceFormat,

+                            &size ) );

+       desiredFormat.mSampleRate = sourceFormat.mSampleRate;

+       desiredFormat.mBytesPerPacket=sizeof(float)*inStreamParams->channelCount;

+       desiredFormat.mBytesPerFrame =sizeof(float)*inStreamParams->channelCount;

+       desiredFormat.mChannelsPerFrame = inStreamParams->channelCount;

+       ERR_WRAP( AudioUnitSetProperty( *audioUnit,

+                            kAudioUnitProperty_StreamFormat,

+                            kAudioUnitScope_Output,

+                            INPUT_ELEMENT,

+                            &desiredFormat,

+                            sizeof(AudioStreamBasicDescription) ) );

+    }

+    /* set the maximumFramesPerSlice */

+    /* not doing this causes real problems

+       (eg. the callback might not be called). The idea of setting both this

+       and the frames per buffer on the device is that we'll be most likely

+       to actually get the frame size we requested in the callback with the

+       minimum latency. */

+    if( outStreamParams ) {

+       UInt32 size = sizeof( *actualOutputFramesPerBuffer );

+       ERR_WRAP( AudioUnitSetProperty( *audioUnit,

+                            kAudioUnitProperty_MaximumFramesPerSlice,

+                            kAudioUnitScope_Input,

+                            OUTPUT_ELEMENT,

+                            actualOutputFramesPerBuffer,

+                            sizeof(unsigned long) ) );

+       ERR_WRAP( AudioUnitGetProperty( *audioUnit,

+                            kAudioUnitProperty_MaximumFramesPerSlice,

+                            kAudioUnitScope_Global,

+                            OUTPUT_ELEMENT,

+                            actualOutputFramesPerBuffer,

+                            &size ) );

+    }

+    if( inStreamParams ) {

+       /*UInt32 size = sizeof( *actualInputFramesPerBuffer );*/

+       ERR_WRAP( AudioUnitSetProperty( *audioUnit,

+                            kAudioUnitProperty_MaximumFramesPerSlice,

+                            kAudioUnitScope_Output,

+                            INPUT_ELEMENT,

+                            actualInputFramesPerBuffer,

+                            sizeof(unsigned long) ) );

+/* Don't know why this causes problems

+       ERR_WRAP( AudioUnitGetProperty( *audioUnit,

+                            kAudioUnitProperty_MaximumFramesPerSlice,

+                            kAudioUnitScope_Global, //Output,

+                            INPUT_ELEMENT,

+                            actualInputFramesPerBuffer,

+                            &size ) );

+*/

+    }

+

+    /* -- if we have input, we may need to setup an SR converter -- */

+    /* even if we got the sample rate we asked for, we need to do

+       the conversion in case another program changes the underlying SR. */

+    /* FIXME: I think we need to monitor stream and change the converter if the incoming format changes. */

+    if( inStreamParams ) {

+       AudioStreamBasicDescription desiredFormat;

+       AudioStreamBasicDescription sourceFormat;

+       UInt32 sourceSize = sizeof( sourceFormat );

+       bzero( &desiredFormat, sizeof(desiredFormat) );

+       desiredFormat.mSampleRate       = sampleRate;

+       desiredFormat.mFormatID         = kAudioFormatLinearPCM ;

+       desiredFormat.mFormatFlags      = kAudioFormatFlagsNativeFloatPacked;

+       desiredFormat.mFramesPerPacket  = 1;

+       desiredFormat.mBitsPerChannel   = sizeof( float ) * 8;

+       desiredFormat.mBytesPerPacket=sizeof(float)*inStreamParams->channelCount;

+       desiredFormat.mBytesPerFrame =sizeof(float)*inStreamParams->channelCount;

+       desiredFormat.mChannelsPerFrame = inStreamParams->channelCount;

+

+       /* get the source format */

+       ERR_WRAP( AudioUnitGetProperty(

+                         *audioUnit,

+                         kAudioUnitProperty_StreamFormat,

+                         kAudioUnitScope_Output,

+                         INPUT_ELEMENT,

+                         &sourceFormat,

+                         &sourceSize ) );

+

+       if( desiredFormat.mSampleRate != sourceFormat.mSampleRate )

+       {

+          UInt32 value = kAudioConverterQuality_Max;

+          switch( macInputStreamFlags & 0x0700 ) {

+          case 0x0100: /*paMacCore_ConversionQualityMin:*/

+             value=kAudioConverterQuality_Min;

+             break;

+          case 0x0200: /*paMacCore_ConversionQualityLow:*/

+             value=kAudioConverterQuality_Low;

+             break;

+          case 0x0300: /*paMacCore_ConversionQualityMedium:*/

+             value=kAudioConverterQuality_Medium;

+             break;

+          case 0x0400: /*paMacCore_ConversionQualityHigh:*/

+             value=kAudioConverterQuality_High;

+             break;

+          }

+          VDBUG(( "Creating sample rate converter for input"

+                  " to convert from %g to %g\n",

+                  (float)sourceFormat.mSampleRate,

+                  (float)desiredFormat.mSampleRate ) );

+          /* create our converter */

+          ERR_WRAP( AudioConverterNew( 

+                             &sourceFormat,

+                             &desiredFormat,

+                             srConverter ) );

+          /* Set quality */

+          ERR_WRAP( AudioConverterSetProperty(

+                             *srConverter,

+                             kAudioConverterSampleRateConverterQuality,

+                             sizeof( value ),

+                             &value ) );

+       }

+    }

+    /* -- set IOProc (callback) -- */

+    callbackKey = outStreamParams ? kAudioUnitProperty_SetRenderCallback

+                                  : kAudioOutputUnitProperty_SetInputCallback ;

+    rcbs.inputProc = AudioIOProc;

+    rcbs.inputProcRefCon = refCon;

+    ERR_WRAP( AudioUnitSetProperty(

+                               *audioUnit,

+                               callbackKey,

+                               kAudioUnitScope_Output,

+                               outStreamParams ? OUTPUT_ELEMENT : INPUT_ELEMENT,

+                               &rcbs,

+                               sizeof(rcbs)) );

+

+    if( inStreamParams && outStreamParams && *srConverter )

+           ERR_WRAP( AudioUnitSetProperty(

+                               *audioUnit,

+                               kAudioOutputUnitProperty_SetInputCallback,

+                               kAudioUnitScope_Output,

+                               INPUT_ELEMENT,

+                               &rcbs,

+                               sizeof(rcbs)) );

+

+    /* channel mapping. */

+    if(inChannelMap)

+    {

+        UInt32 mapSize = inChannelMapSize *sizeof(SInt32);

+

+        //for each channel of desired input, map the channel from

+        //the device's output channel.

+        ERR_WRAP( AudioUnitSetProperty(*audioUnit,

+                                kAudioOutputUnitProperty_ChannelMap,

+                                kAudioUnitScope_Output,

+                                INPUT_ELEMENT,

+                                inChannelMap,

+                                mapSize));

+    }

+    if(outChannelMap)

+    {

+        UInt32 mapSize = outChannelMapSize *sizeof(SInt32);

+

+        //for each channel of desired output, map the channel from

+        //the device's output channel.

+        ERR_WRAP(AudioUnitSetProperty(*audioUnit,

+                                kAudioOutputUnitProperty_ChannelMap,

+                                kAudioUnitScope_Output,

+                                OUTPUT_ELEMENT,

+                                outChannelMap,

+                                mapSize));

+    }

+    /* initialize the audio unit */

+    ERR_WRAP( AudioUnitInitialize(*audioUnit) );

+

+    if( inStreamParams && outStreamParams )

+       VDBUG( ("Opened device %ld for input and output.\n", *audioDevice ) );

+    else if( inStreamParams )

+       VDBUG( ("Opened device %ld for input.\n", *audioDevice ) );

+    else if( outStreamParams )

+       VDBUG( ("Opened device %ld for output.\n", *audioDevice ) );

+    return paNoError;

+#undef ERR_WRAP

+

+    error:

+       CloseComponent( *audioUnit );

+       *audioUnit = NULL;

+       if( result )

+          return PaMacCore_SetError( result, line, 1 );

+       return paResult;

+}

+

+/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */

+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,

+                           PaStream** s,

+                           const PaStreamParameters *inputParameters,

+                           const PaStreamParameters *outputParameters,

+                           double sampleRate,

+                           unsigned long framesPerBuffer,

+                           PaStreamFlags streamFlags,

+                           PaStreamCallback *streamCallback,

+                           void *userData )

+{

+    PaError result = paNoError;

+    PaMacAUHAL *auhalHostApi = (PaMacAUHAL*)hostApi;

+    PaMacCoreStream *stream = 0;

+    int inputChannelCount, outputChannelCount;

+    PaSampleFormat inputSampleFormat, outputSampleFormat;

+    PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;

+    VVDBUG(("OpenStream(): in chan=%d, in fmt=%ld, out chan=%d, out fmt=%ld SR=%g, FPB=%ld\n",

+                inputParameters  ? inputParameters->channelCount  : -1,

+                inputParameters  ? inputParameters->sampleFormat  : -1,

+                outputParameters ? outputParameters->channelCount : -1,

+                outputParameters ? outputParameters->sampleFormat : -1,

+                (float) sampleRate,

+                framesPerBuffer ));

+    VDBUG( ("Opening Stream.\n") );

+

+    /*These first few bits of code are from paSkeleton with few modifications.*/

+    if( inputParameters )

+    {

+        inputChannelCount = inputParameters->channelCount;

+        inputSampleFormat = inputParameters->sampleFormat;

+

+        /* unless alternate device specification is supported, reject the use of

+            paUseHostApiSpecificDeviceSpecification */

+

+        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )

+            return paInvalidDevice;

+

+        /* check that input device can support inputChannelCount */

+        if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )

+            return paInvalidChannelCount;

+

+        /* Host supports interleaved float32 */

+        hostInputSampleFormat = paFloat32;

+    }

+    else

+    {

+        inputChannelCount = 0;

+        inputSampleFormat = hostInputSampleFormat = paFloat32; /* Surpress 'uninitialised var' warnings. */

+    }

+

+    if( outputParameters )

+    {

+        outputChannelCount = outputParameters->channelCount;

+        outputSampleFormat = outputParameters->sampleFormat;

+        

+        /* unless alternate device specification is supported, reject the use of

+            paUseHostApiSpecificDeviceSpecification */

+

+        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )

+            return paInvalidDevice;

+

+        /* check that output device can support inputChannelCount */

+        if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )

+            return paInvalidChannelCount;

+

+        /* Host supports interleaved float32 */

+        hostOutputSampleFormat = paFloat32;

+    }

+    else

+    {

+        outputChannelCount = 0;

+        outputSampleFormat = hostOutputSampleFormat = paFloat32; /* Surpress 'uninitialized var' warnings. */

+    }

+

+    /* validate platform specific flags */

+    if( (streamFlags & paPlatformSpecificFlags) != 0 )

+        return paInvalidFlag; /* unexpected platform specific flag */

+

+    stream = (PaMacCoreStream*)PaUtil_AllocateMemory( sizeof(PaMacCoreStream) );

+    if( !stream )

+    {

+        result = paInsufficientMemory;

+        goto error;

+    }

+

+    /* If we fail after this point, we my be left in a bad state, with

+       some data structures setup and others not. So, first thing we

+       do is initialize everything so that if we fail, we know what hasn't

+       been touched.

+     */

+

+    stream->inputAudioBufferList.mBuffers[0].mData = NULL;

+    stream->inputRingBuffer.buffer = NULL;

+    bzero( &stream->blio, sizeof( PaMacBlio ) );

+/*

+    stream->blio.inputRingBuffer.buffer = NULL;

+    stream->blio.outputRingBuffer.buffer = NULL;

+    stream->blio.inputSampleFormat = inputParameters?inputParameters->sampleFormat:0;

+    stream->blio.inputSampleSize = computeSampleSizeFromFormat(stream->blio.inputSampleFormat);

+    stream->blio.outputSampleFormat=outputParameters?outputParameters->sampleFormat:0;

+    stream->blio.outputSampleSize = computeSampleSizeFromFormat(stream->blio.outputSampleFormat);

+*/

+    stream->inputSRConverter = NULL;

+    stream->inputUnit = NULL;

+    stream->outputUnit = NULL;

+    stream->inputFramesPerBuffer = 0;

+    stream->outputFramesPerBuffer = 0;

+    stream->bufferProcessorIsInitialized = FALSE;

+

+    /* assert( streamCallback ) ; */ /* only callback mode is implemented */

+    if( streamCallback )

+    {

+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,

+                                        &auhalHostApi->callbackStreamInterface,

+                                        streamCallback, userData );

+    }

+    else

+    {

+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,

+                                        &auhalHostApi->blockingStreamInterface,

+                                        BlioCallback, &stream->blio );

+    }

+

+    PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );

+

+    /* -- handle paFramesPerBufferUnspecified -- */

+    if( framesPerBuffer == paFramesPerBufferUnspecified ) {

+       long requested = 64;

+       if( inputParameters )

+          requested = MAX( requested, inputParameters->suggestedLatency * sampleRate / 2 );

+       if( outputParameters )

+          requested = MAX( requested, outputParameters->suggestedLatency *sampleRate / 2 );

+       VDBUG( ("Block Size unspecified. Based on Latency, the user wants a Block Size near: %ld.\n",

+              requested ) );

+       if( requested <= 64 ) {

+          /*requested a realtively low latency. make sure this is in range of devices */

+          /*try to get the device's min natural buffer size and use that (but no smaller than 64).*/

+          AudioValueRange audioRange;

+          size_t size = sizeof( audioRange );

+          if( inputParameters ) {

+             WARNING( result = AudioDeviceGetProperty( auhalHostApi->devIds[inputParameters->device],

+                                          0,

+                                          false,

+                                          kAudioDevicePropertyBufferFrameSizeRange,

+                                          &size, &audioRange ) );

+             if( result )

+                requested = MAX( requested, audioRange.mMinimum );

+          }

+          if( outputParameters ) {

+             WARNING( result = AudioDeviceGetProperty( auhalHostApi->devIds[outputParameters->device],

+                                          0,

+                                          false,

+                                          kAudioDevicePropertyBufferFrameSizeRange,

+                                          &size, &audioRange ) );

+             if( result )

+                requested = MAX( requested, audioRange.mMinimum );

+          }

+       } else {

+          /* requested a realtively high latency. make sure this is in range of devices */

+          /*try to get the device's max natural buffer size and use that (but no larger than 1024).*/

+          AudioValueRange audioRange;

+          size_t size = sizeof( audioRange );

+          requested = MIN( requested, 1024 );

+          if( inputParameters ) {

+             WARNING( result = AudioDeviceGetProperty( auhalHostApi->devIds[inputParameters->device],

+                                          0,

+                                          false,

+                                          kAudioDevicePropertyBufferFrameSizeRange,

+                                          &size, &audioRange ) );

+             if( result )

+                requested = MIN( requested, audioRange.mMaximum );

+          }

+          if( outputParameters ) {

+             WARNING( result = AudioDeviceGetProperty( auhalHostApi->devIds[outputParameters->device],

+                                          0,

+                                          false,

+                                          kAudioDevicePropertyBufferFrameSizeRange,

+                                          &size, &audioRange ) );

+             if( result )

+                requested = MIN( requested, audioRange.mMaximum );

+          }

+       }

+       /* -- double check ranges -- */

+       if( requested > 1024 ) requested = 1024;

+       if( requested < 64 ) requested = 64;

+       VDBUG(("After querying hardware, setting block size to %ld.\n", requested));

+       framesPerBuffer = requested;

+    }

+

+    /* -- Now we actually open and setup streams. -- */

+    if( inputParameters && outputParameters && outputParameters->device == inputParameters->device )

+    { /* full duplex. One device. */

+       result = OpenAndSetupOneAudioUnit( inputParameters,

+                                          outputParameters,

+                                          framesPerBuffer,

+                                          &(stream->inputFramesPerBuffer),

+                                          &(stream->outputFramesPerBuffer),

+                                          auhalHostApi,

+                                          &(stream->inputUnit),

+                                          &(stream->inputSRConverter),

+                                          &(stream->inputDevice),

+                                          sampleRate,

+                                          stream );

+       stream->outputUnit = stream->inputUnit;

+       stream->outputDevice = stream->inputDevice;

+       if( result != paNoError )

+           goto error;

+    }

+    else

+    { /* full duplex, different devices OR simplex */

+       result = OpenAndSetupOneAudioUnit( NULL,

+                                          outputParameters,

+                                          framesPerBuffer,

+                                          NULL,

+                                          &(stream->outputFramesPerBuffer),

+                                          auhalHostApi,

+                                          &(stream->outputUnit),

+                                          NULL,

+                                          &(stream->outputDevice),

+                                          sampleRate,

+                                          stream );

+       if( result != paNoError )

+           goto error;

+       result = OpenAndSetupOneAudioUnit( inputParameters,

+                                          NULL,

+                                          framesPerBuffer,

+                                          &(stream->inputFramesPerBuffer),

+                                          NULL,

+                                          auhalHostApi,

+                                          &(stream->inputUnit),

+                                          &(stream->inputSRConverter),

+                                          &(stream->inputDevice),

+                                          sampleRate,

+                                          stream );

+       if( result != paNoError )

+           goto error;

+    }

+

+    if( stream->inputUnit ) {

+       const size_t szfl = sizeof(float);

+       /* setup the AudioBufferList used for input */

+       bzero( &stream->inputAudioBufferList, sizeof( AudioBufferList ) );

+       stream->inputAudioBufferList.mNumberBuffers = 1;

+       stream->inputAudioBufferList.mBuffers[0].mNumberChannels

+                 = inputChannelCount;

+       stream->inputAudioBufferList.mBuffers[0].mDataByteSize

+                 = stream->inputFramesPerBuffer*inputChannelCount*szfl;

+       stream->inputAudioBufferList.mBuffers[0].mData

+                 = (float *) calloc(

+                               stream->inputFramesPerBuffer*inputChannelCount,

+                               szfl );

+       if( !stream->inputAudioBufferList.mBuffers[0].mData )

+       {

+          result = paInsufficientMemory;

+          goto error;

+       }

+        

+       /*

+        * If input and output devs are different or we are doing SR conversion,

+        * we also need a

+        * ring buffer to store inpt data while waiting for output

+        * data.

+        */

+       if( (stream->outputUnit && stream->inputUnit != stream->outputUnit)

+           || stream->inputSRConverter )

+       {

+          /* May want the ringSize ot initial position in

+             ring buffer to depend somewhat on sample rate change */

+

+          void *data;

+          long ringSize;

+

+          ringSize = computeRingBufferSize( inputParameters,

+                                            outputParameters,

+                                            stream->inputFramesPerBuffer,

+                                            stream->outputFramesPerBuffer,

+                                            sampleRate );

+          /*ringSize <<= 4; *//*16x bigger, for testing */

+

+

+          /*now, we need to allocate memory for the ring buffer*/

+          data = calloc( ringSize, szfl );

+          if( !data )

+          {

+             result = paInsufficientMemory;

+             goto error;

+          }

+

+          /* now we can initialize the ring buffer */

+          PaUtil_InitializeRingBuffer( &stream->inputRingBuffer,

+                                   ringSize*szfl, data ) ;

+          /* advance the read point a little, so we are reading from the

+             middle of the buffer */

+          if( stream->outputUnit )

+             PaUtil_AdvanceRingBufferWriteIndex( &stream->inputRingBuffer, ringSize*szfl / RING_BUFFER_ADVANCE_DENOMINATOR );

+       }

+    }

+

+    /* -- initialize Blio Buffer Processors -- */

+    if( !streamCallback )

+    {

+       long ringSize;

+

+       ringSize = computeRingBufferSize( inputParameters,

+                                         outputParameters,

+                                         stream->inputFramesPerBuffer,

+                                         stream->outputFramesPerBuffer,

+                                         sampleRate );

+       result = initializeBlioRingBuffers( &stream->blio,

+              inputParameters?inputParameters->sampleFormat:0 ,

+              outputParameters?outputParameters->sampleFormat:0 ,

+              MAX(stream->inputFramesPerBuffer,stream->outputFramesPerBuffer),

+              ringSize,

+              inputParameters?inputChannelCount:0 ,

+              outputParameters?outputChannelCount:0 ) ;

+       if( result != paNoError )

+          goto error;

+    }

+

+    /* -- initialize Buffer Processor -- */

+    {

+       unsigned long maxHostFrames = stream->inputFramesPerBuffer;

+       if( stream->outputFramesPerBuffer > maxHostFrames )

+          maxHostFrames = stream->outputFramesPerBuffer;

+       result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,

+                 inputChannelCount, inputSampleFormat,

+                 hostInputSampleFormat,

+                 outputChannelCount, outputSampleFormat,

+                 hostOutputSampleFormat,

+                 sampleRate,

+                 streamFlags,

+                 framesPerBuffer,

+                 /* If sample rate conversion takes place, the buffer size

+                    will not be known. */

+                 maxHostFrames,

+                 stream->inputSRConverter

+                              ? paUtilUnknownHostBufferSize

+                              : paUtilBoundedHostBufferSize,

+                 streamCallback ? streamCallback : BlioCallback,

+                 streamCallback ? userData : &stream->blio );

+       if( result != paNoError )

+           goto error;

+    }

+    stream->bufferProcessorIsInitialized = TRUE;

+

+    /*

+        IMPLEMENT ME: initialise the following fields with estimated or actual

+        values.

+        I think this is okay the way it is br 12/1/05

+        maybe need to change input latency estimate if IO devs differ

+    */

+    stream->streamRepresentation.streamInfo.inputLatency =

+            PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor)/sampleRate;

+    stream->streamRepresentation.streamInfo.outputLatency =

+            PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor)/sampleRate;

+    stream->streamRepresentation.streamInfo.sampleRate = sampleRate;

+

+    stream->sampleRate  = sampleRate;

+    stream->outDeviceSampleRate = 0;

+    if( stream->outputUnit ) {

+       Float64 rate;

+       UInt32 size = sizeof( rate );

+       result = ERR( AudioDeviceGetProperty( stream->outputDevice,

+                                    0,

+                                    FALSE,

+                                    kAudioDevicePropertyNominalSampleRate,

+                                    &size, &rate ) );

+       if( result )

+          goto error;

+       stream->outDeviceSampleRate = rate;

+    }

+    stream->inDeviceSampleRate = 0;

+    if( stream->inputUnit ) {

+       Float64 rate;

+       UInt32 size = sizeof( rate );

+       result = ERR( AudioDeviceGetProperty( stream->inputDevice,

+                                    0,

+                                    TRUE,

+                                    kAudioDevicePropertyNominalSampleRate,

+                                    &size, &rate ) );

+       if( result )

+          goto error;

+       stream->inDeviceSampleRate = rate;

+    }

+    stream->userInChan  = inputChannelCount;

+    stream->userOutChan = outputChannelCount;

+

+    stream->isTimeSet   = FALSE;

+    stream->state = STOPPED;

+    stream->xrunFlags = 0;

+

+    *s = (PaStream*)stream;

+

+    return result;

+

+error:

+    CloseStream( stream );

+    return result;

+}

+

+PaTime GetStreamTime( PaStream *s )

+{

+   /* FIXME: I am not at all sure this timing info stuff is right.

+             patest_sine_time reports negative latencies, which is wierd.*/

+    PaMacCoreStream *stream = (PaMacCoreStream*)s;

+    AudioTimeStamp timeStamp;

+

+    VVDBUG(("GetStreamTime()\n"));

+

+    if ( !stream->isTimeSet )

+        return (PaTime)0;

+

+    if ( stream->outputDevice ) {

+        AudioDeviceGetCurrentTime( stream->outputDevice, &timeStamp);

+        return (PaTime)(timeStamp.mSampleTime - stream->startTime.mSampleTime)/stream->outDeviceSampleRate;

+    } else if ( stream->inputDevice ) {

+        AudioDeviceGetCurrentTime( stream->inputDevice, &timeStamp);

+    return (PaTime)(timeStamp.mSampleTime - stream->startTime.mSampleTime)/stream->inDeviceSampleRate;

+    } else {

+        return (PaTime)0;

+    }

+}

+

+static void setStreamStartTime( PaStream *stream )

+{

+   /* FIXME: I am not at all sure this timing info stuff is right.

+             patest_sine_time reports negative latencies, which is wierd.*/

+   PaMacCoreStream *s = (PaMacCoreStream *) stream;

+   VVDBUG(("setStreamStartTime()\n"));

+   if( s->outputDevice )

+      AudioDeviceGetCurrentTime( s->outputDevice, &s->startTime);

+   else if( s->inputDevice )

+      AudioDeviceGetCurrentTime( s->inputDevice, &s->startTime);

+   else

+      bzero( &s->startTime, sizeof( s->startTime ) );

+

+   //FIXME: we need a memory barier here

+

+   s->isTimeSet = TRUE;

+}

+

+

+static PaTime TimeStampToSecs(PaMacCoreStream *stream, const AudioTimeStamp* timeStamp)

+{

+    VVDBUG(("TimeStampToSecs()\n"));

+    //printf( "ATS: %lu, %g, %g\n", timeStamp->mFlags, timeStamp->mSampleTime, timeStamp->mRateScalar );

+    if (timeStamp->mFlags & kAudioTimeStampSampleTimeValid)

+        return (timeStamp->mSampleTime / stream->sampleRate);

+    else

+        return 0;

+}

+

+#define RING_BUFFER_EMPTY (1000)

+

+static OSStatus ringBufferIOProc( AudioConverterRef inAudioConverter, 

+                             UInt32*ioDataSize, 

+                             void** outData, 

+                             void*inUserData )

+{

+   void *dummyData;

+   long dummySize;

+   PaUtilRingBuffer *rb = (PaUtilRingBuffer *) inUserData;

+

+   VVDBUG(("ringBufferIOProc()\n"));

+

+   assert( sizeof( UInt32 ) == sizeof( long ) );

+   if( PaUtil_GetRingBufferReadAvailable( rb ) == 0 ) {

+      *outData = NULL;

+      *ioDataSize = 0;

+      return RING_BUFFER_EMPTY;

+   }

+   PaUtil_GetRingBufferReadRegions( rb, *ioDataSize,

+                                    outData, (long *)ioDataSize, 

+                                    &dummyData, &dummySize );

+      

+   assert( *ioDataSize );

+   PaUtil_AdvanceRingBufferReadIndex( rb, *ioDataSize );

+

+   return noErr;

+}

+

+/*

+ * Called by the AudioUnit API to process audio from the sound card.

+ * This is where the magic happens.

+ */

+/* FEEDBACK: there is a lot of redundant code here because of how all the cases differ. This makes it hard to maintain, so if there are suggestinos for cleaning it up, I'm all ears. */

+static OSStatus AudioIOProc( void *inRefCon,

+                               AudioUnitRenderActionFlags *ioActionFlags,

+                               const AudioTimeStamp *inTimeStamp,

+                               UInt32 inBusNumber,

+                               UInt32 inNumberFrames,

+                               AudioBufferList *ioData )

+{

+   unsigned long framesProcessed     = 0;

+   PaStreamCallbackTimeInfo timeInfo = {0,0,0};

+   PaMacCoreStream *stream           = (PaMacCoreStream*)inRefCon;

+   const bool isRender               = inBusNumber == OUTPUT_ELEMENT;

+   int callbackResult                = paContinue ;

+

+   VVDBUG(("AudioIOProc()\n"));

+

+   PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );

+

+   /* -----------------------------------------------------------------*\

+      This output may be useful for debugging,

+      But printing durring the callback is a bad enough idea that

+      this is not enabled by enableing the usual debugging calls.

+   \* -----------------------------------------------------------------*/

+   /*

+   static int renderCount = 0;

+   static int inputCount = 0;

+   printf( "-------------------  starting reder/input\n" );

+   if( isRender )

+      printf("Render callback (%d):\t", ++renderCount);

+   else

+      printf("Input callback  (%d):\t", ++inputCount);

+   printf( "Call totals: %d (input), %d (render)\n", inputCount, renderCount );

+

+   printf( "--- inBusNumber: %lu\n", inBusNumber );

+   printf( "--- inNumberFrames: %lu\n", inNumberFrames );

+   printf( "--- %x ioData\n", (unsigned) ioData );

+   if( ioData )

+   {

+      int i=0;

+      printf( "--- ioData.mNumBuffers %lu: \n", ioData->mNumberBuffers );

+      for( i=0; i<ioData->mNumberBuffers; ++i )

+         printf( "--- ioData buffer %d size: %lu.\n", i, ioData->mBuffers[i].mDataByteSize );

+   }

+      ----------------------------------------------------------------- */

+

+   if( !stream->isTimeSet )

+      setStreamStartTime( stream );

+

+   if( isRender ) {

+      AudioTimeStamp currentTime;

+      timeInfo.outputBufferDacTime = TimeStampToSecs(stream, inTimeStamp);

+      AudioDeviceGetCurrentTime(stream->outputDevice, &currentTime);

+      timeInfo.currentTime = TimeStampToSecs(stream, &currentTime);

+   }

+   if( isRender && stream->inputUnit == stream->outputUnit )

+      timeInfo.inputBufferAdcTime = TimeStampToSecs(stream, inTimeStamp);

+   if( !isRender ) {

+      AudioTimeStamp currentTime;

+      timeInfo.inputBufferAdcTime = TimeStampToSecs(stream, inTimeStamp);

+      AudioDeviceGetCurrentTime(stream->inputDevice, &currentTime);

+      timeInfo.currentTime = TimeStampToSecs(stream, &currentTime);

+   }

+

+   //printf( "---%g, %g, %g\n", timeInfo.inputBufferAdcTime, timeInfo.currentTime, timeInfo.outputBufferDacTime );

+

+   if( isRender && stream->inputUnit == stream->outputUnit

+                && !stream->inputSRConverter )

+   {

+      /* --------- Full Duplex, One Device, no SR Conversion -------

+       *

+       * This is the lowest latency case, and also the simplest.

+       * Input data and output data are available at the same time.

+       * we do not use the input SR converter or the input ring buffer.

+       *

+       */

+      OSErr err = 0;

+      unsigned long frames;

+

+      /* -- start processing -- */

+      PaUtil_BeginBufferProcessing( &(stream->bufferProcessor),

+                                    &timeInfo,

+                                    stream->xrunFlags );

+      stream->xrunFlags = 0;

+

+      /* -- compute frames. do some checks -- */

+      assert( ioData->mNumberBuffers == 1 );

+      assert( ioData->mBuffers[0].mNumberChannels == stream->userOutChan );

+      frames = ioData->mBuffers[0].mDataByteSize;

+      frames /= sizeof( float ) * ioData->mBuffers[0].mNumberChannels;

+      /* -- copy and process input data -- */

+      err= AudioUnitRender(stream->inputUnit,

+                    ioActionFlags,

+                    inTimeStamp,

+                    INPUT_ELEMENT,

+                    inNumberFrames,

+                    &stream->inputAudioBufferList );

+      /* FEEDBACK: I'm not sure what to do when this call fails */

+      assert( !err );

+

+      PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames );

+      PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),

+                          0,

+                          stream->inputAudioBufferList.mBuffers[0].mData,

+                          stream->inputAudioBufferList.mBuffers[0].mNumberChannels);

+      /* -- Copy and process output data -- */

+      PaUtil_SetOutputFrameCount( &(stream->bufferProcessor), frames );

+      PaUtil_SetInterleavedOutputChannels( &(stream->bufferProcessor),

+                                        0,

+                                        ioData->mBuffers[0].mData,

+                                        ioData->mBuffers[0].mNumberChannels);

+      /* -- complete processing -- */

+      framesProcessed =

+                 PaUtil_EndBufferProcessing( &(stream->bufferProcessor),

+                                             &callbackResult );

+   }

+   else if( isRender )

+   {

+      /* -------- Output Side of Full Duplex (Separate Devices or SR Conversion)

+       *       -- OR Simplex Output

+       *

+       * This case handles output data as in the full duplex case,

+       * and, if there is input data, reads it off the ring buffer 

+       * and into the PA buffer processor. If sample rate conversion

+       * is required on input, that is done here as well.

+       */

+      unsigned long frames;

+

+      /* Sometimes, when stopping a duplex stream we get erroneous

+         xrun flags, so if this is our last run, clear the flags. */

+      int xrunFlags = stream->xrunFlags;

+/*

+      if( xrunFlags & paInputUnderflow )

+         printf( "input underflow.\n" );

+      if( xrunFlags & paInputOverflow )

+         printf( "input overflow.\n" );

+*/

+      if( stream->state == STOPPING || stream->state == CALLBACK_STOPPED )

+         xrunFlags = 0;

+

+      /* -- start processing -- */

+      PaUtil_BeginBufferProcessing( &(stream->bufferProcessor),

+                                    &timeInfo,

+                                    xrunFlags );

+      stream->xrunFlags = 0; /* FEEDBACK: we only send flags to Buf Proc once */

+

+      /* -- Copy and process output data -- */

+      assert( ioData->mNumberBuffers == 1 );

+      frames = ioData->mBuffers[0].mDataByteSize;

+      frames /= sizeof( float ) * ioData->mBuffers[0].mNumberChannels;

+      assert( ioData->mBuffers[0].mNumberChannels == stream->userOutChan );

+      PaUtil_SetOutputFrameCount( &(stream->bufferProcessor), frames );

+      PaUtil_SetInterleavedOutputChannels( &(stream->bufferProcessor),

+                                     0,

+                                     ioData->mBuffers[0].mData,

+                                     ioData->mBuffers[0].mNumberChannels);

+

+      /* -- copy and process input data, and complete processing -- */

+      if( stream->inputUnit ) {

+         const int flsz = sizeof( float );

+         /* Here, we read the data out of the ring buffer, through the

+            audio converter. */

+         int inChan = stream->inputAudioBufferList.mBuffers[0].mNumberChannels;

+         if( stream->inputSRConverter )

+         {

+               OSStatus err;

+               UInt32 size;

+               float data[ inChan * frames ];

+               size = sizeof( data );

+               err = AudioConverterFillBuffer( 

+                             stream->inputSRConverter,

+                             ringBufferIOProc,

+                             &stream->inputRingBuffer,

+                             &size,

+                             (void *)&data );

+               if( err == RING_BUFFER_EMPTY )

+               { /*the ring buffer callback underflowed */

+                  err = 0;

+                  bzero( ((char *)data) + size, sizeof(data)-size );

+                  stream->xrunFlags |= paInputUnderflow;

+               }

+               ERR( err );

+               assert( !err );

+               

+               PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames );

+               PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),

+                                   0,

+                                   data,

+                                   inChan );

+               framesProcessed =

+                    PaUtil_EndBufferProcessing( &(stream->bufferProcessor),

+                                                &callbackResult );

+         }

+         else

+         {

+            /* Without the AudioConverter is actually a bit more complex

+               because we have to do a little buffer processing that the

+               AudioConverter would otherwise handle for us. */

+            void *data1, *data2;

+            long size1, size2;

+            PaUtil_GetRingBufferReadRegions( &stream->inputRingBuffer,

+                                             inChan*frames*flsz,

+                                             &data1, &size1,

+                                             &data2, &size2 );

+            if( size1 / ( flsz * inChan ) == frames ) {

+               /* simplest case: all in first buffer */

+               PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames );

+               PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),

+                                   0,

+                                   data1,

+                                   inChan );

+               framesProcessed =

+                    PaUtil_EndBufferProcessing( &(stream->bufferProcessor),

+                                                &callbackResult );

+               PaUtil_AdvanceRingBufferReadIndex(&stream->inputRingBuffer, size1 );

+            } else if( ( size1 + size2 ) / ( flsz * inChan ) < frames ) {

+               /*we underflowed. take what data we can, zero the rest.*/

+               float data[frames*inChan];

+               if( size1 )

+                  memcpy( data, data1, size1 );

+               if( size2 )

+                  memcpy( data+size1, data2, size2 );

+               bzero( data+size1+size2, frames*flsz*inChan - size1 - size2 );

+

+               PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames );

+               PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),

+                                   0,

+                                   data,

+                                   inChan );

+               framesProcessed =

+                    PaUtil_EndBufferProcessing( &(stream->bufferProcessor),

+                                                &callbackResult );

+               PaUtil_AdvanceRingBufferReadIndex( &stream->inputRingBuffer,

+                                                  size1+size2 );

+               /* flag underflow */

+               stream->xrunFlags |= paInputUnderflow;

+            } else {

+               /*we got all the data, but split between buffers*/

+               PaUtil_SetInputFrameCount( &(stream->bufferProcessor),

+                                          size1 / ( flsz * inChan ) );

+               PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),

+                                   0,

+                                   data1,

+                                   inChan );

+               PaUtil_Set2ndInputFrameCount( &(stream->bufferProcessor),

+                                             size2 / ( flsz * inChan ) );

+               PaUtil_Set2ndInterleavedInputChannels( &(stream->bufferProcessor),

+                                   0,

+                                   data2,

+                                   inChan );

+               framesProcessed =

+                    PaUtil_EndBufferProcessing( &(stream->bufferProcessor),

+                                                &callbackResult );

+               PaUtil_AdvanceRingBufferReadIndex(&stream->inputRingBuffer, size1+size2 );

+            }

+         }

+      } else {

+         framesProcessed =

+                 PaUtil_EndBufferProcessing( &(stream->bufferProcessor),

+                                             &callbackResult );

+      }

+

+   }

+   else

+   {

+      /* ------------------ Input

+       *

+       * First, we read off the audio data and put it in the ring buffer.

+       * if this is an input-only stream, we need to process it more,

+       * otherwise, we let the output case deal with it.

+       */

+      OSErr err = 0;

+      int chan = stream->inputAudioBufferList.mBuffers[0].mNumberChannels ;

+      /* FIXME: looping here may not actually be necessary, but it was something I tried in testing. */

+      do {

+         err= AudioUnitRender(stream->inputUnit,

+                 ioActionFlags,

+                 inTimeStamp,

+                 INPUT_ELEMENT,

+                 inNumberFrames,

+                 &stream->inputAudioBufferList );

+         if( err == -10874 )

+            inNumberFrames /= 2;

+      } while( err == -10874 && inNumberFrames > 1 );

+      /* FEEDBACK: I'm not sure what to do when this call fails */

+      ERR( err );

+      assert( !err );

+      if( stream->inputSRConverter || stream->outputUnit )

+      {

+         /* If this is duplex or we use a converter, put the data

+            into the ring buffer. */

+         long bytesIn, bytesOut;

+         bytesIn = sizeof( float ) * inNumberFrames * chan;

+         bytesOut = PaUtil_WriteRingBuffer( &stream->inputRingBuffer,

+                                            stream->inputAudioBufferList.mBuffers[0].mData,

+                                            bytesIn );

+         if( bytesIn != bytesOut )

+            stream->xrunFlags |= paInputOverflow ;

+      }

+      else

+      {

+         /* for simplex input w/o SR conversion,

+            just pop the data into the buffer processor.*/

+         PaUtil_BeginBufferProcessing( &(stream->bufferProcessor),

+                              &timeInfo,

+                              stream->xrunFlags );

+         stream->xrunFlags = 0;

+

+         PaUtil_SetInputFrameCount( &(stream->bufferProcessor), inNumberFrames);

+         PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),

+                             0,

+                             stream->inputAudioBufferList.mBuffers[0].mData,

+                             chan );

+         framesProcessed =

+              PaUtil_EndBufferProcessing( &(stream->bufferProcessor),

+                                          &callbackResult );

+      }

+      if( !stream->outputUnit && stream->inputSRConverter )

+      {

+         /* ------------------ Simplex Input w/ SR Conversion

+          *

+          * if this is a simplex input stream, we need to read off the buffer,

+          * do our sample rate conversion and pass the results to the buffer

+          * processor.

+          * The logic here is complicated somewhat by the fact that we don't

+          * know how much data is available, so we loop on reasonably sized

+          * chunks, and let the BufferProcessor deal with the rest.

+          *

+          */

+         /*This might be too big or small depending on SR conversion*/

+         float data[ chan * inNumberFrames ];

+         OSStatus err;

+         do

+         { /*Run the buffer processor until we are out of data*/

+            UInt32 size;

+            long f;

+

+            size = sizeof( data );

+            err = AudioConverterFillBuffer( 

+                          stream->inputSRConverter,

+                          ringBufferIOProc,

+                          &stream->inputRingBuffer,

+                          &size,

+                          (void *)data );

+            if( err != RING_BUFFER_EMPTY )

+               ERR( err );

+            assert( err == 0 || err == RING_BUFFER_EMPTY );

+

+            f = size / ( chan * sizeof(float) );

+            PaUtil_SetInputFrameCount( &(stream->bufferProcessor), f );

+            if( f )

+            {

+               PaUtil_BeginBufferProcessing( &(stream->bufferProcessor),

+                                             &timeInfo,

+                                             stream->xrunFlags );

+               stream->xrunFlags = 0;

+

+               PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),

+                                0,

+                                data,

+                                chan );

+               framesProcessed =

+                    PaUtil_EndBufferProcessing( &(stream->bufferProcessor),

+                                                &callbackResult );

+            }

+         } while( callbackResult == paContinue && !err );

+      }

+   }

+

+   switch( callbackResult )

+   {

+   case paContinue: break;

+   case paComplete:

+   case paAbort:

+      stream->isTimeSet = FALSE;

+      stream->state = CALLBACK_STOPPED ;

+      if( stream->outputUnit )

+         AudioOutputUnitStop(stream->outputUnit);

+      if( stream->inputUnit )

+         AudioOutputUnitStop(stream->inputUnit);

+      break;

+   }

+

+   PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );

+   return noErr;

+}

+

+

+/*

+    When CloseStream() is called, the multi-api layer ensures that

+    the stream has already been stopped or aborted.

+*/

+static PaError CloseStream( PaStream* s )

+{

+    /* This may be called from a failed OpenStream.

+       Therefore, each piece of info is treated seperately. */

+    PaError result = paNoError;

+    PaMacCoreStream *stream = (PaMacCoreStream*)s;

+

+    VVDBUG(("CloseStream()\n"));

+    VDBUG( ( "Closing stream.\n" ) );

+

+    if( stream ) {

+       if( stream->outputUnit && stream->outputUnit != stream->inputUnit ) {

+          AudioUnitUninitialize( stream->outputUnit );

+          CloseComponent( stream->outputUnit );

+       }

+       stream->outputUnit = NULL;

+       if( stream->inputUnit )

+       {

+          AudioUnitUninitialize( stream->inputUnit );

+          CloseComponent( stream->inputUnit );

+          stream->inputUnit = NULL;

+       }

+       if( stream->inputRingBuffer.buffer )

+          free( (void *) stream->inputRingBuffer.buffer );

+       stream->inputRingBuffer.buffer = NULL;

+       /*TODO: is there more that needs to be done on error

+               from AudioConverterDispose?*/

+       if( stream->inputSRConverter )

+          ERR( AudioConverterDispose( stream->inputSRConverter ) );

+       stream->inputSRConverter = NULL;

+       if( stream->inputAudioBufferList.mBuffers[0].mData )

+          free( stream->inputAudioBufferList.mBuffers[0].mData );

+       stream->inputAudioBufferList.mBuffers[0].mData = NULL;

+

+       result = destroyBlioRingBuffers( &stream->blio );

+       if( result )

+          return result;

+       if( stream->bufferProcessorIsInitialized )

+          PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );

+       PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );

+       PaUtil_FreeMemory( stream );

+    }

+

+    return result;

+}

+

+

+static PaError StartStream( PaStream *s )

+{

+    PaMacCoreStream *stream = (PaMacCoreStream*)s;

+    OSErr result = noErr;

+    VVDBUG(("StartStream()\n"));

+    VDBUG( ( "Starting stream.\n" ) );

+

+#define ERR_WRAP(mac_err) do { result = mac_err ; if ( result != noErr ) return ERR(result) ; } while(0)

+

+    /*FIXME: maybe want to do this on close/abort for faster start? */

+    PaUtil_ResetBufferProcessor( &stream->bufferProcessor );

+    if(  stream->inputSRConverter )

+       ERR_WRAP( AudioConverterReset( stream->inputSRConverter ) );

+

+    /* -- start -- */

+    stream->state = ACTIVE;

+    if( stream->inputUnit ) {

+       ERR_WRAP( AudioOutputUnitStart(stream->inputUnit) );

+    }

+    if( stream->outputUnit && stream->outputUnit != stream->inputUnit ) {

+       ERR_WRAP( AudioOutputUnitStart(stream->outputUnit) );

+    }

+

+    //setStreamStartTime( stream );

+    //stream->isTimeSet = TRUE;

+

+    return paNoError;

+#undef ERR_WRAP

+}

+

+// it's not clear from appl's docs that this really waits

+// until all data is flushed.

+static ComponentResult BlockWhileAudioUnitIsRunning( AudioUnit audioUnit, AudioUnitElement element )

+{

+    Boolean isRunning = 1;

+    while( isRunning ) {

+       UInt32 s = sizeof( isRunning );

+       ComponentResult err = AudioUnitGetProperty( audioUnit, kAudioOutputUnitProperty_IsRunning, kAudioUnitScope_Global, element,  &isRunning, &s );

+       if( err )

+          return err;

+       Pa_Sleep( 100 );

+    }

+    return noErr;

+}

+

+static PaError StopStream( PaStream *s )

+{

+    PaMacCoreStream *stream = (PaMacCoreStream*)s;

+    OSErr result = noErr;

+    PaError paErr;

+    VVDBUG(("StopStream()\n"));

+

+    VDBUG( ("Waiting for BLIO.\n") );

+    waitUntilBlioWriteBufferIsFlushed( &stream->blio );

+    VDBUG( ( "Stopping stream.\n" ) );

+

+    stream->isTimeSet = FALSE;

+    stream->state = STOPPING;

+

+#define ERR_WRAP(mac_err) do { result = mac_err ; if ( result != noErr ) return ERR(result) ; } while(0)

+    /* -- stop and reset -- */

+    if( stream->inputUnit == stream->outputUnit && stream->inputUnit )

+    {

+       ERR_WRAP( AudioOutputUnitStop(stream->inputUnit) );

+       ERR_WRAP( BlockWhileAudioUnitIsRunning(stream->inputUnit,0) );

+       ERR_WRAP( BlockWhileAudioUnitIsRunning(stream->inputUnit,1) );

+       ERR_WRAP( AudioUnitReset(stream->inputUnit, kAudioUnitScope_Global, 1) );

+       ERR_WRAP( AudioUnitReset(stream->inputUnit, kAudioUnitScope_Global, 0) );

+    }

+    else

+    {

+       if( stream->inputUnit )

+       {

+          ERR_WRAP(AudioOutputUnitStop(stream->inputUnit) );

+          ERR_WRAP( BlockWhileAudioUnitIsRunning(stream->inputUnit,1) );

+          ERR_WRAP(AudioUnitReset(stream->inputUnit,kAudioUnitScope_Global,1));

+       }

+       if( stream->outputUnit )

+       {

+          ERR_WRAP(AudioOutputUnitStop(stream->outputUnit));

+          ERR_WRAP( BlockWhileAudioUnitIsRunning(stream->outputUnit,0) );

+          ERR_WRAP(AudioUnitReset(stream->outputUnit,kAudioUnitScope_Global,0));

+       }

+    }

+    if( stream->inputRingBuffer.buffer ) {

+       PaUtil_FlushRingBuffer( &stream->inputRingBuffer );

+       bzero( (void *)stream->inputRingBuffer.buffer,

+              stream->inputRingBuffer.bufferSize );

+       /* advance the write point a little, so we are reading from the

+          middle of the buffer. We'll need extra at the end because

+          testing has shown that this helps. */

+       if( stream->outputUnit )

+          PaUtil_AdvanceRingBufferWriteIndex( &stream->inputRingBuffer,

+                                              stream->inputRingBuffer.bufferSize

+                                              / RING_BUFFER_ADVANCE_DENOMINATOR );

+    }

+

+    stream->xrunFlags = 0;

+    stream->state = STOPPED;

+

+    paErr = resetBlioRingBuffers( &stream->blio );

+    if( paErr )

+       return paErr;

+

+/*

+    //stream->isTimeSet = FALSE;

+*/

+

+    VDBUG( ( "Stream Stopped.\n" ) );

+    return paNoError;

+#undef ERR_WRAP

+}

+

+static PaError AbortStream( PaStream *s )

+{

+    VVDBUG(("AbortStream()->StopStream()\n"));

+    VDBUG( ( "Aborting stream.\n" ) );

+    /* We have nothing faster than StopStream. */

+    return StopStream(s);

+}

+

+

+static PaError IsStreamStopped( PaStream *s )

+{

+    PaMacCoreStream *stream = (PaMacCoreStream*)s;

+    VVDBUG(("IsStreamStopped()\n"));

+

+    return stream->state == STOPPED ? 1 : 0;

+}

+

+

+static PaError IsStreamActive( PaStream *s )

+{

+    PaMacCoreStream *stream = (PaMacCoreStream*)s;

+    VVDBUG(("IsStreamActive()\n"));

+    return ( stream->state == ACTIVE || stream->state == STOPPING );

+}

+

+

+static double GetStreamCpuLoad( PaStream* s )

+{

+    PaMacCoreStream *stream = (PaMacCoreStream*)s;

+    VVDBUG(("GetStreamCpuLoad()\n"));

+

+    return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );

+}

diff --git a/src/engine/external/portaudio/pa_mac_core.h b/src/engine/external/portaudio/pa_mac_core.h
new file mode 100644
index 00000000..0782465e
--- /dev/null
+++ b/src/engine/external/portaudio/pa_mac_core.h
@@ -0,0 +1,171 @@
+#ifndef PA_MAC_CORE_H

+#define PA_MAC_CORE_H

+/*

+ * PortAudio Portable Real-Time Audio Library

+ * Macintosh Core Audio specific extensions

+ * portaudio.h should be included before this file.

+ *

+ * Copyright (c) 2005-2006 Bjorn Roche

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+#include <AudioUnit/AudioUnit.h>

+//#include <AudioToolbox/AudioToolbox.h>

+

+#ifdef __cplusplus

+extern "C" {

+#endif

+

+

+/*

+ * A pointer to a paMacCoreStreamInfo may be passed as

+ * the hostApiSpecificStreamInfo in the PaStreamParameters struct

+ * when opening a stream or querying the format. Use NULL, for the

+ * defaults. Note that for duplex streams, flags for input and output

+ * should be the same or behaviour is undefined.

+ */

+typedef struct

+{

+    unsigned long size;           /**size of whole structure including this header */

+    PaHostApiTypeId hostApiType;  /**host API for which this data is intended */

+    unsigned long version;        /**structure version */

+    unsigned long flags;          /* flags to modify behaviour */

+    SInt32 const * channelMap;    /* Channel map for HAL channel mapping , if not needed, use NULL;*/ 

+    unsigned long channelMapSize; /* Channel map size for HAL channel mapping , if not needed, use 0;*/ 

+} PaMacCoreStreamInfo;

+

+/*

+ * Functions

+ */

+

+

+/* Use this function to initialize a paMacCoreStreamInfo struct

+ * using the requested flags. Note that channel mapping is turned

+ * off after a call to this function.

+ * @param data The datastructure to initialize

+ * @param flags The flags to initialize the datastructure with.

+*/

+void PaMacCore_SetupStreamInfo( PaMacCoreStreamInfo *data, unsigned long flags );

+

+/* call this after pa_SetupMacCoreStreamInfo to use channel mapping as described in notes.txt.

+ * @param data The stream info structure to assign a channel mapping to

+ * @param channelMap The channel map array, as described in notes.txt. This array pointer will be used directly (ie the underlying data will not be copied), so the caller should not free the array until after the stream has been opened.

+ * @param channelMapSize The size of the channel map array.

+ */

+void PaMacCore_SetupChannelMap( PaMacCoreStreamInfo *data, const SInt32 * const channelMap, unsigned long channelMapSize );

+

+/*

+ * Retrieve the AudioDeviceID of the input device assigned to an open stream

+ *

+ * @param s The stream to query.

+ *

+ * @return A valid AudioDeviceID, or NULL if an error occurred.

+ */

+AudioDeviceID PaMacCore_GetStreamInputDevice( PaStream* s );

+ 

+/*

+ * Retrieve the AudioDeviceID of the output device assigned to an open stream

+ *

+ * @param s The stream to query.

+ *

+ * @return A valid AudioDeviceID, or NULL if an error occurred.

+ */

+AudioDeviceID PaMacCore_GetStreamOutputDevice( PaStream* s );

+

+/*

+ * Returns a statically allocated string with the device's name

+ * for the given channel. NULL will be returned on failure.

+ *

+ * This function's implemenation is not complete!

+ *

+ * @param device The PortAudio device index.

+ * @param channel The channel number who's name is requested.

+ * @return a statically allocated string with the name of the device.

+ *         Because this string is statically allocated, it must be

+ *         coppied if it is to be saved and used by the user after

+ *         another call to this function.

+ *

+ */

+const char *PaMacCore_GetChannelName( int device, int channelIndex, bool input );

+

+/*

+ * Flags

+ */

+

+/*

+ * The following flags alter the behaviour of PA on the mac platform.

+ * they can be ORed together. These should work both for opening and

+ * checking a device.

+ */

+

+/* Allows PortAudio to change things like the device's frame size,

+ * which allows for much lower latency, but might disrupt the device

+ * if other programs are using it, even when you are just Querying

+ * the device. */

+#define paMacCoreChangeDeviceParameters (0x01)

+

+/* In combination with the above flag,

+ * causes the stream opening to fail, unless the exact sample rates

+ * are supported by the device. */

+#define paMacCoreFailIfConversionRequired (0x02)

+

+/* These flags set the SR conversion quality, if required. The wierd ordering

+ * allows Maximum Quality to be the default.*/

+#define paMacCoreConversionQualityMin    (0x0100)

+#define paMacCoreConversionQualityMedium (0x0200)

+#define paMacCoreConversionQualityLow    (0x0300)

+#define paMacCoreConversionQualityHigh   (0x0400)

+#define paMacCoreConversionQualityMax    (0x0000)

+

+/*

+ * Here are some "preset" combinations of flags (above) to get to some

+ * common configurations. THIS IS OVERKILL, but if more flags are added

+ * it won't be.

+ */

+

+/*This is the default setting: do as much sample rate conversion as possible

+ * and as little mucking with the device as possible. */

+#define paMacCorePlayNice                    (0x00)

+/*This setting is tuned for pro audio apps. It allows SR conversion on input

+  and output, but it tries to set the appropriate SR on the device.*/

+#define paMacCorePro                         (0x01)

+/*This is a setting to minimize CPU usage and still play nice.*/

+#define paMacCoreMinimizeCPUButPlayNice      (0x0100)

+/*This is a setting to minimize CPU usage, even if that means interrupting the device. */

+#define paMacCoreMinimizeCPU                 (0x0101)

+

+

+#ifdef __cplusplus

+}

+#endif /* __cplusplus */

+

+#endif /* PA_MAC_CORE_H */

diff --git a/src/engine/external/portaudio/pa_mac_core_blocking.c b/src/engine/external/portaudio/pa_mac_core_blocking.c
new file mode 100644
index 00000000..3b81389d
--- /dev/null
+++ b/src/engine/external/portaudio/pa_mac_core_blocking.c
@@ -0,0 +1,564 @@
+/*

+ * Implementation of the PortAudio API for Apple AUHAL

+ *

+ * PortAudio Portable Real-Time Audio Library

+ * Latest Version at: http://www.portaudio.com

+ *

+ * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.

+ * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)

+ *

+ * Dominic's code was based on code by Phil Burk, Darren Gibbs,

+ * Gord Peters, Stephane Letz, and Greg Pfiel.

+ *

+ * The following people also deserve acknowledgements:

+ *

+ * Olivier Tristan for feedback and testing

+ * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O

+ * interface.

+ * 

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/**

+ @file

+ @ingroup hostaip_src

+

+ This file contains the implementation

+ required for blocking I/O. It is separated from pa_mac_core.c simply to ease

+ development.

+*/

+

+#include "pa_mac_core_blocking.h"

+#include "pa_mac_core_internal.h"

+#include <assert.h>

+#ifdef MOSX_USE_NON_ATOMIC_FLAG_BITS

+# define OSAtomicOr32( a, b ) ( (*(b)) |= (a) )

+# define OSAtomicAnd32( a, b ) ( (*(b)) &= (a) )

+#else

+# include <libkern/OSAtomic.h>

+#endif

+

+/*

+ * This fnuction determines the size of a particular sample format.

+ * if the format is not recognized, this returns zero.

+ */

+static size_t computeSampleSizeFromFormat( PaSampleFormat format )

+{

+   switch( format ) {

+   case paFloat32: return 4;

+   case paInt32: return 4;

+   case paInt24: return 3;

+   case paInt16: return 2;

+   case paInt8: case paUInt8: return 1;

+   default: return 0;

+   }

+}

+

+

+/*

+ * Functions for initializing, resetting, and destroying BLIO structures.

+ *

+ */

+

+/* This should be called with the relevant info when initializing a stream for

+   callback. */

+PaError initializeBlioRingBuffers(

+                                       PaMacBlio *blio,

+                                       PaSampleFormat inputSampleFormat,

+                                       PaSampleFormat outputSampleFormat,

+                                       size_t framesPerBuffer,

+                                       long ringBufferSize,

+                                       int inChan,

+                                       int outChan )

+{

+   void *data;

+   int result;

+

+   /* zeroify things */

+   bzero( blio, sizeof( PaMacBlio ) );

+   /* this is redundant, but the buffers are used to check

+      if the bufffers have been initialized, so we do it explicitly. */

+   blio->inputRingBuffer.buffer = NULL;

+   blio->outputRingBuffer.buffer = NULL;

+

+   /* initialize simple data */

+   blio->inputSampleFormat = inputSampleFormat;

+   blio->inputSampleSize = computeSampleSizeFromFormat(inputSampleFormat);

+   blio->outputSampleFormat = outputSampleFormat;

+   blio->outputSampleSize = computeSampleSizeFromFormat(outputSampleFormat);

+   blio->framesPerBuffer = framesPerBuffer;

+   blio->inChan = inChan;

+   blio->outChan = outChan;

+   blio->statusFlags = 0;

+   blio->errors = paNoError;

+#ifdef PA_MAC_BLIO_MUTEX

+   blio->isInputEmpty = false;

+   blio->isOutputFull = false;

+#endif

+

+   /* setup ring buffers */

+#ifdef PA_MAC_BLIO_MUTEX

+   result = PaMacCore_SetUnixError( pthread_mutex_init(&(blio->inputMutex),NULL), 0 );

+   if( result )

+      goto error;

+   result = UNIX_ERR( pthread_cond_init( &(blio->inputCond), NULL ) );

+   if( result )

+      goto error;

+   result = UNIX_ERR( pthread_mutex_init(&(blio->outputMutex),NULL) );

+   if( result )

+      goto error;

+   result = UNIX_ERR( pthread_cond_init( &(blio->outputCond), NULL ) );

+#endif

+   if( inChan ) {

+      data = calloc( ringBufferSize, blio->inputSampleSize );

+      if( !data )

+      {

+         result = paInsufficientMemory;

+         goto error;

+      }

+

+      assert( 0 == PaUtil_InitializeRingBuffer(

+            &blio->inputRingBuffer,

+            ringBufferSize*blio->inputSampleSize,

+            data ) );

+   }

+   if( outChan ) {

+      data = calloc( ringBufferSize, blio->outputSampleSize );

+      if( !data )

+      {

+         result = paInsufficientMemory;

+         goto error;

+      }

+

+      assert( 0 == PaUtil_InitializeRingBuffer(

+            &blio->outputRingBuffer,

+            ringBufferSize*blio->outputSampleSize,

+            data ) );

+   }

+

+   result = resetBlioRingBuffers( blio );

+   if( result )

+      goto error;

+

+   return 0;

+

+ error:

+   destroyBlioRingBuffers( blio );

+   return result;

+}

+

+#ifdef PA_MAC_BLIO_MUTEX

+PaError blioSetIsInputEmpty( PaMacBlio *blio, bool isEmpty )

+{

+   PaError result = paNoError;

+   if( isEmpty == blio->isInputEmpty )

+      goto done;

+

+   /* we need to update the value. Here's what we do:

+    * - Lock the mutex, so noone else can write.

+    * - update the value.

+    * - unlock.

+    * - broadcast to all listeners.

+    */

+   result = UNIX_ERR( pthread_mutex_lock( &blio->inputMutex ) );

+   if( result )

+      goto done;

+   blio->isInputEmpty = isEmpty;

+   result = UNIX_ERR( pthread_mutex_unlock( &blio->inputMutex ) );

+   if( result )

+      goto done;

+   result = UNIX_ERR( pthread_cond_broadcast( &blio->inputCond ) );

+   if( result )

+      goto done;

+

+ done:

+   return result;

+}

+PaError blioSetIsOutputFull( PaMacBlio *blio, bool isFull )

+{

+   PaError result = paNoError;

+   if( isFull == blio->isOutputFull )

+      goto done;

+

+   /* we need to update the value. Here's what we do:

+    * - Lock the mutex, so noone else can write.

+    * - update the value.

+    * - unlock.

+    * - broadcast to all listeners.

+    */

+   result = UNIX_ERR( pthread_mutex_lock( &blio->outputMutex ) );

+   if( result )

+      goto done;

+   blio->isOutputFull = isFull;

+   result = UNIX_ERR( pthread_mutex_unlock( &blio->outputMutex ) );

+   if( result )

+      goto done;

+   result = UNIX_ERR( pthread_cond_broadcast( &blio->outputCond ) );

+   if( result )

+      goto done;

+

+ done:

+   return result;

+}

+#endif

+

+/* This should be called after stopping or aborting the stream, so that on next

+   start, the buffers will be ready. */

+PaError resetBlioRingBuffers( PaMacBlio *blio )

+{

+#ifdef PA_MAC__BLIO_MUTEX

+   int result;

+#endif

+   blio->statusFlags = 0;

+   if( blio->outputRingBuffer.buffer ) {

+      PaUtil_FlushRingBuffer( &blio->outputRingBuffer );

+      bzero( blio->outputRingBuffer.buffer,

+             blio->outputRingBuffer.bufferSize );

+      /* Advance buffer */

+      PaUtil_AdvanceRingBufferWriteIndex( &blio->outputRingBuffer, blio->outputRingBuffer.bufferSize );

+

+      /* Update isOutputFull. */

+#ifdef PA_MAC__BLIO_MUTEX

+      result = blioSetIsOutputFull( blio, toAdvance == blio->outputRingBuffer.bufferSize );

+      if( result )

+         goto error;

+#endif

+/*

+      printf( "------%d\n" ,  blio->framesPerBuffer );

+      printf( "------%d\n" ,  blio->outChan );

+      printf( "------%d\n" ,  blio->outputSampleSize );

+      printf( "------%d\n" ,  blio->framesPerBuffer*blio->outChan*blio->outputSampleSize );

+*/

+   }

+   if( blio->inputRingBuffer.buffer ) {

+      PaUtil_FlushRingBuffer( &blio->inputRingBuffer );

+      bzero( blio->inputRingBuffer.buffer,

+             blio->inputRingBuffer.bufferSize );

+      /* Update isInputEmpty. */

+#ifdef PA_MAC__BLIO_MUTEX

+      result = blioSetIsInputEmpty( blio, true );

+      if( result )

+         goto error;

+#endif

+   }

+   return paNoError;

+#ifdef PA_MAC__BLIO_MUTEX

+ error:

+   return result;

+#endif

+}

+

+/*This should be called when you are done with the blio. It can safely be called

+  multiple times if there are no exceptions. */

+PaError destroyBlioRingBuffers( PaMacBlio *blio )

+{

+   PaError result = paNoError;

+   if( blio->inputRingBuffer.buffer ) {

+      free( blio->inputRingBuffer.buffer );

+#ifdef PA_MAC__BLIO_MUTEX

+      result = UNIX_ERR( pthread_mutex_destroy( & blio->inputMutex ) );

+      if( result ) return result;

+      result = UNIX_ERR( pthread_cond_destroy( & blio->inputCond ) );

+      if( result ) return result;

+#endif

+   }

+   blio->inputRingBuffer.buffer = NULL;

+   if( blio->outputRingBuffer.buffer ) {

+      free( blio->outputRingBuffer.buffer );

+#ifdef PA_MAC__BLIO_MUTEX

+      result = UNIX_ERR( pthread_mutex_destroy( & blio->outputMutex ) );

+      if( result ) return result;

+      result = UNIX_ERR( pthread_cond_destroy( & blio->outputCond ) );

+      if( result ) return result;

+#endif

+   }

+   blio->outputRingBuffer.buffer = NULL;

+

+   return result;

+}

+

+/*

+ * this is the BlioCallback function. It expects to recieve a PaMacBlio Object

+ * pointer as userData.

+ *

+ */

+int BlioCallback( const void *input, void *output, unsigned long frameCount,

+	const PaStreamCallbackTimeInfo* timeInfo,

+        PaStreamCallbackFlags statusFlags,

+        void *userData )

+{

+   PaMacBlio *blio = (PaMacBlio*)userData;

+   long avail;

+   long toRead;

+   long toWrite;

+

+   /* set flags returned by OS: */

+   OSAtomicOr32( statusFlags, &blio->statusFlags ) ;

+

+   /* --- Handle Input Buffer --- */

+   if( blio->inChan ) {

+      avail = PaUtil_GetRingBufferWriteAvailable( &blio->inputRingBuffer );

+

+      /* check for underflow */

+      if( avail < frameCount * blio->inputSampleSize * blio->inChan )

+         OSAtomicOr32( paInputOverflow, &blio->statusFlags );

+

+      toRead = MIN( avail, frameCount * blio->inputSampleSize * blio->inChan );

+

+      /* copy the data */

+      /*printf( "reading %d\n", toRead );*/

+      assert( toRead == PaUtil_WriteRingBuffer( &blio->inputRingBuffer, input, toRead ) );

+#ifdef PA_MAC__BLIO_MUTEX

+      /* Priority inversion. See notes below. */

+      blioSetIsInputEmpty( blio, false );

+#endif

+   }

+

+

+   /* --- Handle Output Buffer --- */

+   if( blio->outChan ) {

+      avail = PaUtil_GetRingBufferReadAvailable( &blio->outputRingBuffer );

+

+      /* check for underflow */

+      if( avail < frameCount * blio->outputSampleSize * blio->outChan )

+         OSAtomicOr32( paOutputUnderflow, &blio->statusFlags );

+

+      toWrite = MIN( avail, frameCount * blio->outputSampleSize * blio->outChan );

+

+      if( toWrite != frameCount * blio->outputSampleSize * blio->outChan )

+         bzero( ((char *)output)+toWrite,

+                frameCount * blio->outputSampleSize * blio->outChan - toWrite );

+      /* copy the data */

+      /*printf( "writing %d\n", toWrite );*/

+      assert( toWrite == PaUtil_ReadRingBuffer( &blio->outputRingBuffer, output, toWrite ) );

+#ifdef PA_MAC__BLIO_MUTEX

+      /* We have a priority inversion here. However, we will only have to

+         wait if this was true and is now false, which means we've got

+         some room in the buffer.

+         Hopefully problems will be minimized. */

+      blioSetIsOutputFull( blio, false );

+#endif

+   }

+

+   return paContinue;

+}

+

+PaError ReadStream( PaStream* stream,

+                           void *buffer,

+                           unsigned long frames )

+{

+    PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio;

+    char *cbuf = (char *) buffer;

+    PaError ret = paNoError;

+    VVDBUG(("ReadStream()\n"));

+

+    while( frames > 0 ) {

+       long avail;

+       long toRead;

+       do {

+          avail = PaUtil_GetRingBufferReadAvailable( &blio->inputRingBuffer );

+/*

+          printf( "Read Buffer is %%%g full: %ld of %ld.\n",

+                  100 * (float)avail / (float) blio->inputRingBuffer.bufferSize,

+                  avail, blio->inputRingBuffer.bufferSize );

+*/

+          if( avail == 0 ) {

+#ifdef PA_MAC_BLIO_MUTEX

+             /**block when empty*/

+             ret = UNIX_ERR( pthread_mutex_lock( &blio->inputMutex ) );

+             if( ret )

+                return ret;

+             while( blio->isInputEmpty ) {

+                ret = UNIX_ERR( pthread_cond_wait( &blio->inputCond, &blio->inputMutex ) );

+                if( ret )

+                   return ret;

+             }

+             ret = UNIX_ERR( pthread_mutex_unlock( &blio->inputMutex ) );

+             if( ret )

+                return ret;

+#else

+             Pa_Sleep( PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL );

+#endif

+          }

+       } while( avail == 0 );

+       toRead = MIN( avail, frames * blio->inputSampleSize * blio->inChan );

+       toRead -= toRead % blio->inputSampleSize * blio->inChan ;

+       PaUtil_ReadRingBuffer( &blio->inputRingBuffer, (void *)cbuf, toRead );

+       cbuf += toRead;

+       frames -= toRead / ( blio->inputSampleSize * blio->inChan );

+

+       if( toRead == avail ) {

+#ifdef PA_MAC_BLIO_MUTEX

+          /* we just emptied the buffer, so we need to mark it as empty. */

+          ret = blioSetIsInputEmpty( blio, true );

+          if( ret )

+             return ret;

+          /* of course, in the meantime, the callback may have put some sats

+             in, so

+             so check for that, too, to avoid a race condition. */

+          if( PaUtil_GetRingBufferReadAvailable( &blio->inputRingBuffer ) ) {

+             blioSetIsInputEmpty( blio, false );

+             if( ret )

+                return ret;

+          }

+#endif

+       }

+    }

+

+    /*   Report either paNoError or paInputOverflowed. */

+    /*   may also want to report other errors, but this is non-standard. */

+    ret = blio->statusFlags & paInputOverflow;

+

+    /* report underflow only once: */

+    if( ret ) {

+       OSAtomicAnd32( ~paInputOverflow, &blio->statusFlags );

+       ret = paInputOverflowed;

+    }

+

+    return ret;

+}

+

+

+PaError WriteStream( PaStream* stream,

+                            const void *buffer,

+                            unsigned long frames )

+{

+    PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio;

+    char *cbuf = (char *) buffer;

+    PaError ret = paNoError;

+    VVDBUG(("WriteStream()\n"));

+

+    while( frames > 0 ) {

+       long avail = 0;

+       long toWrite;

+

+       do {

+          avail = PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer );

+/*

+          printf( "Write Buffer is %%%g full: %ld of %ld.\n",

+                  100 - 100 * (float)avail / (float) blio->outputRingBuffer.bufferSize,

+                  avail, blio->outputRingBuffer.bufferSize );

+*/

+          if( avail == 0 ) {

+#ifdef PA_MAC_BLIO_MUTEX

+             /*block while full*/

+             ret = UNIX_ERR( pthread_mutex_lock( &blio->outputMutex ) );

+             if( ret )

+                return ret;

+             while( blio->isOutputFull ) {

+                ret = UNIX_ERR( pthread_cond_wait( &blio->outputCond, &blio->outputMutex ) );

+                if( ret )

+                   return ret;

+             }

+             ret = UNIX_ERR( pthread_mutex_unlock( &blio->outputMutex ) );

+             if( ret )

+                return ret;

+#else

+             Pa_Sleep( PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL );

+#endif

+          }

+       } while( avail == 0 );

+

+       toWrite = MIN( avail, frames * blio->outputSampleSize * blio->outChan );

+       toWrite -= toWrite % blio->outputSampleSize * blio->outChan ;

+       PaUtil_WriteRingBuffer( &blio->outputRingBuffer, (void *)cbuf, toWrite );

+       cbuf += toWrite;

+       frames -= toWrite / ( blio->outputSampleSize * blio->outChan );

+

+#ifdef PA_MAC_BLIO_MUTEX

+       if( toWrite == avail ) {

+          /* we just filled up the buffer, so we need to mark it as filled. */

+          ret = blioSetIsOutputFull( blio, true );

+          if( ret )

+             return ret;

+          /* of course, in the meantime, we may have emptied the buffer, so

+             so check for that, too, to avoid a race condition. */

+          if( PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer ) ) {

+             blioSetIsOutputFull( blio, false );

+             if( ret )

+                return ret;

+          }

+       }

+#endif

+    }

+

+    /*   Report either paNoError or paOutputUnderflowed. */

+    /*   may also want to report other errors, but this is non-standard. */

+    ret = blio->statusFlags & paOutputUnderflow;

+

+    /* report underflow only once: */

+    if( ret ) {

+      OSAtomicAnd32( ~paOutputUnderflow, &blio->statusFlags );

+      ret = paOutputUnderflowed;

+    }

+

+    return ret;

+}

+

+/*

+ *

+ */

+void waitUntilBlioWriteBufferIsFlushed( PaMacBlio *blio )

+{

+    if( blio->outputRingBuffer.buffer ) {

+       long avail = PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer );

+       while( avail != blio->outputRingBuffer.bufferSize ) {

+          if( avail == 0 )

+             Pa_Sleep( PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL );

+          avail = PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer );

+       }

+    }

+}

+

+

+signed long GetStreamReadAvailable( PaStream* stream )

+{

+    PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio;

+    VVDBUG(("GetStreamReadAvailable()\n"));

+

+    return PaUtil_GetRingBufferReadAvailable( &blio->inputRingBuffer )

+                         / ( blio->outputSampleSize * blio->outChan );

+}

+

+

+signed long GetStreamWriteAvailable( PaStream* stream )

+{

+    PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio;

+    VVDBUG(("GetStreamWriteAvailable()\n"));

+

+    return PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer )

+                         / ( blio->outputSampleSize * blio->outChan );

+}

+

diff --git a/src/engine/external/portaudio/pa_mac_core_blocking.h b/src/engine/external/portaudio/pa_mac_core_blocking.h
new file mode 100644
index 00000000..8ad79eaa
--- /dev/null
+++ b/src/engine/external/portaudio/pa_mac_core_blocking.h
@@ -0,0 +1,133 @@
+/*

+ * Internal blocking interfaces for PortAudio Apple AUHAL implementation

+ *

+ * PortAudio Portable Real-Time Audio Library

+ * Latest Version at: http://www.portaudio.com

+ *

+ * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.

+ * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)

+ *

+ * Dominic's code was based on code by Phil Burk, Darren Gibbs,

+ * Gord Peters, Stephane Letz, and Greg Pfiel.

+ *

+ * The following people also deserve acknowledgements:

+ *

+ * Olivier Tristan for feedback and testing

+ * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O

+ * interface.

+ * 

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/**

+ @file

+ @ingroup hostaip_src

+*/

+

+#ifndef PA_MAC_CORE_BLOCKING_H_

+#define PA_MAC_CORE_BLOCKING_H_

+

+#include "pa_ringbuffer.h"

+#include "portaudio.h"

+#include "pa_mac_core_utilities.h"

+

+/*

+ * Number of miliseconds to busy wait whil waiting for data in blocking calls.

+ */

+#define PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL (5)

+/*

+ * Define exactly one of these blocking methods

+ * PA_MAC_BLIO_MUTEX is not actively maintained.

+ */

+#define PA_MAC_BLIO_BUSY_WAIT

+/*

+#define PA_MAC_BLIO_MUTEX

+*/

+

+typedef struct {

+    PaUtilRingBuffer inputRingBuffer;

+    PaUtilRingBuffer outputRingBuffer;

+    PaSampleFormat inputSampleFormat;

+    size_t inputSampleSize;

+    PaSampleFormat outputSampleFormat;

+    size_t outputSampleSize;

+

+    size_t framesPerBuffer;

+

+    int inChan;

+    int outChan;

+

+    //PaStreamCallbackFlags statusFlags;

+    uint32_t statusFlags;

+    PaError errors;

+

+    /* Here we handle blocking, using condition variables. */

+#ifdef  PA_MAC_BLIO_MUTEX

+    volatile bool isInputEmpty;

+    pthread_mutex_t inputMutex;

+    pthread_cond_t inputCond;

+

+    volatile bool isOutputFull;

+    pthread_mutex_t outputMutex;

+    pthread_cond_t outputCond;

+#endif

+}

+PaMacBlio;

+

+/*

+ * These functions operate on condition and related variables.

+ */

+

+PaError initializeBlioRingBuffers(

+                                       PaMacBlio *blio,

+                                       PaSampleFormat inputSampleFormat,

+                                       PaSampleFormat outputSampleFormat,

+                                       size_t framesPerBuffer,

+                                       long ringBufferSize,

+                                       int inChan,

+                                       int outChan );

+PaError destroyBlioRingBuffers( PaMacBlio *blio );

+PaError resetBlioRingBuffers( PaMacBlio *blio );

+

+int BlioCallback(

+        const void *input, void *output,

+        unsigned long frameCount,

+        const PaStreamCallbackTimeInfo* timeInfo,

+        PaStreamCallbackFlags statusFlags,

+        void *userData );

+

+void waitUntilBlioWriteBufferIsFlushed( PaMacBlio *blio );

+

+#endif /*PA_MAC_CORE_BLOCKING_H_*/

diff --git a/src/engine/external/portaudio/pa_mac_core_internal.h b/src/engine/external/portaudio/pa_mac_core_internal.h
new file mode 100644
index 00000000..018cb2c4
--- /dev/null
+++ b/src/engine/external/portaudio/pa_mac_core_internal.h
@@ -0,0 +1,162 @@
+/*

+ * Internal interfaces for PortAudio Apple AUHAL implementation

+ *

+ * PortAudio Portable Real-Time Audio Library

+ * Latest Version at: http://www.portaudio.com

+ *

+ * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.

+ * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)

+ *

+ * Dominic's code was based on code by Phil Burk, Darren Gibbs,

+ * Gord Peters, Stephane Letz, and Greg Pfiel.

+ *

+ * The following people also deserve acknowledgements:

+ *

+ * Olivier Tristan for feedback and testing

+ * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O

+ * interface.

+ * 

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/**

+ @file pa_mac_core

+ @ingroup hostapi_src

+ @author Bjorn Roche

+ @brief AUHAL implementation of PortAudio

+*/

+

+#ifndef PA_MAC_CORE_INTERNAL_H__

+#define PA_MAC_CORE_INTERNAL_H__

+

+#include <AudioUnit/AudioUnit.h>

+#include <AudioToolbox/AudioToolbox.h>

+

+

+#include "portaudio.h"

+#include "pa_util.h"

+#include "pa_hostapi.h"

+#include "pa_stream.h"

+#include "pa_allocation.h"

+#include "pa_cpuload.h"

+#include "pa_process.h"

+#include "pa_ringbuffer.h"

+

+#include "pa_mac_core_blocking.h"

+

+/* function prototypes */

+

+#ifdef __cplusplus

+extern "C"

+{

+#endif /* __cplusplus */

+

+PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );

+

+#ifdef __cplusplus

+}

+#endif /* __cplusplus */

+

+#define RING_BUFFER_ADVANCE_DENOMINATOR (4)

+

+PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );

+PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );

+signed long GetStreamReadAvailable( PaStream* stream );

+signed long GetStreamWriteAvailable( PaStream* stream );

+/* PaMacAUHAL - host api datastructure specific to this implementation */

+typedef struct

+{

+    PaUtilHostApiRepresentation inheritedHostApiRep;

+    PaUtilStreamInterface callbackStreamInterface;

+    PaUtilStreamInterface blockingStreamInterface;

+

+    PaUtilAllocationGroup *allocations;

+

+    /* implementation specific data goes here */

+    long devCount;

+    AudioDeviceID *devIds; /*array of all audio devices*/

+    AudioDeviceID defaultIn;

+    AudioDeviceID defaultOut;

+}

+PaMacAUHAL;

+

+

+

+/* stream data structure specifically for this implementation */

+typedef struct PaMacCoreStream

+{

+    PaUtilStreamRepresentation streamRepresentation;

+    PaUtilCpuLoadMeasurer cpuLoadMeasurer;

+    PaUtilBufferProcessor bufferProcessor;

+

+    /* implementation specific data goes here */

+    bool bufferProcessorIsInitialized;

+    AudioUnit inputUnit;

+    AudioUnit outputUnit;

+    AudioDeviceID inputDevice;

+    AudioDeviceID outputDevice;

+    size_t userInChan;

+    size_t userOutChan;

+    size_t inputFramesPerBuffer;

+    size_t outputFramesPerBuffer;

+    PaMacBlio blio;

+    /* We use this ring buffer when input and out devs are different. */

+    PaUtilRingBuffer inputRingBuffer;

+    /* We may need to do SR conversion on input. */

+    AudioConverterRef inputSRConverter;

+    /* We need to preallocate an inputBuffer for reading data. */

+    AudioBufferList inputAudioBufferList;

+    AudioTimeStamp startTime;

+    volatile PaStreamCallbackFlags xrunFlags;

+    volatile bool isTimeSet;

+    volatile enum {

+       STOPPED          = 0, /* playback is completely stopped,

+                                and the user has called StopStream(). */

+       CALLBACK_STOPPED = 1, /* callback has requested stop,

+                                but user has not yet called StopStream(). */

+       STOPPING         = 2, /* The stream is in the process of closing.

+                                This state is just used internally;

+                                externally it is indistinguishable from

+                                ACTIVE.*/

+       ACTIVE           = 3  /* The stream is active and running. */

+    } state;

+    double sampleRate;

+    //these may be different from the stream sample rate due to SR conversion:

+    double outDeviceSampleRate;

+    double inDeviceSampleRate;

+}

+PaMacCoreStream;

+

+#endif /* PA_MAC_CORE_INTERNAL_H__ */

diff --git a/src/engine/external/portaudio/pa_mac_core_utilities.c b/src/engine/external/portaudio/pa_mac_core_utilities.c
new file mode 100644
index 00000000..bc31169b
--- /dev/null
+++ b/src/engine/external/portaudio/pa_mac_core_utilities.c
@@ -0,0 +1,611 @@
+/*

+ * Helper and utility functions for pa_mac_core.c (Apple AUHAL implementation)

+ *

+ * PortAudio Portable Real-Time Audio Library

+ * Latest Version at: http://www.portaudio.com

+ *

+ * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.

+ * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)

+ *

+ * Dominic's code was based on code by Phil Burk, Darren Gibbs,

+ * Gord Peters, Stephane Letz, and Greg Pfiel.

+ *

+ * The following people also deserve acknowledgements:

+ *

+ * Olivier Tristan for feedback and testing

+ * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O

+ * interface.

+ * 

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/**

+ @file

+ @ingroup hostapi_src

+*/

+

+#include "pa_mac_core_utilities.h"

+

+PaError PaMacCore_SetUnixError( int err, int line )

+{

+   PaError ret;

+   const char *errorText;

+

+   if( err == 0 )

+   {

+      return paNoError;

+   }

+

+   ret = paNoError;

+   errorText = strerror( err );

+

+   /** Map Unix error to PaError. Pretty much the only one that maps

+       is ENOMEM. */

+   if( err == ENOMEM )

+      ret = paInsufficientMemory;

+   else

+      ret = paInternalError;

+

+   DBUG(("%d on line %d: msg='%s'\n", err, line, errorText));

+   PaUtil_SetLastHostErrorInfo( paCoreAudio, err, errorText );

+

+   return ret;

+}

+

+/*

+ * Translates MacOS generated errors into PaErrors

+ */

+PaError PaMacCore_SetError(OSStatus error, int line, int isError)

+{

+    /*FIXME: still need to handle possible ComponentResult values.*/

+    /*       unfortunately, they don't seem to be documented anywhere.*/

+    PaError result;

+    const char *errorType; 

+    const char *errorText;

+    

+    switch (error) {

+    case kAudioHardwareNoError:

+        return paNoError;

+    case kAudioHardwareNotRunningError:

+        errorText = "Audio Hardware Not Running";

+        result = paInternalError; break;

+    case kAudioHardwareUnspecifiedError: 

+        errorText = "Unspecified Audio Hardware Error";

+        result = paInternalError; break;

+    case kAudioHardwareUnknownPropertyError:

+        errorText = "Audio Hardware: Unknown Property";

+        result = paInternalError; break;

+    case kAudioHardwareBadPropertySizeError:

+        errorText = "Audio Hardware: Bad Property Size";

+        result = paInternalError; break;

+    case kAudioHardwareIllegalOperationError: 

+        errorText = "Audio Hardware: Illegal Operation";

+        result = paInternalError; break;

+    case kAudioHardwareBadDeviceError:

+        errorText = "Audio Hardware: Bad Device";

+        result = paInvalidDevice; break;

+    case kAudioHardwareBadStreamError:

+        errorText = "Audio Hardware: BadStream";

+        result = paBadStreamPtr; break;

+    case kAudioHardwareUnsupportedOperationError:

+        errorText = "Audio Hardware: Unsupported Operation";

+        result = paInternalError; break;

+    case kAudioDeviceUnsupportedFormatError:

+        errorText = "Audio Device: Unsupported Format";

+        result = paSampleFormatNotSupported; break;

+    case kAudioDevicePermissionsError:

+        errorText = "Audio Device: Permissions Error";

+        result = paDeviceUnavailable; break;

+    /* Audio Unit Errors: http://developer.apple.com/documentation/MusicAudio/Reference/CoreAudio/audio_units/chapter_5_section_3.html */

+    case kAudioUnitErr_InvalidProperty:

+        errorText = "Audio Unit: Invalid Property";

+        result = paInternalError; break;

+    case kAudioUnitErr_InvalidParameter:

+        errorText = "Audio Unit: Invalid Parameter";

+        result = paInternalError; break;

+    case kAudioUnitErr_NoConnection:

+        errorText = "Audio Unit: No Connection";

+        result = paInternalError; break;

+    case kAudioUnitErr_FailedInitialization:

+        errorText = "Audio Unit: Initialization Failed";

+        result = paInternalError; break;

+    case kAudioUnitErr_TooManyFramesToProcess:

+        errorText = "Audio Unit: Too Many Frames";

+        result = paInternalError; break;

+    case kAudioUnitErr_IllegalInstrument:

+        errorText = "Audio Unit: Illegal Instrument";

+        result = paInternalError; break;

+    case kAudioUnitErr_InstrumentTypeNotFound:

+        errorText = "Audio Unit: Instrument Type Not Found";

+        result = paInternalError; break;

+    case kAudioUnitErr_InvalidFile:

+        errorText = "Audio Unit: Invalid File";

+        result = paInternalError; break;

+    case kAudioUnitErr_UnknownFileType:

+        errorText = "Audio Unit: Unknown File Type";

+        result = paInternalError; break;

+    case kAudioUnitErr_FileNotSpecified:

+        errorText = "Audio Unit: File Not Specified";

+        result = paInternalError; break;

+    case kAudioUnitErr_FormatNotSupported:

+        errorText = "Audio Unit: Format Not Supported";

+        result = paInternalError; break;

+    case kAudioUnitErr_Uninitialized:

+        errorText = "Audio Unit: Unitialized";

+        result = paInternalError; break;

+    case kAudioUnitErr_InvalidScope:

+        errorText = "Audio Unit: Invalid Scope";

+        result = paInternalError; break;

+    case kAudioUnitErr_PropertyNotWritable:

+        errorText = "Audio Unit: PropertyNotWritable";

+        result = paInternalError; break;

+    case kAudioUnitErr_InvalidPropertyValue:

+        errorText = "Audio Unit: Invalid Property Value";

+        result = paInternalError; break;

+    case kAudioUnitErr_PropertyNotInUse:

+        errorText = "Audio Unit: Property Not In Use";

+        result = paInternalError; break;

+    case kAudioUnitErr_Initialized:

+        errorText = "Audio Unit: Initialized";

+        result = paInternalError; break;

+    case kAudioUnitErr_InvalidOfflineRender:

+        errorText = "Audio Unit: Invalid Offline Render";

+        result = paInternalError; break;

+    case kAudioUnitErr_Unauthorized:

+        errorText = "Audio Unit: Unauthorized";

+        result = paInternalError; break;

+    case kAudioUnitErr_CannotDoInCurrentContext:

+        errorText = "Audio Unit: cannot do in current context";

+        result = paInternalError; break;

+    default:

+        errorText = "Unknown Error";

+        result = paInternalError;

+    }

+

+    if (isError)

+        errorType = "Error";

+    else

+        errorType = "Warning";

+

+    if ((int)error < -99999 || (int)error > 99999)

+        DBUG(("%s on line %d: err='%4s', msg='%s'\n", errorType, line, (const char *)&error, errorText));

+    else

+        DBUG(("%s on line %d: err=%d, 0x%x, msg='%s'\n", errorType, line, (int)error, (unsigned)error, errorText));

+

+    PaUtil_SetLastHostErrorInfo( paCoreAudio, error, errorText );

+

+    return result;

+}

+

+/*

+ * This function computes an appropriate ring buffer size given

+ * a requested latency (in seconds), sample rate and framesPerBuffer.

+ *

+ * The returned ringBufferSize is computed using the following

+ * constraints:

+ *   - it must be at least 4.

+ *   - it must be at least 3x framesPerBuffer.

+ *   - it must be at least 2x the suggestedLatency.

+ *   - it must be a power of 2.

+ * This function attempts to compute the minimum such size.

+ *

+ * FEEDBACK: too liberal/conservative/another way?

+ */

+long computeRingBufferSize( const PaStreamParameters *inputParameters,

+                                   const PaStreamParameters *outputParameters,

+                                   long inputFramesPerBuffer,

+                                   long outputFramesPerBuffer,

+                                   double sampleRate )

+{

+   long ringSize;

+   int index;

+   int i;

+   double latencyTimesChannelCount ;

+   long framesPerBufferTimesChannelCount ;

+

+   VVDBUG(( "computeRingBufferSize()\n" ));

+

+   assert( inputParameters || outputParameters );

+

+   if( outputParameters && inputParameters )

+   {

+      latencyTimesChannelCount = MAX(

+           inputParameters->suggestedLatency * inputParameters->channelCount,

+           outputParameters->suggestedLatency * outputParameters->channelCount );

+      framesPerBufferTimesChannelCount = MAX(

+           inputFramesPerBuffer * inputParameters->channelCount,

+           outputFramesPerBuffer * outputParameters->channelCount );

+   } 

+   else if( outputParameters )

+   {

+      latencyTimesChannelCount

+                = outputParameters->suggestedLatency * outputParameters->channelCount;

+      framesPerBufferTimesChannelCount

+                = outputFramesPerBuffer * outputParameters->channelCount;

+   }

+   else /* we have inputParameters  */

+   {

+      latencyTimesChannelCount

+                = inputParameters->suggestedLatency * inputParameters->channelCount;

+      framesPerBufferTimesChannelCount

+                = inputFramesPerBuffer * inputParameters->channelCount;

+   }

+

+   ringSize = (long) ( latencyTimesChannelCount * sampleRate * 2 + .5);

+   VDBUG( ( "suggested latency * channelCount: %d\n", (int) (latencyTimesChannelCount*sampleRate) ) );

+   if( ringSize < framesPerBufferTimesChannelCount * 3 )

+      ringSize = framesPerBufferTimesChannelCount * 3 ;

+   VDBUG(("framesPerBuffer*channelCount:%d\n",(int)framesPerBufferTimesChannelCount));

+   VDBUG(("Ringbuffer size (1): %d\n", (int)ringSize ));

+

+   /* make sure it's at least 4 */

+   ringSize = MAX( ringSize, 4 );

+

+   /* round up to the next power of 2 */

+   index = -1;

+   for( i=0; i<sizeof(long)*8; ++i )

+      if( ringSize >> i & 0x01 )

+         index = i;

+   assert( index > 0 );

+   if( ringSize <= ( 0x01 << index ) )

+      ringSize = 0x01 << index ;

+   else

+      ringSize = 0x01 << ( index + 1 );

+

+   VDBUG(( "Final Ringbuffer size (2): %d\n", (int)ringSize ));

+   return ringSize;

+}

+

+

+/*

+ * Durring testing of core audio, I found that serious crashes could occur

+ * if properties such as sample rate were changed multiple times in rapid

+ * succession. The function below has some fancy logic to make sure that changes

+ * are acknowledged before another is requested. That seems to help a lot.

+ */

+

+OSStatus propertyProc(

+    AudioDeviceID inDevice, 

+    UInt32 inChannel, 

+    Boolean isInput, 

+    AudioDevicePropertyID inPropertyID, 

+    void* inClientData )

+{

+   MutexAndBool *mab = (MutexAndBool *) inClientData;

+   mab->once = TRUE;

+   pthread_mutex_unlock( &(mab->mutex) );

+   return noErr;

+}

+

+/* sets the value of the given property and waits for the change to 

+   be acknowledged, and returns the final value, which is not guaranteed

+   by this function to be the same as the desired value. Obviously, this

+   function can only be used for data whose input and output are the

+   same size and format, and their size and format are known in advance.*/

+PaError AudioDeviceSetPropertyNowAndWaitForChange(

+    AudioDeviceID inDevice,

+    UInt32 inChannel, 

+    Boolean isInput, 

+    AudioDevicePropertyID inPropertyID,

+    UInt32 inPropertyDataSize, 

+    const void *inPropertyData,

+    void *outPropertyData )

+{

+   OSStatus macErr;

+   int unixErr;

+   MutexAndBool mab;

+   UInt32 outPropertyDataSize = inPropertyDataSize;

+

+   /* First, see if it already has that value. If so, return. */

+   macErr = AudioDeviceGetProperty( inDevice, inChannel,

+                                 isInput, inPropertyID, 

+                                 &outPropertyDataSize, outPropertyData );

+   if( macErr )

+      goto failMac2;

+   if( inPropertyDataSize!=outPropertyDataSize )

+      return paInternalError;

+   if( 0==memcmp( outPropertyData, inPropertyData, outPropertyDataSize ) )

+      return paNoError;

+

+   /* setup and lock mutex */

+   mab.once = FALSE;

+   unixErr = pthread_mutex_init( &mab.mutex, NULL );

+   if( unixErr )

+      goto failUnix2;

+   unixErr = pthread_mutex_lock( &mab.mutex );

+   if( unixErr )

+      goto failUnix;

+

+   /* add property listener */

+   macErr = AudioDeviceAddPropertyListener( inDevice, inChannel, isInput,

+                                   inPropertyID, propertyProc,

+                                   &mab ); 

+   if( macErr )

+      goto failMac;

+   /* set property */

+   macErr  = AudioDeviceSetProperty( inDevice, NULL, inChannel,

+                                 isInput, inPropertyID,

+                                 inPropertyDataSize, inPropertyData );

+   if( macErr ) {

+      /* we couldn't set the property, so we'll just unlock the mutex

+         and move on. */

+      pthread_mutex_unlock( &mab.mutex );

+   }

+

+   /* wait for property to change */                      

+   unixErr = pthread_mutex_lock( &mab.mutex );

+   if( unixErr )

+      goto failUnix;

+

+   /* now read the property back out */

+   macErr = AudioDeviceGetProperty( inDevice, inChannel,

+                                 isInput, inPropertyID, 

+                                 &outPropertyDataSize, outPropertyData );

+   if( macErr )

+      goto failMac;

+   /* cleanup */

+   AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput,

+                                      inPropertyID, propertyProc );

+   unixErr = pthread_mutex_unlock( &mab.mutex );

+   if( unixErr )

+      goto failUnix2;

+   unixErr = pthread_mutex_destroy( &mab.mutex );

+   if( unixErr )

+      goto failUnix2;

+

+   return paNoError;

+

+ failUnix:

+   pthread_mutex_destroy( &mab.mutex );

+   AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput,

+                                      inPropertyID, propertyProc );

+

+ failUnix2:

+   DBUG( ("Error #%d while setting a device property: %s\n", unixErr, strerror( unixErr ) ) );

+   return paUnanticipatedHostError;

+

+ failMac:

+   pthread_mutex_destroy( &mab.mutex );

+   AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput,

+                                      inPropertyID, propertyProc );

+ failMac2:

+   return ERR( macErr );

+}

+

+/*

+ * Sets the sample rate the HAL device.

+ * if requireExact: set the sample rate or fail.

+ *

+ * otherwise      : set the exact sample rate.

+ *             If that fails, check for available sample rates, and choose one

+ *             higher than the requested rate. If there isn't a higher one,

+ *             just use the highest available.

+ */

+PaError setBestSampleRateForDevice( const AudioDeviceID device,

+                                    const bool isOutput,

+                                    const bool requireExact,

+                                    const Float64 desiredSrate )

+{

+   /*FIXME: changing the sample rate is disruptive to other programs using the

+            device, so it might be good to offer a custom flag to not change the

+            sample rate and just do conversion. (in my casual tests, there is

+            no disruption unless the sample rate really does need to change) */

+   const bool isInput = isOutput ? 0 : 1;

+   Float64 srate;

+   UInt32 propsize = sizeof( Float64 );

+   OSErr err;

+   AudioValueRange *ranges;

+   int i=0;

+   Float64 max  = -1; /*the maximum rate available*/

+   Float64 best = -1; /*the lowest sample rate still greater than desired rate*/

+   VDBUG(("Setting sample rate for device %ld to %g.\n",device,(float)desiredSrate));

+

+   /* -- try setting the sample rate -- */

+   err = AudioDeviceSetPropertyNowAndWaitForChange(

+                                 device, 0, isInput,

+                                 kAudioDevicePropertyNominalSampleRate,

+                                 propsize, &desiredSrate, &srate );

+   if( err )

+      return err;

+

+   /* -- if the rate agrees, and we got no errors, we are done -- */

+   if( !err && srate == desiredSrate )

+      return paNoError;

+   /* -- we've failed if the rates disagree and we are setting input -- */

+   if( requireExact )

+      return paInvalidSampleRate;

+

+   /* -- generate a list of available sample rates -- */

+   err = AudioDeviceGetPropertyInfo( device, 0, isInput,

+                                kAudioDevicePropertyAvailableNominalSampleRates,

+                                &propsize, NULL );

+   if( err )

+      return ERR( err );

+   ranges = (AudioValueRange *)calloc( 1, propsize );

+   if( !ranges )

+      return paInsufficientMemory;

+   err = AudioDeviceGetProperty( device, 0, isInput,

+                                kAudioDevicePropertyAvailableNominalSampleRates,

+                                &propsize, ranges );

+   if( err )

+   {

+      free( ranges );

+      return ERR( err );

+   }

+   VDBUG(("Requested sample rate of %g was not available.\n", (float)desiredSrate));

+   VDBUG(("%lu Available Sample Rates are:\n",propsize/sizeof(AudioValueRange)));

+#ifdef MAC_CORE_VERBOSE_DEBUG

+   for( i=0; i<propsize/sizeof(AudioValueRange); ++i )

+      VDBUG( ("\t%g-%g\n",

+              (float) ranges[i].mMinimum,

+              (float) ranges[i].mMaximum ) );

+#endif

+   VDBUG(("-----\n"));

+   

+   /* -- now pick the best available sample rate -- */

+   for( i=0; i<propsize/sizeof(AudioValueRange); ++i )

+   {

+      if( ranges[i].mMaximum > max ) max = ranges[i].mMaximum;

+      if( ranges[i].mMinimum > desiredSrate ) {

+         if( best < 0 )

+            best = ranges[i].mMinimum;

+         else if( ranges[i].mMinimum < best )

+            best = ranges[i].mMinimum;

+      }

+   }

+   if( best < 0 )

+      best = max;

+   VDBUG( ("Maximum Rate %g. best is %g.\n", max, best ) );

+   free( ranges );

+

+   /* -- set the sample rate -- */

+   propsize = sizeof( best );

+   err = AudioDeviceSetPropertyNowAndWaitForChange(

+                                 device, 0, isInput,

+                                 kAudioDevicePropertyNominalSampleRate,

+                                 propsize, &best, &srate );

+   if( err )

+      return err;

+

+   if( err )

+      return ERR( err );

+   /* -- if the set rate matches, we are done -- */

+   if( srate == best )

+      return paNoError;

+

+   /* -- otherwise, something wierd happened: we didn't set the rate, and we got no errors. Just bail. */

+   return paInternalError;

+}

+

+

+/*

+   Attempts to set the requestedFramesPerBuffer. If it can't set the exact

+   value, it settles for something smaller if available. If nothing smaller

+   is available, it uses the smallest available size.

+   actualFramesPerBuffer will be set to the actual value on successful return.

+   OK to pass NULL to actualFramesPerBuffer.

+   The logic is very simmilar too setBestSampleRate only failure here is

+   not usually catastrophic.

+*/

+PaError setBestFramesPerBuffer( const AudioDeviceID device,

+                                       const bool isOutput,

+                                       unsigned long requestedFramesPerBuffer, 

+                                       unsigned long *actualFramesPerBuffer )

+{

+   UInt32 afpb;

+   const bool isInput = !isOutput;

+   UInt32 propsize = sizeof(UInt32);

+   OSErr err;

+   Float64 min  = -1; /*the min blocksize*/

+   Float64 best = -1; /*the best blocksize*/

+   int i=0;

+   AudioValueRange *ranges;

+

+   if( actualFramesPerBuffer == NULL )

+      actualFramesPerBuffer = &afpb;

+

+

+   /* -- try and set exact FPB -- */

+   err = AudioDeviceSetProperty( device, NULL, 0, isInput,

+                                 kAudioDevicePropertyBufferFrameSize,

+                                 propsize, &requestedFramesPerBuffer);

+   err = AudioDeviceGetProperty( device, 0, isInput,

+                           kAudioDevicePropertyBufferFrameSize,

+                           &propsize, actualFramesPerBuffer);

+   if( err )

+      return ERR( err );

+   if( *actualFramesPerBuffer == requestedFramesPerBuffer )

+      return paNoError; /* we are done */

+

+   /* -- fetch available block sizes -- */

+   err = AudioDeviceGetPropertyInfo( device, 0, isInput,

+                           kAudioDevicePropertyBufferSizeRange,

+                           &propsize, NULL );

+   if( err )

+      return ERR( err );

+   ranges = (AudioValueRange *)calloc( 1, propsize );

+   if( !ranges )

+      return paInsufficientMemory;

+   err = AudioDeviceGetProperty( device, 0, isInput,

+                                kAudioDevicePropertyBufferSizeRange,

+                                &propsize, ranges );

+   if( err )

+   {

+      free( ranges );

+      return ERR( err );

+   }

+   VDBUG(("Requested block size of %lu was not available.\n",

+          requestedFramesPerBuffer ));

+   VDBUG(("%lu Available block sizes are:\n",propsize/sizeof(AudioValueRange)));

+#ifdef MAC_CORE_VERBOSE_DEBUG

+   for( i=0; i<propsize/sizeof(AudioValueRange); ++i )

+      VDBUG( ("\t%g-%g\n",

+              (float) ranges[i].mMinimum,

+              (float) ranges[i].mMaximum ) );

+#endif

+   VDBUG(("-----\n"));

+   

+   /* --- now pick the best available framesPerBuffer -- */

+   for( i=0; i<propsize/sizeof(AudioValueRange); ++i )

+   {

+      if( min == -1 || ranges[i].mMinimum < min ) min = ranges[i].mMinimum;

+      if( ranges[i].mMaximum < requestedFramesPerBuffer ) {

+         if( best < 0 )

+            best = ranges[i].mMaximum;

+         else if( ranges[i].mMaximum > best )

+            best = ranges[i].mMaximum;

+      }

+   }

+   if( best == -1 )

+      best = min;

+   VDBUG( ("Minimum FPB  %g. best is %g.\n", min, best ) );

+   free( ranges );

+

+   /* --- set the buffer size (ignore errors) -- */

+   requestedFramesPerBuffer = (UInt32) best ;

+   propsize = sizeof( UInt32 );

+   err = AudioDeviceSetProperty( device, NULL, 0, isInput,

+                                 kAudioDevicePropertyBufferSize,

+                                 propsize, &requestedFramesPerBuffer );

+   /* --- read the property to check that it was set -- */

+   err = AudioDeviceGetProperty( device, 0, isInput,

+                                 kAudioDevicePropertyBufferSize,

+                                 &propsize, actualFramesPerBuffer );

+

+   if( err )

+      return ERR( err );

+

+   return paNoError;

+}

diff --git a/src/engine/external/portaudio/pa_mac_core_utilities.h b/src/engine/external/portaudio/pa_mac_core_utilities.h
new file mode 100644
index 00000000..992ba060
--- /dev/null
+++ b/src/engine/external/portaudio/pa_mac_core_utilities.h
@@ -0,0 +1,205 @@
+/*

+ * Helper and utility functions for pa_mac_core.c (Apple AUHAL implementation)

+ *

+ * PortAudio Portable Real-Time Audio Library

+ * Latest Version at: http://www.portaudio.com

+ *

+ * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.

+ * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)

+ *

+ * Dominic's code was based on code by Phil Burk, Darren Gibbs,

+ * Gord Peters, Stephane Letz, and Greg Pfiel.

+ *

+ * The following people also deserve acknowledgements:

+ *

+ * Olivier Tristan for feedback and testing

+ * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O

+ * interface.

+ * 

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/**

+ @file

+ @ingroup hostapi_src

+*/

+

+#ifndef PA_MAC_CORE_UTILITIES_H__

+#define PA_MAC_CORE_UTILITIES_H__

+

+#include <pthread.h>

+#include "portaudio.h"

+#include "pa_util.h"

+#include <AudioUnit/AudioUnit.h>

+#include <AudioToolbox/AudioToolbox.h>

+

+#ifndef MIN

+#define MIN(a, b)  (((a)<(b))?(a):(b))

+#endif

+

+#ifndef MAX

+#define MAX(a, b)  (((a)<(b))?(b):(a))

+#endif

+

+#define ERR(mac_error) PaMacCore_SetError(mac_error, __LINE__, 1 ) 

+#define WARNING(mac_error) PaMacCore_SetError(mac_error, __LINE__, 0 )

+

+

+/* Help keep track of AUHAL element numbers */

+#define INPUT_ELEMENT  (1)

+#define OUTPUT_ELEMENT (0)

+

+/* Normal level of debugging: fine for most apps that don't mind the occational warning being printf'ed */

+/*

+ */

+#define MAC_CORE_DEBUG

+#ifdef MAC_CORE_DEBUG

+# define DBUG(MSG) do { printf("||PaMacCore (AUHAL)|| "); printf MSG ; fflush(stdout); } while(0)

+#else

+# define DBUG(MSG)

+#endif

+

+/* Verbose Debugging: useful for developement */

+/*

+#define MAC_CORE_VERBOSE_DEBUG

+*/

+#ifdef MAC_CORE_VERBOSE_DEBUG

+# define VDBUG(MSG) do { printf("||PaMacCore (v )|| "); printf MSG ; fflush(stdout); } while(0)

+#else

+# define VDBUG(MSG)

+#endif

+

+/* Very Verbose Debugging: Traces every call. */

+/*

+#define MAC_CORE_VERY_VERBOSE_DEBUG

+ */

+#ifdef MAC_CORE_VERY_VERBOSE_DEBUG

+# define VVDBUG(MSG) do { printf("||PaMacCore (vv)|| "); printf MSG ; fflush(stdout); } while(0)

+#else

+# define VVDBUG(MSG)

+#endif

+

+

+

+

+

+#define UNIX_ERR(err) PaMacCore_SetUnixError( err, __LINE__ )

+

+PaError PaMacCore_SetUnixError( int err, int line );

+

+/*

+ * Translates MacOS generated errors into PaErrors

+ */

+PaError PaMacCore_SetError(OSStatus error, int line, int isError);

+

+/*

+ * This function computes an appropriate ring buffer size given

+ * a requested latency (in seconds), sample rate and framesPerBuffer.

+ *

+ * The returned ringBufferSize is computed using the following

+ * constraints:

+ *   - it must be at least 4.

+ *   - it must be at least 3x framesPerBuffer.

+ *   - it must be at least 2x the suggestedLatency.

+ *   - it must be a power of 2.

+ * This function attempts to compute the minimum such size.

+ *

+ */

+long computeRingBufferSize( const PaStreamParameters *inputParameters,

+                                   const PaStreamParameters *outputParameters,

+                                   long inputFramesPerBuffer,

+                                   long outputFramesPerBuffer,

+                                   double sampleRate );

+

+/*

+ * Durring testing of core audio, I found that serious crashes could occur

+ * if properties such as sample rate were changed multiple times in rapid

+ * succession. The function below has some fancy logic to make sure that changes

+ * are acknowledged before another is requested. That seems to help a lot.

+ */

+

+typedef struct {

+   bool once; /* I didn't end up using this. bdr */

+   pthread_mutex_t mutex;

+} MutexAndBool ;

+

+OSStatus propertyProc(

+    AudioDeviceID inDevice, 

+    UInt32 inChannel, 

+    Boolean isInput, 

+    AudioDevicePropertyID inPropertyID, 

+    void* inClientData );

+

+/* sets the value of the given property and waits for the change to 

+   be acknowledged, and returns the final value, which is not guaranteed

+   by this function to be the same as the desired value. Obviously, this

+   function can only be used for data whose input and output are the

+   same size and format, and their size and format are known in advance.*/

+PaError AudioDeviceSetPropertyNowAndWaitForChange(

+    AudioDeviceID inDevice,

+    UInt32 inChannel, 

+    Boolean isInput, 

+    AudioDevicePropertyID inPropertyID,

+    UInt32 inPropertyDataSize, 

+    const void *inPropertyData,

+    void *outPropertyData );

+

+/*

+ * Sets the sample rate the HAL device.

+ * if requireExact: set the sample rate or fail.

+ *

+ * otherwise      : set the exact sample rate.

+ *             If that fails, check for available sample rates, and choose one

+ *             higher than the requested rate. If there isn't a higher one,

+ *             just use the highest available.

+ */

+PaError setBestSampleRateForDevice( const AudioDeviceID device,

+                                    const bool isOutput,

+                                    const bool requireExact,

+                                    const Float64 desiredSrate );

+/*

+   Attempts to set the requestedFramesPerBuffer. If it can't set the exact

+   value, it settles for something smaller if available. If nothing smaller

+   is available, it uses the smallest available size.

+   actualFramesPerBuffer will be set to the actual value on successful return.

+   OK to pass NULL to actualFramesPerBuffer.

+   The logic is very simmilar too setBestSampleRate only failure here is

+   not usually catastrophic.

+*/

+PaError setBestFramesPerBuffer( const AudioDeviceID device,

+                                       const bool isOutput,

+                                       unsigned long requestedFramesPerBuffer, 

+                                       unsigned long *actualFramesPerBuffer );

+#endif /* PA_MAC_CORE_UTILITIES_H__*/

diff --git a/src/engine/external/portaudio/pa_mac_hostapis.c b/src/engine/external/portaudio/pa_mac_hostapis.c
new file mode 100644
index 00000000..7831bffe
--- /dev/null
+++ b/src/engine/external/portaudio/pa_mac_hostapis.c
@@ -0,0 +1,87 @@
+/*

+ * $Id: pa_mac_hostapis.c 1097 2006-08-26 08:27:53Z rossb $

+ * Portable Audio I/O Library Macintosh initialization table

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup macosx_src

+Mac OS host API initialization function table.

+*/

+

+

+#include "pa_hostapi.h"

+

+#ifdef __cplusplus

+extern "C"

+{

+#endif /* __cplusplus */

+    

+    PaError PaSkeleton_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );

+    PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );

+    PaError PaMacSm_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );

+    PaError PaJack_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );

+    PaError PaMacAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );

+    

+#ifdef __cplusplus

+}

+#endif /* __cplusplus */

+

+

+PaUtilHostApiInitializer *paHostApiInitializers[] =

+{

+#ifdef PA_USE_COREAUDIO

+    PaMacCore_Initialize,

+#endif

+    

+#ifdef PA_USE_SM

+    PaMacSm_Initialize,

+#endif

+    

+#ifdef PA_USE_JACK

+    PaJack_Initialize,

+#endif

+

+#ifdef PA_USE_ASIO

+    PaMacAsio_Initialize,

+#endif

+    

+    //PaSkeleton_Initialize, /* just for testing */

+    

+    0   /* NULL terminated array */

+};

+

+

+int paDefaultHostApiIndex = 0;

diff --git a/src/engine/external/portaudio/pa_process.c b/src/engine/external/portaudio/pa_process.c
new file mode 100644
index 00000000..bc8848e2
--- /dev/null
+++ b/src/engine/external/portaudio/pa_process.c
@@ -0,0 +1,1772 @@
+/*

+ * $Id: pa_process.c 1097 2006-08-26 08:27:53Z rossb $

+ * Portable Audio I/O Library

+ * streamCallback <-> host buffer processing adapter

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup common_src

+

+ @brief Buffer Processor implementation.

+    

+ The code in this file is not optimised yet - although it's not clear that

+ it needs to be. there may appear to be redundancies

+ that could be factored into common functions, but the redundanceis are left

+ intentionally as each appearance may have different optimisation possibilities.

+

+ The optimisations which are planned involve only converting data in-place

+ where possible, rather than copying to the temp buffer(s).

+

+ Note that in the extreme case of being able to convert in-place, and there

+ being no conversion necessary there should be some code which short-circuits

+ the operation.

+

+    @todo Consider cache tilings for intereave<->deinterleave.

+

+    @todo implement timeInfo->currentTime int PaUtil_BeginBufferProcessing()

+

+    @todo specify and implement some kind of logical policy for handling the

+        underflow and overflow stream flags when the underflow/overflow overlaps

+        multiple user buffers/callbacks.

+

+	@todo provide support for priming the buffers with data from the callback.

+        The client interface is now implemented through PaUtil_SetNoInput()

+        which sets bp->hostInputChannels[0][0].data to zero. However this is

+        currently only implemented in NonAdaptingProcess(). It shouldn't be

+        needed for AdaptingInputOnlyProcess() (no priming should ever be

+        requested for AdaptingInputOnlyProcess()).

+        Not sure if additional work should be required to make it work with

+        AdaptingOutputOnlyProcess, but it definitely is required for

+        AdaptingProcess.

+

+    @todo implement PaUtil_SetNoOutput for AdaptingProcess

+

+    @todo don't allocate temp buffers for blocking streams unless they are

+        needed. At the moment they are needed, but perhaps for host APIs

+        where the implementation passes a buffer to the host they could be

+        used.

+*/

+

+

+#include <assert.h>

+#include <string.h> /* memset() */

+

+#include "pa_process.h"

+#include "pa_util.h"

+

+

+#define PA_FRAMES_PER_TEMP_BUFFER_WHEN_HOST_BUFFER_SIZE_IS_UNKNOWN_    1024

+

+#define PA_MIN_( a, b ) ( ((a)<(b)) ? (a) : (b) )

+

+

+/* greatest common divisor - PGCD in French */

+static unsigned long GCD( unsigned long a, unsigned long b )

+{

+    return (b==0) ? a : GCD( b, a%b);

+}

+

+/* least common multiple - PPCM in French */

+static unsigned long LCM( unsigned long a, unsigned long b )

+{

+    return (a*b) / GCD(a,b);

+}

+

+#define PA_MAX_( a, b ) (((a) > (b)) ? (a) : (b))

+

+static unsigned long CalculateFrameShift( unsigned long M, unsigned long N )

+{

+    unsigned long result = 0;

+    unsigned long i;

+    unsigned long lcm;

+

+    assert( M > 0 );

+    assert( N > 0 );

+

+    lcm = LCM( M, N );

+    for( i = M; i < lcm; i += M )

+        result = PA_MAX_( result, i % N );

+

+    return result;

+}

+

+

+PaError PaUtil_InitializeBufferProcessor( PaUtilBufferProcessor* bp,

+        int inputChannelCount, PaSampleFormat userInputSampleFormat,

+        PaSampleFormat hostInputSampleFormat,

+        int outputChannelCount, PaSampleFormat userOutputSampleFormat,

+        PaSampleFormat hostOutputSampleFormat,

+        double sampleRate,

+        PaStreamFlags streamFlags,

+        unsigned long framesPerUserBuffer,

+        unsigned long framesPerHostBuffer,

+        PaUtilHostBufferSizeMode hostBufferSizeMode,

+        PaStreamCallback *streamCallback, void *userData )

+{

+    PaError result = paNoError;

+    PaError bytesPerSample;

+    unsigned long tempInputBufferSize, tempOutputBufferSize;

+

+    if( streamFlags & paNeverDropInput )

+    {

+        /* paNeverDropInput is only valid for full-duplex callback streams, with an unspecified number of frames per buffer. */

+        if( !streamCallback || !(inputChannelCount > 0 && outputChannelCount > 0) ||

+                framesPerUserBuffer != paFramesPerBufferUnspecified )

+            return paInvalidFlag;

+    }

+

+    /* initialize buffer ptrs to zero so they can be freed if necessary in error */

+    bp->tempInputBuffer = 0;

+    bp->tempInputBufferPtrs = 0;

+    bp->tempOutputBuffer = 0;

+    bp->tempOutputBufferPtrs = 0;

+

+    bp->framesPerUserBuffer = framesPerUserBuffer;

+    bp->framesPerHostBuffer = framesPerHostBuffer;

+

+    bp->inputChannelCount = inputChannelCount;

+    bp->outputChannelCount = outputChannelCount;

+

+    bp->hostBufferSizeMode = hostBufferSizeMode;

+

+    bp->hostInputChannels[0] = bp->hostInputChannels[1] = 0;

+    bp->hostOutputChannels[0] = bp->hostOutputChannels[1] = 0;

+

+    if( framesPerUserBuffer == 0 ) /* streamCallback will accept any buffer size */

+    {

+        bp->useNonAdaptingProcess = 1;

+        bp->initialFramesInTempInputBuffer = 0;

+        bp->initialFramesInTempOutputBuffer = 0;

+

+        if( hostBufferSizeMode == paUtilFixedHostBufferSize

+                || hostBufferSizeMode == paUtilBoundedHostBufferSize )

+        {

+            bp->framesPerTempBuffer = framesPerHostBuffer;

+        }

+        else /* unknown host buffer size */

+        {

+             bp->framesPerTempBuffer = PA_FRAMES_PER_TEMP_BUFFER_WHEN_HOST_BUFFER_SIZE_IS_UNKNOWN_;

+        }

+    }

+    else

+    {

+        bp->framesPerTempBuffer = framesPerUserBuffer;

+

+        if( hostBufferSizeMode == paUtilFixedHostBufferSize

+                && framesPerHostBuffer % framesPerUserBuffer == 0 )

+        {

+            bp->useNonAdaptingProcess = 1;

+            bp->initialFramesInTempInputBuffer = 0;

+            bp->initialFramesInTempOutputBuffer = 0;

+        }

+        else

+        {

+            bp->useNonAdaptingProcess = 0;

+

+            if( inputChannelCount > 0 && outputChannelCount > 0 )

+            {

+                /* full duplex */

+                if( hostBufferSizeMode == paUtilFixedHostBufferSize )

+                {

+                    unsigned long frameShift =

+                        CalculateFrameShift( framesPerHostBuffer, framesPerUserBuffer );

+

+                    if( framesPerUserBuffer > framesPerHostBuffer )

+                    {

+                        bp->initialFramesInTempInputBuffer = frameShift;

+                        bp->initialFramesInTempOutputBuffer = 0;

+                    }

+                    else

+                    {

+                        bp->initialFramesInTempInputBuffer = 0;

+                        bp->initialFramesInTempOutputBuffer = frameShift;

+                    }

+                }

+                else /* variable host buffer size, add framesPerUserBuffer latency */

+                {

+                    bp->initialFramesInTempInputBuffer = 0;

+                    bp->initialFramesInTempOutputBuffer = framesPerUserBuffer;

+                }

+            }

+            else

+            {

+                /* half duplex */

+                bp->initialFramesInTempInputBuffer = 0;

+                bp->initialFramesInTempOutputBuffer = 0;

+            }

+        }

+    }

+

+

+    bp->framesInTempInputBuffer = bp->initialFramesInTempInputBuffer;

+    bp->framesInTempOutputBuffer = bp->initialFramesInTempOutputBuffer;

+

+    

+    if( inputChannelCount > 0 )

+    {

+        bytesPerSample = Pa_GetSampleSize( hostInputSampleFormat );

+        if( bytesPerSample > 0 )

+        {

+            bp->bytesPerHostInputSample = bytesPerSample;

+        }

+        else

+        {

+            result = bytesPerSample;

+            goto error;

+        }

+

+        bytesPerSample = Pa_GetSampleSize( userInputSampleFormat );

+        if( bytesPerSample > 0 )

+        {

+            bp->bytesPerUserInputSample = bytesPerSample;

+        }

+        else

+        {

+            result = bytesPerSample;

+            goto error;

+        }

+

+        bp->inputConverter =

+            PaUtil_SelectConverter( hostInputSampleFormat, userInputSampleFormat, streamFlags );

+

+        bp->inputZeroer = PaUtil_SelectZeroer( hostInputSampleFormat );

+            

+        bp->userInputIsInterleaved = (userInputSampleFormat & paNonInterleaved)?0:1;

+

+

+        tempInputBufferSize =

+            bp->framesPerTempBuffer * bp->bytesPerUserInputSample * inputChannelCount;

+         

+        bp->tempInputBuffer = PaUtil_AllocateMemory( tempInputBufferSize );

+        if( bp->tempInputBuffer == 0 )

+        {

+            result = paInsufficientMemory;

+            goto error;

+        }

+        

+        if( bp->framesInTempInputBuffer > 0 )

+            memset( bp->tempInputBuffer, 0, tempInputBufferSize );

+

+        if( userInputSampleFormat & paNonInterleaved )

+        {

+            bp->tempInputBufferPtrs =

+                (void **)PaUtil_AllocateMemory( sizeof(void*)*inputChannelCount );

+            if( bp->tempInputBufferPtrs == 0 )

+            {

+                result = paInsufficientMemory;

+                goto error;

+            }

+        }

+

+        bp->hostInputChannels[0] = (PaUtilChannelDescriptor*)

+                PaUtil_AllocateMemory( sizeof(PaUtilChannelDescriptor) * inputChannelCount * 2);

+        if( bp->hostInputChannels[0] == 0 )

+        {

+            result = paInsufficientMemory;

+            goto error;

+        }

+

+        bp->hostInputChannels[1] = &bp->hostInputChannels[0][inputChannelCount];

+    }

+

+    if( outputChannelCount > 0 )

+    {

+        bytesPerSample = Pa_GetSampleSize( hostOutputSampleFormat );

+        if( bytesPerSample > 0 )

+        {

+            bp->bytesPerHostOutputSample = bytesPerSample;

+        }

+        else

+        {

+            result = bytesPerSample;

+            goto error;

+        }

+

+        bytesPerSample = Pa_GetSampleSize( userOutputSampleFormat );

+        if( bytesPerSample > 0 )

+        {

+            bp->bytesPerUserOutputSample = bytesPerSample;

+        }

+        else

+        {

+            result = bytesPerSample;

+            goto error;

+        }

+

+        bp->outputConverter =

+            PaUtil_SelectConverter( userOutputSampleFormat, hostOutputSampleFormat, streamFlags );

+

+        bp->outputZeroer = PaUtil_SelectZeroer( hostOutputSampleFormat );

+

+        bp->userOutputIsInterleaved = (userOutputSampleFormat & paNonInterleaved)?0:1;

+

+        tempOutputBufferSize =

+                bp->framesPerTempBuffer * bp->bytesPerUserOutputSample * outputChannelCount;

+

+        bp->tempOutputBuffer = PaUtil_AllocateMemory( tempOutputBufferSize );

+        if( bp->tempOutputBuffer == 0 )

+        {

+            result = paInsufficientMemory;

+            goto error;

+        }

+

+        if( bp->framesInTempOutputBuffer > 0 )

+            memset( bp->tempOutputBuffer, 0, tempOutputBufferSize );

+        

+        if( userOutputSampleFormat & paNonInterleaved )

+        {

+            bp->tempOutputBufferPtrs =

+                (void **)PaUtil_AllocateMemory( sizeof(void*)*outputChannelCount );

+            if( bp->tempOutputBufferPtrs == 0 )

+            {

+                result = paInsufficientMemory;

+                goto error;

+            }

+        }

+

+        bp->hostOutputChannels[0] = (PaUtilChannelDescriptor*)

+                PaUtil_AllocateMemory( sizeof(PaUtilChannelDescriptor)*outputChannelCount * 2 );

+        if( bp->hostOutputChannels[0] == 0 )

+        {                                                                     

+            result = paInsufficientMemory;

+            goto error;

+        }

+

+        bp->hostOutputChannels[1] = &bp->hostOutputChannels[0][outputChannelCount];

+    }

+

+    PaUtil_InitializeTriangularDitherState( &bp->ditherGenerator );

+

+    bp->samplePeriod = 1. / sampleRate;

+

+    bp->streamCallback = streamCallback;

+    bp->userData = userData;

+

+    return result;

+

+error:

+    if( bp->tempInputBuffer )

+        PaUtil_FreeMemory( bp->tempInputBuffer );

+

+    if( bp->tempInputBufferPtrs )

+        PaUtil_FreeMemory( bp->tempInputBufferPtrs );

+

+    if( bp->hostInputChannels[0] )

+        PaUtil_FreeMemory( bp->hostInputChannels[0] );

+

+    if( bp->tempOutputBuffer )

+        PaUtil_FreeMemory( bp->tempOutputBuffer );

+

+    if( bp->tempOutputBufferPtrs )

+        PaUtil_FreeMemory( bp->tempOutputBufferPtrs );

+

+    if( bp->hostOutputChannels[0] )

+        PaUtil_FreeMemory( bp->hostOutputChannels[0] );

+

+    return result;

+}

+

+

+void PaUtil_TerminateBufferProcessor( PaUtilBufferProcessor* bp )

+{

+    if( bp->tempInputBuffer )

+        PaUtil_FreeMemory( bp->tempInputBuffer );

+

+    if( bp->tempInputBufferPtrs )

+        PaUtil_FreeMemory( bp->tempInputBufferPtrs );

+

+    if( bp->hostInputChannels[0] )

+        PaUtil_FreeMemory( bp->hostInputChannels[0] );

+        

+    if( bp->tempOutputBuffer )

+        PaUtil_FreeMemory( bp->tempOutputBuffer );

+

+    if( bp->tempOutputBufferPtrs )

+        PaUtil_FreeMemory( bp->tempOutputBufferPtrs );

+

+    if( bp->hostOutputChannels[0] )

+        PaUtil_FreeMemory( bp->hostOutputChannels[0] );

+}

+

+

+void PaUtil_ResetBufferProcessor( PaUtilBufferProcessor* bp )

+{

+    unsigned long tempInputBufferSize, tempOutputBufferSize;

+

+    bp->framesInTempInputBuffer = bp->initialFramesInTempInputBuffer;

+    bp->framesInTempOutputBuffer = bp->initialFramesInTempOutputBuffer;

+

+    if( bp->framesInTempInputBuffer > 0 )

+    {

+        tempInputBufferSize =

+            bp->framesPerTempBuffer * bp->bytesPerUserInputSample * bp->inputChannelCount;

+        memset( bp->tempInputBuffer, 0, tempInputBufferSize );

+    }

+

+    if( bp->framesInTempOutputBuffer > 0 )

+    {      

+        tempOutputBufferSize =

+            bp->framesPerTempBuffer * bp->bytesPerUserOutputSample * bp->outputChannelCount;

+        memset( bp->tempOutputBuffer, 0, tempOutputBufferSize );

+    }

+}

+

+

+unsigned long PaUtil_GetBufferProcessorInputLatency( PaUtilBufferProcessor* bp )

+{

+    return bp->initialFramesInTempInputBuffer;

+}

+

+

+unsigned long PaUtil_GetBufferProcessorOutputLatency( PaUtilBufferProcessor* bp )

+{

+    return bp->initialFramesInTempOutputBuffer;

+}

+

+

+void PaUtil_SetInputFrameCount( PaUtilBufferProcessor* bp,

+        unsigned long frameCount )

+{

+    if( frameCount == 0 )

+        bp->hostInputFrameCount[0] = bp->framesPerHostBuffer;

+    else

+        bp->hostInputFrameCount[0] = frameCount;

+}

+        

+

+void PaUtil_SetNoInput( PaUtilBufferProcessor* bp )

+{

+    assert( bp->inputChannelCount > 0 );

+

+    bp->hostInputChannels[0][0].data = 0;

+}

+

+

+void PaUtil_SetInputChannel( PaUtilBufferProcessor* bp,

+        unsigned int channel, void *data, unsigned int stride )

+{

+    assert( channel < bp->inputChannelCount );

+    

+    bp->hostInputChannels[0][channel].data = data;

+    bp->hostInputChannels[0][channel].stride = stride;

+}

+

+

+void PaUtil_SetInterleavedInputChannels( PaUtilBufferProcessor* bp,

+        unsigned int firstChannel, void *data, unsigned int channelCount )

+{

+    unsigned int i;

+    unsigned int channel = firstChannel;

+    unsigned char *p = (unsigned char*)data;

+

+    if( channelCount == 0 )

+        channelCount = bp->inputChannelCount;

+

+    assert( firstChannel < bp->inputChannelCount );

+    assert( firstChannel + channelCount <= bp->inputChannelCount );

+

+    for( i=0; i< channelCount; ++i )

+    {

+        bp->hostInputChannels[0][channel+i].data = p;

+        p += bp->bytesPerHostInputSample;

+        bp->hostInputChannels[0][channel+i].stride = channelCount;

+    }

+}

+

+

+void PaUtil_SetNonInterleavedInputChannel( PaUtilBufferProcessor* bp,

+        unsigned int channel, void *data )

+{

+    assert( channel < bp->inputChannelCount );

+    

+    bp->hostInputChannels[0][channel].data = data;

+    bp->hostInputChannels[0][channel].stride = 1;

+}

+

+

+void PaUtil_Set2ndInputFrameCount( PaUtilBufferProcessor* bp,

+        unsigned long frameCount )

+{

+    bp->hostInputFrameCount[1] = frameCount;

+}

+

+

+void PaUtil_Set2ndInputChannel( PaUtilBufferProcessor* bp,

+        unsigned int channel, void *data, unsigned int stride )

+{

+    assert( channel < bp->inputChannelCount );

+

+    bp->hostInputChannels[1][channel].data = data;

+    bp->hostInputChannels[1][channel].stride = stride;

+}

+

+

+void PaUtil_Set2ndInterleavedInputChannels( PaUtilBufferProcessor* bp,

+        unsigned int firstChannel, void *data, unsigned int channelCount )

+{

+    unsigned int i;

+    unsigned int channel = firstChannel;

+    unsigned char *p = (unsigned char*)data;

+

+    if( channelCount == 0 )

+        channelCount = bp->inputChannelCount;

+

+    assert( firstChannel < bp->inputChannelCount );

+    assert( firstChannel + channelCount <= bp->inputChannelCount );

+    

+    for( i=0; i< channelCount; ++i )

+    {

+        bp->hostInputChannels[1][channel+i].data = p;

+        p += bp->bytesPerHostInputSample;

+        bp->hostInputChannels[1][channel+i].stride = channelCount;

+    }

+}

+

+        

+void PaUtil_Set2ndNonInterleavedInputChannel( PaUtilBufferProcessor* bp,

+        unsigned int channel, void *data )

+{

+    assert( channel < bp->inputChannelCount );

+    

+    bp->hostInputChannels[1][channel].data = data;

+    bp->hostInputChannels[1][channel].stride = 1;

+}

+

+

+void PaUtil_SetOutputFrameCount( PaUtilBufferProcessor* bp,

+        unsigned long frameCount )

+{

+    if( frameCount == 0 )

+        bp->hostOutputFrameCount[0] = bp->framesPerHostBuffer;

+    else

+        bp->hostOutputFrameCount[0] = frameCount;

+}

+

+

+void PaUtil_SetNoOutput( PaUtilBufferProcessor* bp )

+{

+    assert( bp->outputChannelCount > 0 );

+

+    bp->hostOutputChannels[0][0].data = 0;

+}

+

+

+void PaUtil_SetOutputChannel( PaUtilBufferProcessor* bp,

+        unsigned int channel, void *data, unsigned int stride )

+{

+    assert( channel < bp->outputChannelCount );

+    assert( data != NULL );

+

+    bp->hostOutputChannels[0][channel].data = data;

+    bp->hostOutputChannels[0][channel].stride = stride;

+}

+

+

+void PaUtil_SetInterleavedOutputChannels( PaUtilBufferProcessor* bp,

+        unsigned int firstChannel, void *data, unsigned int channelCount )

+{

+    unsigned int i;

+    unsigned int channel = firstChannel;

+    unsigned char *p = (unsigned char*)data;

+

+    if( channelCount == 0 )

+        channelCount = bp->outputChannelCount;

+

+    assert( firstChannel < bp->outputChannelCount );

+    assert( firstChannel + channelCount <= bp->outputChannelCount );

+    

+    for( i=0; i< channelCount; ++i )

+    {

+        PaUtil_SetOutputChannel( bp, channel + i, p, channelCount );

+        p += bp->bytesPerHostOutputSample;

+    }

+}

+

+

+void PaUtil_SetNonInterleavedOutputChannel( PaUtilBufferProcessor* bp,

+        unsigned int channel, void *data )

+{

+    assert( channel < bp->outputChannelCount );

+

+    PaUtil_SetOutputChannel( bp, channel, data, 1 );

+}

+

+

+void PaUtil_Set2ndOutputFrameCount( PaUtilBufferProcessor* bp,

+        unsigned long frameCount )

+{

+    bp->hostOutputFrameCount[1] = frameCount;

+}

+

+

+void PaUtil_Set2ndOutputChannel( PaUtilBufferProcessor* bp,

+        unsigned int channel, void *data, unsigned int stride )

+{

+    assert( channel < bp->outputChannelCount );

+    assert( data != NULL );

+

+    bp->hostOutputChannels[1][channel].data = data;

+    bp->hostOutputChannels[1][channel].stride = stride;

+}

+

+

+void PaUtil_Set2ndInterleavedOutputChannels( PaUtilBufferProcessor* bp,

+        unsigned int firstChannel, void *data, unsigned int channelCount )

+{

+    unsigned int i;

+    unsigned int channel = firstChannel;

+    unsigned char *p = (unsigned char*)data;

+

+    if( channelCount == 0 )

+        channelCount = bp->outputChannelCount;

+

+    assert( firstChannel < bp->outputChannelCount );

+    assert( firstChannel + channelCount <= bp->outputChannelCount );

+    

+    for( i=0; i< channelCount; ++i )

+    {

+        PaUtil_Set2ndOutputChannel( bp, channel + i, p, channelCount );

+        p += bp->bytesPerHostOutputSample;

+    }

+}

+

+        

+void PaUtil_Set2ndNonInterleavedOutputChannel( PaUtilBufferProcessor* bp,

+        unsigned int channel, void *data )

+{

+    assert( channel < bp->outputChannelCount );

+    

+    PaUtil_Set2ndOutputChannel( bp, channel, data, 1 );

+}

+

+

+void PaUtil_BeginBufferProcessing( PaUtilBufferProcessor* bp,

+        PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags callbackStatusFlags )

+{

+    bp->timeInfo = timeInfo;

+

+    /* the first streamCallback will be called to process samples which are

+        currently in the input buffer before the ones starting at the timeInfo time */

+        

+    bp->timeInfo->inputBufferAdcTime -= bp->framesInTempInputBuffer * bp->samplePeriod;

+    

+    bp->timeInfo->currentTime = 0; /** FIXME: @todo time info currentTime not implemented */

+

+    /* the first streamCallback will be called to generate samples which will be

+        outputted after the frames currently in the output buffer have been

+        outputted. */

+    bp->timeInfo->outputBufferDacTime += bp->framesInTempOutputBuffer * bp->samplePeriod;

+

+    bp->callbackStatusFlags = callbackStatusFlags;

+

+    bp->hostInputFrameCount[1] = 0;

+    bp->hostOutputFrameCount[1] = 0;

+}

+

+

+/*

+    NonAdaptingProcess() is a simple buffer copying adaptor that can handle

+    both full and half duplex copies. It processes framesToProcess frames,

+    broken into blocks bp->framesPerTempBuffer long.

+    This routine can be used when the streamCallback doesn't care what length

+    the buffers are, or when framesToProcess is an integer multiple of

+    bp->framesPerTempBuffer, in which case streamCallback will always be called

+    with bp->framesPerTempBuffer samples.

+*/

+static unsigned long NonAdaptingProcess( PaUtilBufferProcessor *bp,

+        int *streamCallbackResult,

+        PaUtilChannelDescriptor *hostInputChannels,

+        PaUtilChannelDescriptor *hostOutputChannels,

+        unsigned long framesToProcess )

+{

+    void *userInput, *userOutput;

+    unsigned char *srcBytePtr, *destBytePtr;

+    unsigned int srcSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */

+    unsigned int srcChannelStrideBytes; /* stride from one channel to the next, in bytes */

+    unsigned int destSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */

+    unsigned int destChannelStrideBytes; /* stride from one channel to the next, in bytes */

+    unsigned int i;

+    unsigned long frameCount;

+    unsigned long framesToGo = framesToProcess;

+    unsigned long framesProcessed = 0;

+

+

+    if( *streamCallbackResult == paContinue )

+    {

+        do

+        {

+            frameCount = PA_MIN_( bp->framesPerTempBuffer, framesToGo );

+

+            /* configure user input buffer and convert input data (host -> user) */

+            if( bp->inputChannelCount == 0 )

+            {

+                /* no input */

+                userInput = 0;

+            }

+            else /* there are input channels */

+            {

+                /*

+                    could use more elaborate logic here and sometimes process

+                    buffers in-place.

+                */

+            

+                destBytePtr = (unsigned char *)bp->tempInputBuffer;

+

+                if( bp->userInputIsInterleaved )

+                {

+                    destSampleStrideSamples = bp->inputChannelCount;

+                    destChannelStrideBytes = bp->bytesPerUserInputSample;

+                    userInput = bp->tempInputBuffer;

+                }

+                else /* user input is not interleaved */

+                {

+                    destSampleStrideSamples = 1;

+                    destChannelStrideBytes = frameCount * bp->bytesPerUserInputSample;

+

+                    /* setup non-interleaved ptrs */

+                    for( i=0; i<bp->inputChannelCount; ++i )

+                    {

+                        bp->tempInputBufferPtrs[i] = ((unsigned char*)bp->tempInputBuffer) +

+                            i * bp->bytesPerUserInputSample * frameCount;

+                    }

+                

+                    userInput = bp->tempInputBufferPtrs;

+                }

+

+                if( !bp->hostInputChannels[0][0].data )

+                {

+                    /* no input was supplied (see PaUtil_SetNoInput), so

+                        zero the input buffer */

+

+                    for( i=0; i<bp->inputChannelCount; ++i )

+                    {

+                        bp->inputZeroer( destBytePtr, destSampleStrideSamples, frameCount );

+                        destBytePtr += destChannelStrideBytes;  /* skip to next destination channel */

+                    }

+                }

+                else

+                {

+                    for( i=0; i<bp->inputChannelCount; ++i )

+                    {

+                        bp->inputConverter( destBytePtr, destSampleStrideSamples,

+                                                hostInputChannels[i].data,

+                                                hostInputChannels[i].stride,

+                                                frameCount, &bp->ditherGenerator );

+

+                        destBytePtr += destChannelStrideBytes;  /* skip to next destination channel */

+

+                        /* advance src ptr for next iteration */

+                        hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) +

+                                frameCount * hostInputChannels[i].stride * bp->bytesPerHostInputSample;

+                    }

+                }

+            }

+

+            /* configure user output buffer */

+            if( bp->outputChannelCount == 0 )

+            {

+                /* no output */

+                userOutput = 0;

+            }

+            else /* there are output channels */

+            {

+                if( bp->userOutputIsInterleaved )

+                {

+                    userOutput = bp->tempOutputBuffer;

+                }

+                else /* user output is not interleaved */

+                {

+                    for( i = 0; i < bp->outputChannelCount; ++i )

+                    {

+                        bp->tempOutputBufferPtrs[i] = ((unsigned char*)bp->tempOutputBuffer) +

+                            i * bp->bytesPerUserOutputSample * frameCount;

+                    }

+

+                    userOutput = bp->tempOutputBufferPtrs;

+                }

+            }

+        

+            *streamCallbackResult = bp->streamCallback( userInput, userOutput,

+                    frameCount, bp->timeInfo, bp->callbackStatusFlags, bp->userData );

+

+            if( *streamCallbackResult == paAbort )

+            {

+                /* callback returned paAbort, don't advance framesProcessed

+                        and framesToGo, they will be handled below */

+            }

+            else

+            {

+                bp->timeInfo->inputBufferAdcTime += frameCount * bp->samplePeriod;

+                bp->timeInfo->outputBufferDacTime += frameCount * bp->samplePeriod;

+

+                /* convert output data (user -> host) */

+                

+                if( bp->outputChannelCount != 0 && bp->hostOutputChannels[0][0].data )

+                {

+                    /*

+                        could use more elaborate logic here and sometimes process

+                        buffers in-place.

+                    */

+            

+                    srcBytePtr = (unsigned char *)bp->tempOutputBuffer;

+

+                    if( bp->userOutputIsInterleaved )

+                    {

+                        srcSampleStrideSamples = bp->outputChannelCount;

+                        srcChannelStrideBytes = bp->bytesPerUserOutputSample;

+                    }

+                    else /* user output is not interleaved */

+                    {

+                        srcSampleStrideSamples = 1;

+                        srcChannelStrideBytes = frameCount * bp->bytesPerUserOutputSample;

+                    }

+

+                    for( i=0; i<bp->outputChannelCount; ++i )

+                    {

+                        bp->outputConverter(    hostOutputChannels[i].data,

+                                                hostOutputChannels[i].stride,

+                                                srcBytePtr, srcSampleStrideSamples,

+                                                frameCount, &bp->ditherGenerator );

+

+                        srcBytePtr += srcChannelStrideBytes;  /* skip to next source channel */

+

+                        /* advance dest ptr for next iteration */

+                        hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) +

+                                frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;

+                    }

+                }

+             

+                framesProcessed += frameCount;

+

+                framesToGo -= frameCount;

+            }

+        }

+        while( framesToGo > 0  && *streamCallbackResult == paContinue );

+    }

+

+    if( framesToGo > 0 )

+    {

+        /* zero any remaining frames output. There will only be remaining frames

+            if the callback has returned paComplete or paAbort */

+

+        frameCount = framesToGo;

+

+        if( bp->outputChannelCount != 0 && bp->hostOutputChannels[0][0].data )

+        {

+            for( i=0; i<bp->outputChannelCount; ++i )

+            {

+                bp->outputZeroer(   hostOutputChannels[i].data,

+                                    hostOutputChannels[i].stride,

+                                    frameCount );

+

+                /* advance dest ptr for next iteration */

+                hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) +

+                        frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;

+            }

+        }

+

+        framesProcessed += frameCount;

+    }

+

+    return framesProcessed;

+}

+

+

+/*

+    AdaptingInputOnlyProcess() is a half duplex input buffer processor. It

+    converts data from the input buffers into the temporary input buffer,

+    when the temporary input buffer is full, it calls the streamCallback.

+*/

+static unsigned long AdaptingInputOnlyProcess( PaUtilBufferProcessor *bp,

+        int *streamCallbackResult,

+        PaUtilChannelDescriptor *hostInputChannels,

+        unsigned long framesToProcess )

+{

+    void *userInput, *userOutput;

+    unsigned char *destBytePtr;

+    unsigned int destSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */

+    unsigned int destChannelStrideBytes; /* stride from one channel to the next, in bytes */

+    unsigned int i;

+    unsigned long frameCount;

+    unsigned long framesToGo = framesToProcess;

+    unsigned long framesProcessed = 0;

+    

+    userOutput = 0;

+

+    do

+    {

+        frameCount = ( bp->framesInTempInputBuffer + framesToGo > bp->framesPerUserBuffer )

+                ? ( bp->framesPerUserBuffer - bp->framesInTempInputBuffer )

+                : framesToGo;

+

+        /* convert frameCount samples into temp buffer */

+

+        if( bp->userInputIsInterleaved )

+        {

+            destBytePtr = ((unsigned char*)bp->tempInputBuffer) +

+                    bp->bytesPerUserInputSample * bp->inputChannelCount *

+                    bp->framesInTempInputBuffer;

+                      

+            destSampleStrideSamples = bp->inputChannelCount;

+            destChannelStrideBytes = bp->bytesPerUserInputSample;

+

+            userInput = bp->tempInputBuffer;

+        }

+        else /* user input is not interleaved */

+        {

+            destBytePtr = ((unsigned char*)bp->tempInputBuffer) +

+                    bp->bytesPerUserInputSample * bp->framesInTempInputBuffer;

+

+            destSampleStrideSamples = 1;

+            destChannelStrideBytes = bp->framesPerUserBuffer * bp->bytesPerUserInputSample;

+

+            /* setup non-interleaved ptrs */

+            for( i=0; i<bp->inputChannelCount; ++i )

+            {

+                bp->tempInputBufferPtrs[i] = ((unsigned char*)bp->tempInputBuffer) +

+                    i * bp->bytesPerUserInputSample * bp->framesPerUserBuffer;

+            }

+                    

+            userInput = bp->tempInputBufferPtrs;

+        }

+

+        for( i=0; i<bp->inputChannelCount; ++i )

+        {

+            bp->inputConverter( destBytePtr, destSampleStrideSamples,

+                                    hostInputChannels[i].data,

+                                    hostInputChannels[i].stride,

+                                    frameCount, &bp->ditherGenerator );

+

+            destBytePtr += destChannelStrideBytes;  /* skip to next destination channel */

+

+            /* advance src ptr for next iteration */

+            hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) +

+                    frameCount * hostInputChannels[i].stride * bp->bytesPerHostInputSample;

+        }

+

+        bp->framesInTempInputBuffer += frameCount;

+

+        if( bp->framesInTempInputBuffer == bp->framesPerUserBuffer )

+        {

+            /**

+            @todo (non-critical optimisation)

+            The conditional below implements the continue/complete/abort mechanism

+            simply by continuing on iterating through the input buffer, but not

+            passing the data to the callback. With care, the outer loop could be

+            terminated earlier, thus some unneeded conversion cycles would be

+            saved.

+            */

+            if( *streamCallbackResult == paContinue )

+            {

+                bp->timeInfo->outputBufferDacTime = 0;

+

+                *streamCallbackResult = bp->streamCallback( userInput, userOutput,

+                        bp->framesPerUserBuffer, bp->timeInfo,

+                        bp->callbackStatusFlags, bp->userData );

+

+                bp->timeInfo->inputBufferAdcTime += frameCount * bp->samplePeriod;

+            }

+            

+            bp->framesInTempInputBuffer = 0;

+        }

+

+        framesProcessed += frameCount;

+

+        framesToGo -= frameCount;

+    }while( framesToGo > 0 );

+

+    return framesProcessed;

+}

+

+

+/*

+    AdaptingOutputOnlyProcess() is a half duplex output buffer processor.

+    It converts data from the temporary output buffer, to the output buffers,

+    when the temporary output buffer is empty, it calls the streamCallback.

+*/

+static unsigned long AdaptingOutputOnlyProcess( PaUtilBufferProcessor *bp,

+        int *streamCallbackResult,

+        PaUtilChannelDescriptor *hostOutputChannels,

+        unsigned long framesToProcess )

+{

+    void *userInput, *userOutput;

+    unsigned char *srcBytePtr;

+    unsigned int srcSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */

+    unsigned int srcChannelStrideBytes;  /* stride from one channel to the next, in bytes */

+    unsigned int i;

+    unsigned long frameCount;

+    unsigned long framesToGo = framesToProcess;

+    unsigned long framesProcessed = 0;

+

+    do

+    {

+        if( bp->framesInTempOutputBuffer == 0 && *streamCallbackResult == paContinue )

+        {

+            userInput = 0;

+

+            /* setup userOutput */

+            if( bp->userOutputIsInterleaved )

+            {

+                userOutput = bp->tempOutputBuffer;

+            }

+            else /* user output is not interleaved */

+            {

+                for( i = 0; i < bp->outputChannelCount; ++i )

+                {

+                    bp->tempOutputBufferPtrs[i] = ((unsigned char*)bp->tempOutputBuffer) +

+                            i * bp->framesPerUserBuffer * bp->bytesPerUserOutputSample;

+                }

+

+                userOutput = bp->tempOutputBufferPtrs;

+            }

+

+            bp->timeInfo->inputBufferAdcTime = 0;

+            

+            *streamCallbackResult = bp->streamCallback( userInput, userOutput,

+                    bp->framesPerUserBuffer, bp->timeInfo,

+                    bp->callbackStatusFlags, bp->userData );

+

+            if( *streamCallbackResult == paAbort )

+            {

+                /* if the callback returned paAbort, we disregard its output */

+            }

+            else

+            {

+                bp->timeInfo->outputBufferDacTime += bp->framesPerUserBuffer * bp->samplePeriod;

+

+                bp->framesInTempOutputBuffer = bp->framesPerUserBuffer;

+            }

+        }

+

+        if( bp->framesInTempOutputBuffer > 0 )

+        {

+            /* convert frameCount frames from user buffer to host buffer */

+

+            frameCount = PA_MIN_( bp->framesInTempOutputBuffer, framesToGo );

+

+            if( bp->userOutputIsInterleaved )

+            {

+                srcBytePtr = ((unsigned char*)bp->tempOutputBuffer) +

+                        bp->bytesPerUserOutputSample * bp->outputChannelCount *

+                        (bp->framesPerUserBuffer - bp->framesInTempOutputBuffer);

+

+                srcSampleStrideSamples = bp->outputChannelCount;

+                srcChannelStrideBytes = bp->bytesPerUserOutputSample;

+            }

+            else /* user output is not interleaved */

+            {

+                srcBytePtr = ((unsigned char*)bp->tempOutputBuffer) +

+                        bp->bytesPerUserOutputSample *

+                        (bp->framesPerUserBuffer - bp->framesInTempOutputBuffer);

+                            

+                srcSampleStrideSamples = 1;

+                srcChannelStrideBytes = bp->framesPerUserBuffer * bp->bytesPerUserOutputSample;

+            }

+

+            for( i=0; i<bp->outputChannelCount; ++i )

+            {

+                bp->outputConverter(    hostOutputChannels[i].data,

+                                        hostOutputChannels[i].stride,

+                                        srcBytePtr, srcSampleStrideSamples,

+                                        frameCount, &bp->ditherGenerator );

+

+                srcBytePtr += srcChannelStrideBytes;  /* skip to next source channel */

+

+                /* advance dest ptr for next iteration */

+                hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) +

+                        frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;

+            }

+

+            bp->framesInTempOutputBuffer -= frameCount;

+        }

+        else

+        {

+            /* no more user data is available because the callback has returned

+                paComplete or paAbort. Fill the remainder of the host buffer

+                with zeros.

+            */

+

+            frameCount = framesToGo;

+

+            for( i=0; i<bp->outputChannelCount; ++i )

+            {

+                bp->outputZeroer(   hostOutputChannels[i].data,

+                                    hostOutputChannels[i].stride,

+                                    frameCount );

+

+                /* advance dest ptr for next iteration */

+                hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) +

+                        frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;

+            }

+        }

+        

+        framesProcessed += frameCount;

+        

+        framesToGo -= frameCount;

+

+    }while( framesToGo > 0 );

+

+    return framesProcessed;

+}

+

+/* CopyTempOutputBuffersToHostOutputBuffers is called from AdaptingProcess to copy frames from

+	tempOutputBuffer to hostOutputChannels. This includes data conversion

+	and interleaving. 

+*/

+static void CopyTempOutputBuffersToHostOutputBuffers( PaUtilBufferProcessor *bp)

+{

+    unsigned long maxFramesToCopy;

+    PaUtilChannelDescriptor *hostOutputChannels;

+    unsigned int frameCount;

+    unsigned char *srcBytePtr;

+    unsigned int srcSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */

+    unsigned int srcChannelStrideBytes; /* stride from one channel to the next, in bytes */

+    unsigned int i;

+

+     /* copy frames from user to host output buffers */

+     while( bp->framesInTempOutputBuffer > 0 &&

+             ((bp->hostOutputFrameCount[0] + bp->hostOutputFrameCount[1]) > 0) )

+     {

+         maxFramesToCopy = bp->framesInTempOutputBuffer;

+

+         /* select the output buffer set (1st or 2nd) */

+         if( bp->hostOutputFrameCount[0] > 0 )

+         {

+             hostOutputChannels = bp->hostOutputChannels[0];

+             frameCount = PA_MIN_( bp->hostOutputFrameCount[0], maxFramesToCopy );

+         }

+         else

+         {

+             hostOutputChannels = bp->hostOutputChannels[1];

+             frameCount = PA_MIN_( bp->hostOutputFrameCount[1], maxFramesToCopy );

+         }

+

+         if( bp->userOutputIsInterleaved )

+         {

+             srcBytePtr = ((unsigned char*)bp->tempOutputBuffer) +

+                     bp->bytesPerUserOutputSample * bp->outputChannelCount *

+                     (bp->framesPerUserBuffer - bp->framesInTempOutputBuffer);

+                         

+             srcSampleStrideSamples = bp->outputChannelCount;

+             srcChannelStrideBytes = bp->bytesPerUserOutputSample;

+         }

+         else /* user output is not interleaved */

+         {

+             srcBytePtr = ((unsigned char*)bp->tempOutputBuffer) +

+                     bp->bytesPerUserOutputSample *

+                     (bp->framesPerUserBuffer - bp->framesInTempOutputBuffer);

+

+             srcSampleStrideSamples = 1;

+             srcChannelStrideBytes = bp->framesPerUserBuffer * bp->bytesPerUserOutputSample;

+         }

+

+         for( i=0; i<bp->outputChannelCount; ++i )

+         {

+             assert( hostOutputChannels[i].data != NULL );

+             bp->outputConverter(    hostOutputChannels[i].data,

+                                     hostOutputChannels[i].stride,

+                                     srcBytePtr, srcSampleStrideSamples,

+                                     frameCount, &bp->ditherGenerator );

+

+             srcBytePtr += srcChannelStrideBytes;  /* skip to next source channel */

+

+             /* advance dest ptr for next iteration */

+             hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) +

+                     frameCount * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;

+         }

+

+         if( bp->hostOutputFrameCount[0] > 0 )

+             bp->hostOutputFrameCount[0] -= frameCount;

+         else

+             bp->hostOutputFrameCount[1] -= frameCount;

+

+         bp->framesInTempOutputBuffer -= frameCount;

+     }

+}

+

+/*

+    AdaptingProcess is a full duplex adapting buffer processor. It converts

+    data from the temporary output buffer into the host output buffers, then

+    from the host input buffers into the temporary input buffers. Calling the

+    streamCallback when necessary.

+    When processPartialUserBuffers is 0, all available input data will be

+    consumed and all available output space will be filled. When

+    processPartialUserBuffers is non-zero, as many full user buffers

+    as possible will be processed, but partial buffers will not be consumed.

+*/

+static unsigned long AdaptingProcess( PaUtilBufferProcessor *bp,

+        int *streamCallbackResult, int processPartialUserBuffers )

+{

+    void *userInput, *userOutput;

+    unsigned long framesProcessed = 0;

+    unsigned long framesAvailable;

+    unsigned long endProcessingMinFrameCount;

+    unsigned long maxFramesToCopy;

+    PaUtilChannelDescriptor *hostInputChannels, *hostOutputChannels;

+    unsigned int frameCount;

+    unsigned char *destBytePtr;

+    unsigned int destSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */

+    unsigned int destChannelStrideBytes; /* stride from one channel to the next, in bytes */

+    unsigned int i, j;

+ 

+

+    framesAvailable = bp->hostInputFrameCount[0] + bp->hostInputFrameCount[1];/* this is assumed to be the same as the output buffer's frame count */

+

+    if( processPartialUserBuffers )

+        endProcessingMinFrameCount = 0;

+    else

+        endProcessingMinFrameCount = (bp->framesPerUserBuffer - 1);

+

+    /* Fill host output with remaining frames in user output (tempOutputBuffer) */

+    CopyTempOutputBuffersToHostOutputBuffers( bp );		  	

+

+    while( framesAvailable > endProcessingMinFrameCount ) 

+    {

+

+        if( bp->framesInTempOutputBuffer == 0 && *streamCallbackResult != paContinue )

+        {

+            /* the callback will not be called any more, so zero what remains

+                of the host output buffers */

+

+            for( i=0; i<2; ++i )

+            {

+                frameCount = bp->hostOutputFrameCount[i];

+                if( frameCount > 0 )

+                {

+                    hostOutputChannels = bp->hostOutputChannels[i];

+                    

+                    for( j=0; j<bp->outputChannelCount; ++j )

+                    {

+                        bp->outputZeroer(   hostOutputChannels[j].data,

+                                            hostOutputChannels[j].stride,

+                                            frameCount );

+

+                        /* advance dest ptr for next iteration  */

+                        hostOutputChannels[j].data = ((unsigned char*)hostOutputChannels[j].data) +

+                                frameCount * hostOutputChannels[j].stride * bp->bytesPerHostOutputSample;

+                    }

+                    bp->hostOutputFrameCount[i] = 0;

+                }

+            }

+        }          

+

+

+        /* copy frames from host to user input buffers */

+        while( bp->framesInTempInputBuffer < bp->framesPerUserBuffer &&

+                ((bp->hostInputFrameCount[0] + bp->hostInputFrameCount[1]) > 0) )

+        {

+            maxFramesToCopy = bp->framesPerUserBuffer - bp->framesInTempInputBuffer;

+

+            /* select the input buffer set (1st or 2nd) */

+            if( bp->hostInputFrameCount[0] > 0 )

+            {

+                hostInputChannels = bp->hostInputChannels[0];

+                frameCount = PA_MIN_( bp->hostInputFrameCount[0], maxFramesToCopy );

+            }

+            else

+            {

+                hostInputChannels = bp->hostInputChannels[1];

+                frameCount = PA_MIN_( bp->hostInputFrameCount[1], maxFramesToCopy );

+            }

+

+            /* configure conversion destination pointers */

+            if( bp->userInputIsInterleaved )

+            {

+                destBytePtr = ((unsigned char*)bp->tempInputBuffer) +

+                        bp->bytesPerUserInputSample * bp->inputChannelCount *

+                        bp->framesInTempInputBuffer;

+

+                destSampleStrideSamples = bp->inputChannelCount;

+                destChannelStrideBytes = bp->bytesPerUserInputSample;

+            }

+            else /* user input is not interleaved */

+            {

+                destBytePtr = ((unsigned char*)bp->tempInputBuffer) +

+                        bp->bytesPerUserInputSample * bp->framesInTempInputBuffer;

+

+                destSampleStrideSamples = 1;

+                destChannelStrideBytes = bp->framesPerUserBuffer * bp->bytesPerUserInputSample;

+            }

+

+            for( i=0; i<bp->inputChannelCount; ++i )

+            {

+                bp->inputConverter( destBytePtr, destSampleStrideSamples,

+                                        hostInputChannels[i].data,

+                                        hostInputChannels[i].stride,

+                                        frameCount, &bp->ditherGenerator );

+

+                destBytePtr += destChannelStrideBytes;  /* skip to next destination channel */

+

+                /* advance src ptr for next iteration */

+                hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) +

+                        frameCount * hostInputChannels[i].stride * bp->bytesPerHostInputSample;

+            }

+

+            if( bp->hostInputFrameCount[0] > 0 )

+                bp->hostInputFrameCount[0] -= frameCount;

+            else

+                bp->hostInputFrameCount[1] -= frameCount;

+                

+            bp->framesInTempInputBuffer += frameCount;

+

+            /* update framesAvailable and framesProcessed based on input consumed

+                unless something is very wrong this will also correspond to the

+                amount of output generated */

+            framesAvailable -= frameCount;

+            framesProcessed += frameCount;

+        }

+

+        /* call streamCallback */

+        if( bp->framesInTempInputBuffer == bp->framesPerUserBuffer &&

+            bp->framesInTempOutputBuffer == 0 )

+        {

+            if( *streamCallbackResult == paContinue )

+            {

+                /* setup userInput */

+                if( bp->userInputIsInterleaved )

+                {

+                    userInput = bp->tempInputBuffer;

+                }

+                else /* user input is not interleaved */

+                {

+                    for( i = 0; i < bp->inputChannelCount; ++i )

+                    {

+                        bp->tempInputBufferPtrs[i] = ((unsigned char*)bp->tempInputBuffer) +

+                                i * bp->framesPerUserBuffer * bp->bytesPerUserInputSample;

+                    }

+

+                    userInput = bp->tempInputBufferPtrs;

+                }

+

+                /* setup userOutput */

+                if( bp->userOutputIsInterleaved )

+                {

+                    userOutput = bp->tempOutputBuffer;

+                }

+                else /* user output is not interleaved */

+                {

+                    for( i = 0; i < bp->outputChannelCount; ++i )

+                    {

+                        bp->tempOutputBufferPtrs[i] = ((unsigned char*)bp->tempOutputBuffer) +

+                                i * bp->framesPerUserBuffer * bp->bytesPerUserOutputSample;

+                    }

+

+                    userOutput = bp->tempOutputBufferPtrs;

+                }

+

+                /* call streamCallback */

+

+                *streamCallbackResult = bp->streamCallback( userInput, userOutput,

+                        bp->framesPerUserBuffer, bp->timeInfo,

+                        bp->callbackStatusFlags, bp->userData );

+

+                bp->timeInfo->inputBufferAdcTime += bp->framesPerUserBuffer * bp->samplePeriod;

+                bp->timeInfo->outputBufferDacTime += bp->framesPerUserBuffer * bp->samplePeriod;

+

+                bp->framesInTempInputBuffer = 0;

+

+                if( *streamCallbackResult == paAbort )

+                    bp->framesInTempOutputBuffer = 0;

+                else

+                    bp->framesInTempOutputBuffer = bp->framesPerUserBuffer;

+            }

+            else

+            {

+                /* paComplete or paAbort has already been called. */

+

+                bp->framesInTempInputBuffer = 0;

+            }

+        }

+

+        /* copy frames from user (tempOutputBuffer) to host output buffers (hostOutputChannels) 

+           Means to process the user output provided by the callback. Has to be called after

+            each callback. */

+        CopyTempOutputBuffersToHostOutputBuffers( bp );		  	

+

+    }

+    

+    return framesProcessed;

+}

+

+

+unsigned long PaUtil_EndBufferProcessing( PaUtilBufferProcessor* bp, int *streamCallbackResult )

+{

+    unsigned long framesToProcess, framesToGo;

+    unsigned long framesProcessed = 0;

+    

+    if( bp->inputChannelCount != 0 && bp->outputChannelCount != 0

+            && bp->hostInputChannels[0][0].data /* input was supplied (see PaUtil_SetNoInput) */

+            && bp->hostOutputChannels[0][0].data /* output was supplied (see PaUtil_SetNoOutput) */ )

+    {

+        assert( (bp->hostInputFrameCount[0] + bp->hostInputFrameCount[1]) ==

+                (bp->hostOutputFrameCount[0] + bp->hostOutputFrameCount[1]) );

+    }

+

+    assert( *streamCallbackResult == paContinue

+            || *streamCallbackResult == paComplete

+            || *streamCallbackResult == paAbort ); /* don't forget to pass in a valid callback result value */

+

+    if( bp->useNonAdaptingProcess )

+    {

+        if( bp->inputChannelCount != 0 && bp->outputChannelCount != 0 )

+        {

+            /* full duplex non-adapting process, splice buffers if they are

+                different lengths */

+

+            framesToGo = bp->hostOutputFrameCount[0] + bp->hostOutputFrameCount[1]; /* relies on assert above for input/output equivalence */

+

+            do{

+                unsigned long noInputInputFrameCount;

+                unsigned long *hostInputFrameCount;

+                PaUtilChannelDescriptor *hostInputChannels;

+                unsigned long noOutputOutputFrameCount;

+                unsigned long *hostOutputFrameCount;

+                PaUtilChannelDescriptor *hostOutputChannels;

+                unsigned long framesProcessedThisIteration;

+

+                if( !bp->hostInputChannels[0][0].data )

+                {

+                    /* no input was supplied (see PaUtil_SetNoInput)

+                        NonAdaptingProcess knows how to deal with this

+                    */

+                    noInputInputFrameCount = framesToGo;

+                    hostInputFrameCount = &noInputInputFrameCount;

+                    hostInputChannels = 0;

+                }

+                else if( bp->hostInputFrameCount[0] != 0 )

+                {

+                    hostInputFrameCount = &bp->hostInputFrameCount[0];

+                    hostInputChannels = bp->hostInputChannels[0];

+                }

+                else

+                {

+                    hostInputFrameCount = &bp->hostInputFrameCount[1];

+                    hostInputChannels = bp->hostInputChannels[1];

+                }

+

+                if( !bp->hostOutputChannels[0][0].data )

+                {

+                    /* no output was supplied (see PaUtil_SetNoOutput)

+                        NonAdaptingProcess knows how to deal with this

+                    */

+                    noOutputOutputFrameCount = framesToGo;

+                    hostOutputFrameCount = &noOutputOutputFrameCount;

+                    hostOutputChannels = 0;

+                }

+                if( bp->hostOutputFrameCount[0] != 0 )

+                {

+                    hostOutputFrameCount = &bp->hostOutputFrameCount[0];

+                    hostOutputChannels = bp->hostOutputChannels[0];

+                }

+                else

+                {

+                    hostOutputFrameCount = &bp->hostOutputFrameCount[1];

+                    hostOutputChannels = bp->hostOutputChannels[1];

+                }

+

+                framesToProcess = PA_MIN_( *hostInputFrameCount,

+                                       *hostOutputFrameCount );

+

+                assert( framesToProcess != 0 );

+                

+                framesProcessedThisIteration = NonAdaptingProcess( bp, streamCallbackResult,

+                        hostInputChannels, hostOutputChannels,

+                        framesToProcess );                                       

+

+                *hostInputFrameCount -= framesProcessedThisIteration;

+                *hostOutputFrameCount -= framesProcessedThisIteration;

+

+                framesProcessed += framesProcessedThisIteration;

+                framesToGo -= framesProcessedThisIteration;

+                

+            }while( framesToGo > 0 );

+        }

+        else

+        {

+            /* half duplex non-adapting process, just process 1st and 2nd buffer */

+            /* process first buffer */

+

+            framesToProcess = (bp->inputChannelCount != 0)

+                            ? bp->hostInputFrameCount[0]

+                            : bp->hostOutputFrameCount[0];

+

+            framesProcessed = NonAdaptingProcess( bp, streamCallbackResult,

+                        bp->hostInputChannels[0], bp->hostOutputChannels[0],

+                        framesToProcess );

+

+            /* process second buffer if provided */

+    

+            framesToProcess = (bp->inputChannelCount != 0)

+                            ? bp->hostInputFrameCount[1]

+                            : bp->hostOutputFrameCount[1];

+            if( framesToProcess > 0 )

+            {

+                framesProcessed += NonAdaptingProcess( bp, streamCallbackResult,

+                    bp->hostInputChannels[1], bp->hostOutputChannels[1],

+                    framesToProcess );

+            }

+        }

+    }

+    else /* block adaption necessary*/

+    {

+

+        if( bp->inputChannelCount != 0 && bp->outputChannelCount != 0 )

+        {

+            /* full duplex */

+            

+            if( bp->hostBufferSizeMode == paUtilVariableHostBufferSizePartialUsageAllowed  )

+            {

+                framesProcessed = AdaptingProcess( bp, streamCallbackResult,

+                        0 /* dont process partial user buffers */ );

+            }

+            else

+            {

+                framesProcessed = AdaptingProcess( bp, streamCallbackResult,

+                        1 /* process partial user buffers */ );

+            }

+        }

+        else if( bp->inputChannelCount != 0 )

+        {

+            /* input only */

+            framesToProcess = bp->hostInputFrameCount[0];

+

+            framesProcessed = AdaptingInputOnlyProcess( bp, streamCallbackResult,

+                        bp->hostInputChannels[0], framesToProcess );

+

+            framesToProcess = bp->hostInputFrameCount[1];

+            if( framesToProcess > 0 )

+            {

+                framesProcessed += AdaptingInputOnlyProcess( bp, streamCallbackResult,

+                        bp->hostInputChannels[1], framesToProcess );

+            }

+        }

+        else

+        {

+            /* output only */

+            framesToProcess = bp->hostOutputFrameCount[0];

+

+            framesProcessed = AdaptingOutputOnlyProcess( bp, streamCallbackResult,

+                        bp->hostOutputChannels[0], framesToProcess );

+

+            framesToProcess = bp->hostOutputFrameCount[1];

+            if( framesToProcess > 0 )

+            {

+                framesProcessed += AdaptingOutputOnlyProcess( bp, streamCallbackResult,

+                        bp->hostOutputChannels[1], framesToProcess );

+            }

+        }

+    }

+

+    return framesProcessed;

+}

+

+

+int PaUtil_IsBufferProcessorOutputEmpty( PaUtilBufferProcessor* bp )

+{

+    return (bp->framesInTempOutputBuffer) ? 0 : 1;

+} 

+

+

+unsigned long PaUtil_CopyInput( PaUtilBufferProcessor* bp,

+        void **buffer, unsigned long frameCount )

+{

+    PaUtilChannelDescriptor *hostInputChannels;

+    unsigned int framesToCopy;

+    unsigned char *destBytePtr;

+    void **nonInterleavedDestPtrs;

+    unsigned int destSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */

+    unsigned int destChannelStrideBytes; /* stride from one channel to the next, in bytes */

+    unsigned int i;

+

+    hostInputChannels = bp->hostInputChannels[0];

+    framesToCopy = PA_MIN_( bp->hostInputFrameCount[0], frameCount );

+

+    if( bp->userInputIsInterleaved )

+    {

+        destBytePtr = (unsigned char*)*buffer;

+        

+        destSampleStrideSamples = bp->inputChannelCount;

+        destChannelStrideBytes = bp->bytesPerUserInputSample;

+

+        for( i=0; i<bp->inputChannelCount; ++i )

+        {

+            bp->inputConverter( destBytePtr, destSampleStrideSamples,

+                                hostInputChannels[i].data,

+                                hostInputChannels[i].stride,

+                                framesToCopy, &bp->ditherGenerator );

+

+            destBytePtr += destChannelStrideBytes;  /* skip to next source channel */

+

+            /* advance dest ptr for next iteration */

+            hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) +

+                    framesToCopy * hostInputChannels[i].stride * bp->bytesPerHostInputSample;

+        }

+

+        /* advance callers dest pointer (buffer) */

+        *buffer = ((unsigned char *)*buffer) +

+                framesToCopy * bp->inputChannelCount * bp->bytesPerUserInputSample;

+    }

+    else

+    {

+        /* user input is not interleaved */

+        

+        nonInterleavedDestPtrs = (void**)*buffer;

+

+        destSampleStrideSamples = 1;

+        

+        for( i=0; i<bp->inputChannelCount; ++i )

+        {

+            destBytePtr = (unsigned char*)nonInterleavedDestPtrs[i];

+

+            bp->inputConverter( destBytePtr, destSampleStrideSamples,

+                                hostInputChannels[i].data,

+                                hostInputChannels[i].stride,

+                                framesToCopy, &bp->ditherGenerator );

+

+            /* advance callers dest pointer (nonInterleavedDestPtrs[i]) */

+            destBytePtr += bp->bytesPerUserInputSample * framesToCopy;

+            nonInterleavedDestPtrs[i] = destBytePtr;

+            

+            /* advance dest ptr for next iteration */

+            hostInputChannels[i].data = ((unsigned char*)hostInputChannels[i].data) +

+                    framesToCopy * hostInputChannels[i].stride * bp->bytesPerHostInputSample;

+        }

+    }

+

+    bp->hostInputFrameCount[0] -= framesToCopy;

+    

+    return framesToCopy;

+}

+

+unsigned long PaUtil_CopyOutput( PaUtilBufferProcessor* bp,

+        const void ** buffer, unsigned long frameCount )

+{

+    PaUtilChannelDescriptor *hostOutputChannels;

+    unsigned int framesToCopy;

+    unsigned char *srcBytePtr;

+    void **nonInterleavedSrcPtrs;

+    unsigned int srcSampleStrideSamples; /* stride from one sample to the next within a channel, in samples */

+    unsigned int srcChannelStrideBytes; /* stride from one channel to the next, in bytes */

+    unsigned int i;

+

+    hostOutputChannels = bp->hostOutputChannels[0];

+    framesToCopy = PA_MIN_( bp->hostOutputFrameCount[0], frameCount );

+

+    if( bp->userOutputIsInterleaved )

+    {

+        srcBytePtr = (unsigned char*)*buffer;

+        

+        srcSampleStrideSamples = bp->outputChannelCount;

+        srcChannelStrideBytes = bp->bytesPerUserOutputSample;

+

+        for( i=0; i<bp->outputChannelCount; ++i )

+        {

+            bp->outputConverter(    hostOutputChannels[i].data,

+                                    hostOutputChannels[i].stride,

+                                    srcBytePtr, srcSampleStrideSamples,

+                                    framesToCopy, &bp->ditherGenerator );

+

+            srcBytePtr += srcChannelStrideBytes;  /* skip to next source channel */

+

+            /* advance dest ptr for next iteration */

+            hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) +

+                    framesToCopy * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;

+        }

+

+        /* advance callers source pointer (buffer) */

+        *buffer = ((unsigned char *)*buffer) +

+                framesToCopy * bp->outputChannelCount * bp->bytesPerUserOutputSample;

+

+    }

+    else

+    {

+        /* user output is not interleaved */

+        

+        nonInterleavedSrcPtrs = (void**)*buffer;

+

+        srcSampleStrideSamples = 1;

+        

+        for( i=0; i<bp->outputChannelCount; ++i )

+        {

+            srcBytePtr = (unsigned char*)nonInterleavedSrcPtrs[i];

+            

+            bp->outputConverter(    hostOutputChannels[i].data,

+                                    hostOutputChannels[i].stride,

+                                    srcBytePtr, srcSampleStrideSamples,

+                                    framesToCopy, &bp->ditherGenerator );

+

+

+            /* advance callers source pointer (nonInterleavedSrcPtrs[i]) */

+            srcBytePtr += bp->bytesPerUserOutputSample * framesToCopy;

+            nonInterleavedSrcPtrs[i] = srcBytePtr;

+            

+            /* advance dest ptr for next iteration */

+            hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) +

+                    framesToCopy * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;

+        }

+    }

+

+    bp->hostOutputFrameCount[0] += framesToCopy;

+    

+    return framesToCopy;

+}

+

+

+unsigned long PaUtil_ZeroOutput( PaUtilBufferProcessor* bp, unsigned long frameCount )

+{

+    PaUtilChannelDescriptor *hostOutputChannels;

+    unsigned int framesToZero;

+    unsigned int i;

+

+    hostOutputChannels = bp->hostOutputChannels[0];

+    framesToZero = PA_MIN_( bp->hostOutputFrameCount[0], frameCount );

+

+    for( i=0; i<bp->outputChannelCount; ++i )

+    {

+        bp->outputZeroer(   hostOutputChannels[i].data,

+                            hostOutputChannels[i].stride,

+                            framesToZero );

+

+

+        /* advance dest ptr for next iteration */

+        hostOutputChannels[i].data = ((unsigned char*)hostOutputChannels[i].data) +

+                framesToZero * hostOutputChannels[i].stride * bp->bytesPerHostOutputSample;

+    }

+

+    bp->hostOutputFrameCount[0] += framesToZero;

+    

+    return framesToZero;

+}

diff --git a/src/engine/external/portaudio/pa_process.h b/src/engine/external/portaudio/pa_process.h
new file mode 100644
index 00000000..e7600aaa
--- /dev/null
+++ b/src/engine/external/portaudio/pa_process.h
@@ -0,0 +1,750 @@
+#ifndef PA_PROCESS_H

+#define PA_PROCESS_H

+/*

+ * $Id: pa_process.h 1097 2006-08-26 08:27:53Z rossb $

+ * Portable Audio I/O Library callback buffer processing adapters

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Phil Burk, Ross Bencina

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+ 

+/** @file

+ @ingroup common_src

+

+ @brief Buffer Processor prototypes. A Buffer Processor performs buffer length

+ adaption, coordinates sample format conversion, and interleaves/deinterleaves

+ channels.

+

+ <h3>Overview</h3>

+

+ The "Buffer Processor" (PaUtilBufferProcessor) manages conversion of audio

+ data from host buffers to user buffers and back again. Where required, the

+ buffer processor takes care of converting between host and user sample formats,

+ interleaving and deinterleaving multichannel buffers, and adapting between host

+ and user buffers with different lengths. The buffer processor may be used with

+ full and half duplex streams, for both callback streams and blocking read/write

+ streams.

+

+ One of the important capabilities provided by the buffer processor is

+ the ability to adapt between user and host buffer sizes of different lengths

+ with minimum latency. Although this task is relatively easy to perform when

+ the host buffer size is an integer multiple of the user buffer size, the

+ problem is more complicated when this is not the case - especially for

+ full-duplex callback streams. Where necessary the adaption is implemented by

+ internally buffering some input and/or output data. The buffer adation

+ algorithm used by the buffer processor was originally implemented by

+ Stephan Letz for the ASIO version of PortAudio, and is described in his

+ Callback_adaption_.pdf which is included in the distribution.

+

+ The buffer processor performs sample conversion using the functions provided

+ by pa_converters.c.

+

+ The following sections provide an overview of how to use the buffer processor.

+ Interested readers are advised to consult the host API implementations for

+ examples of buffer processor usage.

+ 

+

+ <h4>Initialization, resetting and termination</h4>

+

+ When a stream is opened, the buffer processor should be initialized using

+ PaUtil_InitializeBufferProcessor. This function initializes internal state

+ and allocates temporary buffers as neccesary according to the supplied

+ configuration parameters. Some of the parameters correspond to those requested

+ by the user in their call to Pa_OpenStream(), others reflect the requirements

+ of the host API implementation - they indicate host buffer sizes, formats,

+ and the type of buffering which the Host API uses. The buffer processor should

+ be initialized for callback streams and blocking read/write streams.

+

+ Call PaUtil_ResetBufferProcessor to clear any sample data which is present

+ in the buffer processor before starting to use it (for example when

+ Pa_StartStream is called).

+

+ When the buffer processor is no longer used call

+ PaUtil_TerminateBufferProcessor.

+

+ 

+ <h4>Using the buffer processor for a callback stream</h4>

+

+ The buffer processor's role in a callback stream is to take host input buffers

+ process them with the stream callback, and fill host output buffers. For a

+ full duplex stream, the buffer processor handles input and output simultaneously

+ due to the requirements of the minimum-latency buffer adation algorithm.

+

+ When a host buffer becomes available, the implementation should call

+ the buffer processor to process the buffer. The buffer processor calls the

+ stream callback to consume and/or produce audio data as necessary. The buffer

+ processor will convert sample formats, interleave/deinterleave channels,

+ and slice or chunk the data to the appropriate buffer lengths according to

+ the requirements of the stream callback and the host API.

+

+ To process a host buffer (or a pair of host buffers for a full-duplex stream)

+ use the following calling sequence:

+

+ -# Call PaUtil_BeginBufferProcessing

+ -# For a stream which takes input:

+    - Call PaUtil_SetInputFrameCount with the number of frames in the host input

+        buffer.

+    - Call one of the following functions one or more times to tell the

+        buffer processor about the host input buffer(s): PaUtil_SetInputChannel,

+        PaUtil_SetInterleavedInputChannels, PaUtil_SetNonInterleavedInputChannel.

+        Which function you call will depend on whether the host buffer(s) are

+        interleaved or not.

+    - If the available host data is split accross two buffers (for example a

+        data range at the end of a circular buffer and another range at the

+        beginning of the circular buffer), also call

+        PaUtil_Set2ndInputFrameCount, PaUtil_Set2ndInputChannel,

+        PaUtil_Set2ndInterleavedInputChannels,

+        PaUtil_Set2ndNonInterleavedInputChannel as necessary to tell the buffer

+        processor about the second buffer.

+ -# For a stream which generates output:

+    - Call PaUtil_SetOutputFrameCount with the number of frames in the host

+        output buffer.

+    - Call one of the following functions one or more times to tell the

+        buffer processor about the host output buffer(s): PaUtil_SetOutputChannel,

+        PaUtil_SetInterleavedOutputChannels, PaUtil_SetNonInterleavedOutputChannel.

+        Which function you call will depend on whether the host buffer(s) are

+        interleaved or not.

+    - If the available host output buffer space is split accross two buffers

+        (for example a data range at the end of a circular buffer and another

+        range at the beginning of the circular buffer), call

+        PaUtil_Set2ndOutputFrameCount, PaUtil_Set2ndOutputChannel,

+        PaUtil_Set2ndInterleavedOutputChannels,

+        PaUtil_Set2ndNonInterleavedOutputChannel as necessary to tell the buffer

+        processor about the second buffer.

+ -# Call PaUtil_EndBufferProcessing, this function performs the actual data

+    conversion and processing.

+

+

+ <h4>Using the buffer processor for a blocking read/write stream</h4>

+

+ Blocking read/write streams use the buffer processor to convert and copy user

+ output data to a host buffer, and to convert and copy host input data to

+ the user's buffer. The buffer processor does not perform any buffer adaption.

+ When using the buffer processor in a blocking read/write stream the input and

+ output conversion are performed separately by the PaUtil_CopyInput and

+ PaUtil_CopyOutput functions.

+

+ To copy data from a host input buffer to the buffer(s) which the user supplies

+ to Pa_ReadStream, use the following calling sequence.

+

+ - Repeat the following three steps until the user buffer(s) have been filled

+    with samples from the host input buffers:

+     -# Call PaUtil_SetInputFrameCount with the number of frames in the host

+        input buffer.

+     -# Call one of the following functions one or more times to tell the

+        buffer processor about the host input buffer(s): PaUtil_SetInputChannel,

+        PaUtil_SetInterleavedInputChannels, PaUtil_SetNonInterleavedInputChannel.

+        Which function you call will depend on whether the host buffer(s) are

+        interleaved or not.

+     -# Call PaUtil_CopyInput with the user buffer pointer (or a copy of the

+        array of buffer pointers for a non-interleaved stream) passed to

+        Pa_ReadStream, along with the number of frames in the user buffer(s).

+        Be careful to pass a <i>copy</i> of the user buffer pointers to

+        PaUtil_CopyInput because PaUtil_CopyInput advances the pointers to

+        the start of the next region to copy.

+ - PaUtil_CopyInput will not copy more data than is available in the

+    host buffer(s), so the above steps need to be repeated until the user

+    buffer(s) are full.

+

+ 

+ To copy data to the host output buffer from the user buffers(s) supplied

+ to Pa_WriteStream use the following calling sequence.

+

+ - Repeat the following three steps until all frames from the user buffer(s)

+    have been copied to the host API:

+     -# Call PaUtil_SetOutputFrameCount with the number of frames in the host

+        output buffer.

+     -# Call one of the following functions one or more times to tell the

+        buffer processor about the host output buffer(s): PaUtil_SetOutputChannel,

+        PaUtil_SetInterleavedOutputChannels, PaUtil_SetNonInterleavedOutputChannel.

+        Which function you call will depend on whether the host buffer(s) are

+        interleaved or not.

+     -# Call PaUtil_CopyOutput with the user buffer pointer (or a copy of the

+        array of buffer pointers for a non-interleaved stream) passed to

+        Pa_WriteStream, along with the number of frames in the user buffer(s).

+        Be careful to pass a <i>copy</i> of the user buffer pointers to 

+        PaUtil_CopyOutput because PaUtil_CopyOutput advances the pointers to

+        the start of the next region to copy.

+ - PaUtil_CopyOutput will not copy more data than fits in the host buffer(s),

+    so the above steps need to be repeated until all user data is copied.

+*/

+

+

+#include "portaudio.h"

+#include "pa_converters.h"

+#include "pa_dither.h"

+

+#ifdef __cplusplus

+extern "C"

+{

+#endif /* __cplusplus */

+

+

+/** @brief Mode flag passed to PaUtil_InitializeBufferProcessor indicating the type

+ of buffering that the host API uses.

+

+ The mode used depends on whether the host API or the implementation manages

+ the buffers, and how these buffers are used (scatter gather, circular buffer).

+*/

+typedef enum {

+/** The host buffer size is a fixed known size. */

+    paUtilFixedHostBufferSize,

+

+/** The host buffer size may vary, but has a known maximum size. */

+    paUtilBoundedHostBufferSize,

+

+/** Nothing is known about the host buffer size. */

+    paUtilUnknownHostBufferSize,

+

+/** The host buffer size varies, and the client does not require the buffer

+ processor to consume all of the input and fill all of the output buffer. This

+ is useful when the implementation has access to the host API's circular buffer

+ and only needs to consume/fill some of it, not necessarily all of it, with each

+ call to the buffer processor. This is the only mode where

+ PaUtil_EndBufferProcessing() may not consume the whole buffer.

+*/

+    paUtilVariableHostBufferSizePartialUsageAllowed

+}PaUtilHostBufferSizeMode;

+

+

+/** @brief An auxilliary data structure used internally by the buffer processor

+ to represent host input and output buffers. */

+typedef struct PaUtilChannelDescriptor{

+    void *data;

+    unsigned int stride;  /**< stride in samples, not bytes */

+}PaUtilChannelDescriptor;

+

+

+/** @brief The main buffer processor data structure.

+

+ Allocate one of these, initialize it with PaUtil_InitializeBufferProcessor

+ and terminate it with PaUtil_TerminateBufferProcessor.

+*/

+typedef struct {

+    unsigned long framesPerUserBuffer;

+    unsigned long framesPerHostBuffer;

+

+    PaUtilHostBufferSizeMode hostBufferSizeMode;

+    int useNonAdaptingProcess;

+    unsigned long framesPerTempBuffer;

+

+    unsigned int inputChannelCount;

+    unsigned int bytesPerHostInputSample;

+    unsigned int bytesPerUserInputSample;

+    int userInputIsInterleaved;

+    PaUtilConverter *inputConverter;

+    PaUtilZeroer *inputZeroer;

+    

+    unsigned int outputChannelCount;

+    unsigned int bytesPerHostOutputSample;

+    unsigned int bytesPerUserOutputSample;

+    int userOutputIsInterleaved;

+    PaUtilConverter *outputConverter;

+    PaUtilZeroer *outputZeroer;

+

+    unsigned long initialFramesInTempInputBuffer;

+    unsigned long initialFramesInTempOutputBuffer;

+

+    void *tempInputBuffer;          /**< used for slips, block adaption, and conversion. */

+    void **tempInputBufferPtrs;     /**< storage for non-interleaved buffer pointers, NULL for interleaved user input */

+    unsigned long framesInTempInputBuffer; /**< frames remaining in input buffer from previous adaption iteration */

+

+    void *tempOutputBuffer;         /**< used for slips, block adaption, and conversion. */

+    void **tempOutputBufferPtrs;    /**< storage for non-interleaved buffer pointers, NULL for interleaved user output */

+    unsigned long framesInTempOutputBuffer; /**< frames remaining in input buffer from previous adaption iteration */

+

+    PaStreamCallbackTimeInfo *timeInfo;

+

+    PaStreamCallbackFlags callbackStatusFlags;

+

+    unsigned long hostInputFrameCount[2];

+    PaUtilChannelDescriptor *hostInputChannels[2]; /**< pointers to arrays of channel descriptors.

+                                                        pointers are NULL for half-duplex output processing.

+                                                        hostInputChannels[i].data is NULL when the caller

+                                                        calls PaUtil_SetNoInput()

+                                                        */

+    unsigned long hostOutputFrameCount[2];

+    PaUtilChannelDescriptor *hostOutputChannels[2]; /**< pointers to arrays of channel descriptors.

+                                                         pointers are NULL for half-duplex input processing.

+                                                         hostOutputChannels[i].data is NULL when the caller

+                                                         calls PaUtil_SetNoOutput()

+                                                         */

+

+    PaUtilTriangularDitherGenerator ditherGenerator;

+

+    double samplePeriod;

+

+    PaStreamCallback *streamCallback;

+    void *userData;

+} PaUtilBufferProcessor;

+

+

+/** @name Initialization, termination, resetting and info */

+/*@{*/

+

+/** Initialize a buffer processor's representation stored in a

+ PaUtilBufferProcessor structure. Be sure to call

+ PaUtil_TerminateBufferProcessor after finishing with a buffer processor.

+

+ @param bufferProcessor The buffer processor structure to initialize.

+

+ @param inputChannelCount The number of input channels as passed to

+ Pa_OpenStream or 0 for an output-only stream.

+

+ @param userInputSampleFormat Format of user input samples, as passed to

+ Pa_OpenStream. This parameter is ignored for ouput-only streams.

+ 

+ @param hostInputSampleFormat Format of host input samples. This parameter is

+ ignored for output-only streams. See note about host buffer interleave below.

+

+ @param outputChannelCount The number of output channels as passed to

+ Pa_OpenStream or 0 for an input-only stream.

+

+ @param userOutputSampleFormat Format of user output samples, as passed to

+ Pa_OpenStream. This parameter is ignored for input-only streams.

+ 

+ @param hostOutputSampleFormat Format of host output samples. This parameter is

+ ignored for input-only streams. See note about host buffer interleave below.

+

+ @param sampleRate Sample rate of the stream. The more accurate this is the

+ better - it is used for updating time stamps when adapting buffers.

+ 

+ @param streamFlags Stream flags as passed to Pa_OpenStream, this parameter is

+ used for selecting special sample conversion options such as clipping and

+ dithering.

+ 

+ @param framesPerUserBuffer Number of frames per user buffer, as requested

+ by the framesPerBuffer parameter to Pa_OpenStream. This parameter may be

+ zero to indicate that the user will accept any (and varying) buffer sizes.

+

+ @param framesPerHostBuffer Specifies the number of frames per host buffer

+ for the fixed buffer size mode, and the maximum number of frames

+ per host buffer for the bounded host buffer size mode. It is ignored for

+ the other modes.

+

+ @param hostBufferSizeMode A mode flag indicating the size variability of

+ host buffers that will be passed to the buffer processor. See

+ PaUtilHostBufferSizeMode for further details.

+ 

+ @param streamCallback The user stream callback passed to Pa_OpenStream.

+

+ @param userData The user data field passed to Pa_OpenStream.

+    

+ @note The interleave flag is ignored for host buffer formats. Host

+ interleave is determined by the use of different SetInput and SetOutput

+ functions.

+

+ @return An error code indicating whether the initialization was successful.

+ If the error code is not PaNoError, the buffer processor was not initialized

+ and should not be used.

+ 

+ @see Pa_OpenStream, PaUtilHostBufferSizeMode, PaUtil_TerminateBufferProcessor

+*/

+PaError PaUtil_InitializeBufferProcessor( PaUtilBufferProcessor* bufferProcessor,

+            int inputChannelCount, PaSampleFormat userInputSampleFormat,

+            PaSampleFormat hostInputSampleFormat,

+            int outputChannelCount, PaSampleFormat userOutputSampleFormat,

+            PaSampleFormat hostOutputSampleFormat,

+            double sampleRate,

+            PaStreamFlags streamFlags,

+            unsigned long framesPerUserBuffer, /* 0 indicates don't care */

+            unsigned long framesPerHostBuffer,

+            PaUtilHostBufferSizeMode hostBufferSizeMode,

+            PaStreamCallback *streamCallback, void *userData );

+

+

+/** Terminate a buffer processor's representation. Deallocates any temporary

+ buffers allocated by PaUtil_InitializeBufferProcessor.

+ 

+ @param bufferProcessor The buffer processor structure to terminate.

+

+ @see PaUtil_InitializeBufferProcessor.

+*/

+void PaUtil_TerminateBufferProcessor( PaUtilBufferProcessor* bufferProcessor );

+

+

+/** Clear any internally buffered data. If you call

+ PaUtil_InitializeBufferProcessor in your OpenStream routine, make sure you

+ call PaUtil_ResetBufferProcessor in your StartStream call.

+

+ @param bufferProcessor The buffer processor to reset.

+*/

+void PaUtil_ResetBufferProcessor( PaUtilBufferProcessor* bufferProcessor );

+

+

+/** Retrieve the input latency of a buffer processor.

+

+ @param bufferProcessor The buffer processor examine.

+

+ @return The input latency introduced by the buffer processor, in frames.

+

+ @see PaUtil_GetBufferProcessorOutputLatency

+*/

+unsigned long PaUtil_GetBufferProcessorInputLatency( PaUtilBufferProcessor* bufferProcessor );

+

+/** Retrieve the output latency of a buffer processor.

+

+ @param bufferProcessor The buffer processor examine.

+

+ @return The output latency introduced by the buffer processor, in frames.

+

+ @see PaUtil_GetBufferProcessorInputLatency

+*/

+unsigned long PaUtil_GetBufferProcessorOutputLatency( PaUtilBufferProcessor* bufferProcessor );

+

+/*@}*/

+

+

+/** @name Host buffer pointer configuration

+

+ Functions to set host input and output buffers, used by both callback streams

+ and blocking read/write streams.

+*/

+/*@{*/ 

+

+

+/** Set the number of frames in the input host buffer(s) specified by the

+ PaUtil_Set*InputChannel functions.

+

+ @param bufferProcessor The buffer processor.

+

+ @param frameCount The number of host input frames. A 0 frameCount indicates to

+ use the framesPerHostBuffer value passed to PaUtil_InitializeBufferProcessor.

+

+ @see PaUtil_SetNoInput, PaUtil_SetInputChannel,

+ PaUtil_SetInterleavedInputChannels, PaUtil_SetNonInterleavedInputChannel

+*/

+void PaUtil_SetInputFrameCount( PaUtilBufferProcessor* bufferProcessor,

+        unsigned long frameCount );

+

+        

+/** Indicate that no input is avalable. This function should be used when

+ priming the output of a full-duplex stream opened with the

+ paPrimeOutputBuffersUsingStreamCallback flag. Note that it is not necessary

+ to call this or any othe PaUtil_Set*Input* functions for ouput-only streams.

+

+ @param bufferProcessor The buffer processor.

+*/

+void PaUtil_SetNoInput( PaUtilBufferProcessor* bufferProcessor );

+

+

+/** Provide the buffer processor with a pointer to a host input channel.

+

+ @param bufferProcessor The buffer processor.

+ @param channel The channel number.

+ @param data The buffer.

+ @param stride The stride from one sample to the next, in samples. For

+ interleaved host buffers, the stride will usually be the same as the number of

+ channels in the buffer.

+*/

+void PaUtil_SetInputChannel( PaUtilBufferProcessor* bufferProcessor,

+        unsigned int channel, void *data, unsigned int stride );

+

+

+/** Provide the buffer processor with a pointer to an number of interleaved

+ host input channels.

+

+ @param bufferProcessor The buffer processor.

+ @param firstChannel The first channel number.

+ @param data The buffer.

+ @param channelCount The number of interleaved channels in the buffer. If

+ channelCount is zero, the number of channels specified to

+ PaUtil_InitializeBufferProcessor will be used.

+*/

+void PaUtil_SetInterleavedInputChannels( PaUtilBufferProcessor* bufferProcessor,

+        unsigned int firstChannel, void *data, unsigned int channelCount );

+

+

+/** Provide the buffer processor with a pointer to one non-interleaved host

+ output channel.

+

+ @param bufferProcessor The buffer processor.

+ @param channel The channel number.

+ @param data The buffer.

+*/

+void PaUtil_SetNonInterleavedInputChannel( PaUtilBufferProcessor* bufferProcessor,

+        unsigned int channel, void *data );

+

+

+/** Use for the second buffer half when the input buffer is split in two halves.

+ @see PaUtil_SetInputFrameCount

+*/

+void PaUtil_Set2ndInputFrameCount( PaUtilBufferProcessor* bufferProcessor,

+        unsigned long frameCount );

+

+/** Use for the second buffer half when the input buffer is split in two halves.

+ @see PaUtil_SetInputChannel

+*/

+void PaUtil_Set2ndInputChannel( PaUtilBufferProcessor* bufferProcessor,

+        unsigned int channel, void *data, unsigned int stride );

+

+/** Use for the second buffer half when the input buffer is split in two halves.

+ @see PaUtil_SetInterleavedInputChannels

+*/

+void PaUtil_Set2ndInterleavedInputChannels( PaUtilBufferProcessor* bufferProcessor,

+        unsigned int firstChannel, void *data, unsigned int channelCount );

+

+/** Use for the second buffer half when the input buffer is split in two halves.

+ @see PaUtil_SetNonInterleavedInputChannel

+*/

+void PaUtil_Set2ndNonInterleavedInputChannel( PaUtilBufferProcessor* bufferProcessor,

+        unsigned int channel, void *data );

+

+        

+/** Set the number of frames in the output host buffer(s) specified by the

+ PaUtil_Set*OutputChannel functions.

+

+ @param bufferProcessor The buffer processor.

+

+ @param frameCount The number of host output frames. A 0 frameCount indicates to

+ use the framesPerHostBuffer value passed to PaUtil_InitializeBufferProcessor.

+

+ @see PaUtil_SetOutputChannel, PaUtil_SetInterleavedOutputChannels,

+ PaUtil_SetNonInterleavedOutputChannel

+*/

+void PaUtil_SetOutputFrameCount( PaUtilBufferProcessor* bufferProcessor,

+        unsigned long frameCount );

+

+

+/** Indicate that the output will be discarded. This function should be used

+ when implementing the paNeverDropInput mode for full duplex streams.

+

+ @param bufferProcessor The buffer processor.

+*/

+void PaUtil_SetNoOutput( PaUtilBufferProcessor* bufferProcessor );

+

+

+/** Provide the buffer processor with a pointer to a host output channel.

+

+ @param bufferProcessor The buffer processor.

+ @param channel The channel number.

+ @param data The buffer.

+ @param stride The stride from one sample to the next, in samples. For

+ interleaved host buffers, the stride will usually be the same as the number of

+ channels in the buffer.

+*/

+void PaUtil_SetOutputChannel( PaUtilBufferProcessor* bufferProcessor,

+        unsigned int channel, void *data, unsigned int stride );

+

+

+/** Provide the buffer processor with a pointer to a number of interleaved

+ host output channels.

+

+ @param bufferProcessor The buffer processor.

+ @param firstChannel The first channel number.

+ @param data The buffer.

+ @param channelCount The number of interleaved channels in the buffer. If

+ channelCount is zero, the number of channels specified to

+ PaUtil_InitializeBufferProcessor will be used.

+*/

+void PaUtil_SetInterleavedOutputChannels( PaUtilBufferProcessor* bufferProcessor,

+        unsigned int firstChannel, void *data, unsigned int channelCount );

+

+        

+/** Provide the buffer processor with a pointer to one non-interleaved host

+ output channel.

+

+ @param bufferProcessor The buffer processor.

+ @param channel The channel number.

+ @param data The buffer.

+*/

+void PaUtil_SetNonInterleavedOutputChannel( PaUtilBufferProcessor* bufferProcessor,

+        unsigned int channel, void *data );

+

+

+/** Use for the second buffer half when the output buffer is split in two halves.

+ @see PaUtil_SetOutputFrameCount

+*/

+void PaUtil_Set2ndOutputFrameCount( PaUtilBufferProcessor* bufferProcessor,

+        unsigned long frameCount );

+

+/** Use for the second buffer half when the output buffer is split in two halves.

+ @see PaUtil_SetOutputChannel

+*/

+void PaUtil_Set2ndOutputChannel( PaUtilBufferProcessor* bufferProcessor,

+        unsigned int channel, void *data, unsigned int stride );

+

+/** Use for the second buffer half when the output buffer is split in two halves.

+ @see PaUtil_SetInterleavedOutputChannels

+*/

+void PaUtil_Set2ndInterleavedOutputChannels( PaUtilBufferProcessor* bufferProcessor,

+        unsigned int firstChannel, void *data, unsigned int channelCount );

+

+/** Use for the second buffer half when the output buffer is split in two halves.

+ @see PaUtil_SetNonInterleavedOutputChannel

+*/

+void PaUtil_Set2ndNonInterleavedOutputChannel( PaUtilBufferProcessor* bufferProcessor,

+        unsigned int channel, void *data );

+

+/*@}*/

+

+

+/** @name Buffer processing functions for callback streams

+*/

+/*@{*/

+

+/** Commence processing a host buffer (or a pair of host buffers in the

+ full-duplex case) for a callback stream.

+

+ @param bufferProcessor The buffer processor.

+

+ @param timeInfo Timing information for the first sample of the host

+ buffer(s). This information may be adjusted when buffer adaption is being

+ performed.

+

+ @param callbackStatusFlags Flags indicating whether underruns and overruns

+ have occurred since the last time the buffer processor was called.

+*/

+void PaUtil_BeginBufferProcessing( PaUtilBufferProcessor* bufferProcessor,

+        PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags callbackStatusFlags );

+

+        

+/** Finish processing a host buffer (or a pair of host buffers in the

+ full-duplex case) for a callback stream.

+

+ @param bufferProcessor The buffer processor.

+ 

+ @param callbackResult On input, indicates a previous callback result, and on

+ exit, the result of the user stream callback, if it is called.

+ On entry callbackResult should contain one of { paContinue, paComplete, or

+ paAbort}. If paComplete is passed, the stream callback will not be called

+ but any audio that was generated by previous stream callbacks will be copied

+ to the output buffer(s). You can check whether the buffer processor's internal

+ buffer is empty by calling PaUtil_IsBufferProcessorOutputEmpty.

+

+ If the stream callback is called its result is stored in *callbackResult. If

+ the stream callback returns paComplete or paAbort, all output buffers will be

+ full of valid data - some of which may be zeros to acount for data that

+ wasn't generated by the terminating callback.

+

+ @return The number of frames processed. This usually corresponds to the

+ number of frames specified by the PaUtil_Set*FrameCount functions, exept in

+ the paUtilVariableHostBufferSizePartialUsageAllowed buffer size mode when a

+ smaller value may be returned.

+*/

+unsigned long PaUtil_EndBufferProcessing( PaUtilBufferProcessor* bufferProcessor,

+        int *callbackResult );

+

+

+/** Determine whether any callback generated output remains in the bufffer

+ processor's internal buffers. This method may be used to determine when to

+ continue calling PaUtil_EndBufferProcessing() after the callback has returned

+ a callbackResult of paComplete.

+

+ @param bufferProcessor The buffer processor.

+ 

+ @return Returns non-zero when callback generated output remains in the internal

+ buffer and zero (0) when there internal buffer contains no callback generated

+ data.

+*/

+int PaUtil_IsBufferProcessorOutputEmpty( PaUtilBufferProcessor* bufferProcessor );

+

+/*@}*/

+

+

+/** @name Buffer processing functions for blocking read/write streams

+*/

+/*@{*/

+

+/** Copy samples from host input channels set up by the PaUtil_Set*InputChannels

+ functions to a user supplied buffer. This function is intended for use with

+ blocking read/write streams. Copies the minimum of the number of

+ user frames (specified by the frameCount parameter) and the number of available

+ host frames (specified in a previous call to SetInputFrameCount()).

+

+ @param bufferProcessor The buffer processor.

+

+ @param buffer A pointer to the user buffer pointer, or a pointer to a pointer

+ to an array of user buffer pointers for a non-interleaved stream. It is

+ important that this parameter points to a copy of the user buffer pointers,

+ not to the actual user buffer pointers, because this function updates the

+ pointers before returning.

+

+ @param frameCount The number of frames of data in the buffer(s) pointed to by

+ the buffer parameter.

+

+ @return The number of frames copied. The buffer pointer(s) pointed to by the

+ buffer parameter are advanced to point to the frame(s) following the last one

+ filled.

+*/

+unsigned long PaUtil_CopyInput( PaUtilBufferProcessor* bufferProcessor,

+        void **buffer, unsigned long frameCount );

+

+

+/* Copy samples from a user supplied buffer to host output channels set up by

+ the PaUtil_Set*OutputChannels functions. This function is intended for use with

+ blocking read/write streams. Copies the minimum of the number of

+ user frames (specified by the frameCount parameter) and the number of

+ host frames (specified in a previous call to SetOutputFrameCount()).

+

+ @param bufferProcessor The buffer processor.

+

+ @param buffer A pointer to the user buffer pointer, or a pointer to a pointer

+ to an array of user buffer pointers for a non-interleaved stream. It is

+ important that this parameter points to a copy of the user buffer pointers,

+ not to the actual user buffer pointers, because this function updates the

+ pointers before returning.

+

+ @param frameCount The number of frames of data in the buffer(s) pointed to by

+ the buffer parameter.

+

+ @return The number of frames copied. The buffer pointer(s) pointed to by the

+ buffer parameter are advanced to point to the frame(s) following the last one

+ copied.

+*/

+unsigned long PaUtil_CopyOutput( PaUtilBufferProcessor* bufferProcessor,

+        const void ** buffer, unsigned long frameCount );

+

+

+/* Zero samples in host output channels set up by the PaUtil_Set*OutputChannels

+ functions. This function is useful for flushing streams.

+ Zeros the minimum of frameCount and the number of host frames specified in a

+ previous call to SetOutputFrameCount().

+

+ @param bufferProcessor The buffer processor.

+

+ @param frameCount The maximum number of frames to zero.

+ 

+ @return The number of frames zeroed.

+*/

+unsigned long PaUtil_ZeroOutput( PaUtilBufferProcessor* bufferProcessor,

+        unsigned long frameCount );

+

+

+/*@}*/

+

+

+#ifdef __cplusplus

+}

+#endif /* __cplusplus */

+#endif /* PA_PROCESS_H */

diff --git a/src/engine/external/portaudio/pa_ringbuffer.c b/src/engine/external/portaudio/pa_ringbuffer.c
new file mode 100644
index 00000000..e115915b
--- /dev/null
+++ b/src/engine/external/portaudio/pa_ringbuffer.c
@@ -0,0 +1,285 @@
+/*

+ * $Id: pa_ringbuffer.c 1240 2007-07-17 13:05:07Z bjornroche $

+ * Portable Audio I/O Library

+ * Ring Buffer utility.

+ *

+ * Author: Phil Burk, http://www.softsynth.com

+ * modified for SMP safety on Mac OS X by Bjorn Roche

+ * modified for SMP safety on Linux by Leland Lucius

+ * also, allowed for const where possible

+ * Note that this is safe only for a single-thread reader and a

+ * single-thread writer.

+ *

+ * This program uses the PortAudio Portable Audio Library.

+ * For more information see: http://www.portaudio.com

+ * Copyright (c) 1999-2000 Ross Bencina and Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/**

+ @file

+ @ingroup common_src

+*/

+

+#include <stdio.h>

+#include <stdlib.h>

+#include <math.h>

+#include "pa_ringbuffer.h"

+#include <string.h>

+

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

+ * First, we'll define some memory barrier primitives based on the system.

+ * right now only OS X, FreeBSD, and Linux are supported. In addition to providing

+ * memory barriers, these functions should ensure that data cached in registers

+ * is written out to cache where it can be snooped by other CPUs. (ie, the volatile

+ * keyword should not be required)

+ *

+ * the primitives that must be defined are:

+ *

+ * PaUtil_FullMemoryBarrier()

+ * PaUtil_ReadMemoryBarrier()

+ * PaUtil_WriteMemoryBarrier()

+ *

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

+

+#if defined(__APPLE__)

+#   include <libkern/OSAtomic.h>

+    /* Here are the memory barrier functions. Mac OS X only provides

+       full memory barriers, so the three types of barriers are the same,

+       however, these barriers are superior to compiler-based ones. */

+#   define PaUtil_FullMemoryBarrier()  OSMemoryBarrier()

+#   define PaUtil_ReadMemoryBarrier()  OSMemoryBarrier()

+#   define PaUtil_WriteMemoryBarrier() OSMemoryBarrier()

+#elif defined(__GNUC__)

+    /* GCC >= 4.1 has built-in intrinsics. We'll use those */

+#   if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)

+#      define PaUtil_FullMemoryBarrier()  __sync_synchronize()

+#      define PaUtil_ReadMemoryBarrier()  __sync_synchronize()

+#      define PaUtil_WriteMemoryBarrier() __sync_synchronize()

+    /* as a fallback, GCC understands volatile asm and "memory" to mean it

+     * should not reorder memory read/writes */

+#   elif defined( __PPC__ )

+#      define PaUtil_FullMemoryBarrier()  asm volatile("sync":::"memory")

+#      define PaUtil_ReadMemoryBarrier()  asm volatile("sync":::"memory")

+#      define PaUtil_WriteMemoryBarrier() asm volatile("sync":::"memory")

+#   elif defined( __i386__ ) || defined( __i486__ ) || defined( __i586__ ) || defined( __i686__ ) || defined( __x86_64__ )

+#      define PaUtil_FullMemoryBarrier()  asm volatile("mfence":::"memory")

+#      define PaUtil_ReadMemoryBarrier()  asm volatile("lfence":::"memory")

+#      define PaUtil_WriteMemoryBarrier() asm volatile("sfence":::"memory")

+#   else

+#      ifdef ALLOW_SMP_DANGERS

+#         warning Memory barriers not defined on this system or system unknown

+#         warning For SMP safety, you should fix this.

+#         define PaUtil_FullMemoryBarrier()

+#         define PaUtil_ReadMemoryBarrier()

+#         define PaUtil_WriteMemoryBarrier()

+#      else

+#         error Memory barriers are not defined on this system. You can still compile by defining ALLOW_SMP_DANGERS, but SMP safety will not be guaranteed.

+#      endif

+#   endif

+#else

+#   ifdef ALLOW_SMP_DANGERS

+#      warning Memory barriers not defined on this system or system unknown

+#      warning For SMP safety, you should fix this.

+#      define PaUtil_FullMemoryBarrier()

+#      define PaUtil_ReadMemoryBarrier()

+#      define PaUtil_WriteMemoryBarrier()

+#   else

+#      error Memory barriers are not defined on this system. You can still compile by defining ALLOW_SMP_DANGERS, but SMP safety will not be guaranteed.

+#   endif

+#endif

+

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

+ * Initialize FIFO.

+ * numBytes must be power of 2, returns -1 if not.

+ */

+long PaUtil_InitializeRingBuffer( PaUtilRingBuffer *rbuf, long numBytes, void *dataPtr )

+{

+    if( ((numBytes-1) & numBytes) != 0) return -1; /* Not Power of two. */

+    rbuf->bufferSize = numBytes;

+    rbuf->buffer = (char *)dataPtr;

+    PaUtil_FlushRingBuffer( rbuf );

+    rbuf->bigMask = (numBytes*2)-1;

+    rbuf->smallMask = (numBytes)-1;

+    return 0;

+}

+

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

+** Return number of bytes available for reading. */

+long PaUtil_GetRingBufferReadAvailable( PaUtilRingBuffer *rbuf )

+{

+    PaUtil_ReadMemoryBarrier();

+    return ( (rbuf->writeIndex - rbuf->readIndex) & rbuf->bigMask );

+}

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

+** Return number of bytes available for writing. */

+long PaUtil_GetRingBufferWriteAvailable( PaUtilRingBuffer *rbuf )

+{

+    /* Since we are calling PaUtil_GetRingBufferReadAvailable, we don't need an aditional MB */

+    return ( rbuf->bufferSize - PaUtil_GetRingBufferReadAvailable(rbuf));

+}

+

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

+** Clear buffer. Should only be called when buffer is NOT being read. */

+void PaUtil_FlushRingBuffer( PaUtilRingBuffer *rbuf )

+{

+    rbuf->writeIndex = rbuf->readIndex = 0;

+}

+

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

+** Get address of region(s) to which we can write data.

+** If the region is contiguous, size2 will be zero.

+** If non-contiguous, size2 will be the size of second region.

+** Returns room available to be written or numBytes, whichever is smaller.

+*/

+long PaUtil_GetRingBufferWriteRegions( PaUtilRingBuffer *rbuf, long numBytes,

+                                       void **dataPtr1, long *sizePtr1,

+                                       void **dataPtr2, long *sizePtr2 )

+{

+    long   index;

+    long   available = PaUtil_GetRingBufferWriteAvailable( rbuf );

+    if( numBytes > available ) numBytes = available;

+    /* Check to see if write is not contiguous. */

+    index = rbuf->writeIndex & rbuf->smallMask;

+    if( (index + numBytes) > rbuf->bufferSize )

+    {

+        /* Write data in two blocks that wrap the buffer. */

+        long   firstHalf = rbuf->bufferSize - index;

+        *dataPtr1 = &rbuf->buffer[index];

+        *sizePtr1 = firstHalf;

+        *dataPtr2 = &rbuf->buffer[0];

+        *sizePtr2 = numBytes - firstHalf;

+    }

+    else

+    {

+        *dataPtr1 = &rbuf->buffer[index];

+        *sizePtr1 = numBytes;

+        *dataPtr2 = NULL;

+        *sizePtr2 = 0;

+    }

+    return numBytes;

+}

+

+

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

+*/

+long PaUtil_AdvanceRingBufferWriteIndex( PaUtilRingBuffer *rbuf, long numBytes )

+{

+    /* we need to ensure that previous writes are seen before we update the write index */

+    PaUtil_WriteMemoryBarrier();

+    return rbuf->writeIndex = (rbuf->writeIndex + numBytes) & rbuf->bigMask;

+}

+

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

+** Get address of region(s) from which we can read data.

+** If the region is contiguous, size2 will be zero.

+** If non-contiguous, size2 will be the size of second region.

+** Returns room available to be written or numBytes, whichever is smaller.

+*/

+long PaUtil_GetRingBufferReadRegions( PaUtilRingBuffer *rbuf, long numBytes,

+                                void **dataPtr1, long *sizePtr1,

+                                void **dataPtr2, long *sizePtr2 )

+{

+    long   index;

+    long   available = PaUtil_GetRingBufferReadAvailable( rbuf );

+    if( numBytes > available ) numBytes = available;

+    /* Check to see if read is not contiguous. */

+    index = rbuf->readIndex & rbuf->smallMask;

+    if( (index + numBytes) > rbuf->bufferSize )

+    {

+        /* Write data in two blocks that wrap the buffer. */

+        long firstHalf = rbuf->bufferSize - index;

+        *dataPtr1 = &rbuf->buffer[index];

+        *sizePtr1 = firstHalf;

+        *dataPtr2 = &rbuf->buffer[0];

+        *sizePtr2 = numBytes - firstHalf;

+    }

+    else

+    {

+        *dataPtr1 = &rbuf->buffer[index];

+        *sizePtr1 = numBytes;

+        *dataPtr2 = NULL;

+        *sizePtr2 = 0;

+    }

+    return numBytes;

+}

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

+*/

+long PaUtil_AdvanceRingBufferReadIndex( PaUtilRingBuffer *rbuf, long numBytes )

+{

+    /* we need to ensure that previous writes are always seen before updating the index. */

+    PaUtil_WriteMemoryBarrier();

+    return rbuf->readIndex = (rbuf->readIndex + numBytes) & rbuf->bigMask;

+}

+

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

+** Return bytes written. */

+long PaUtil_WriteRingBuffer( PaUtilRingBuffer *rbuf, const void *data, long numBytes )

+{

+    long size1, size2, numWritten;

+    void *data1, *data2;

+    numWritten = PaUtil_GetRingBufferWriteRegions( rbuf, numBytes, &data1, &size1, &data2, &size2 );

+    if( size2 > 0 )

+    {

+

+        memcpy( data1, data, size1 );

+        data = ((char *)data) + size1;

+        memcpy( data2, data, size2 );

+    }

+    else

+    {

+        memcpy( data1, data, size1 );

+    }

+    PaUtil_AdvanceRingBufferWriteIndex( rbuf, numWritten );

+    return numWritten;

+}

+

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

+** Return bytes read. */

+long PaUtil_ReadRingBuffer( PaUtilRingBuffer *rbuf, void *data, long numBytes )

+{

+    long size1, size2, numRead;

+    void *data1, *data2;

+    numRead = PaUtil_GetRingBufferReadRegions( rbuf, numBytes, &data1, &size1, &data2, &size2 );

+    if( size2 > 0 )

+    {

+        memcpy( data, data1, size1 );

+        data = ((char *)data) + size1;

+        memcpy( data, data2, size2 );

+    }

+    else

+    {

+        memcpy( data, data1, size1 );

+    }

+    PaUtil_AdvanceRingBufferReadIndex( rbuf, numRead );

+    return numRead;

+}

diff --git a/src/engine/external/portaudio/pa_ringbuffer.h b/src/engine/external/portaudio/pa_ringbuffer.h
new file mode 100644
index 00000000..395aad22
--- /dev/null
+++ b/src/engine/external/portaudio/pa_ringbuffer.h
@@ -0,0 +1,198 @@
+#ifndef PA_RINGBUFFER_H

+#define PA_RINGBUFFER_H

+/*

+ * $Id: pa_ringbuffer.h 1151 2006-11-29 02:11:16Z leland_lucius $

+ * Portable Audio I/O Library

+ * Ring Buffer utility.

+ *

+ * Author: Phil Burk, http://www.softsynth.com

+ * modified for SMP safety on OS X by Bjorn Roche.

+ * also allowed for const where possible.

+ * Note that this is safe only for a single-thread reader

+ * and a single-thread writer.

+ *

+ * This program is distributed with the PortAudio Portable Audio Library.

+ * For more information see: http://www.portaudio.com

+ * Copyright (c) 1999-2000 Ross Bencina and Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup common_src

+*/

+

+#ifdef __cplusplus

+extern "C"

+{

+#endif /* __cplusplus */

+

+typedef struct PaUtilRingBuffer

+{

+    long   bufferSize; /* Number of bytes in FIFO. Power of 2. Set by PaUtil_InitRingBuffer. */

+    long   writeIndex; /* Index of next writable byte. Set by PaUtil_AdvanceRingBufferWriteIndex. */

+    long   readIndex;  /* Index of next readable byte. Set by PaUtil_AdvanceRingBufferReadIndex. */

+    long   bigMask;    /* Used for wrapping indices with extra bit to distinguish full/empty. */

+    long   smallMask;  /* Used for fitting indices to buffer. */

+    char  *buffer;

+}PaUtilRingBuffer;

+

+/** Initialize Ring Buffer.

+

+ @param rbuf The ring buffer.

+

+ @param numBytes The number of bytes in the buffer and must be power of 2.

+

+ @param dataPtr A pointer to a previously allocated area where the data

+ will be maintained.  It must be numBytes long.

+

+ @return -1 if numBytes is not a power of 2, otherwise 0.

+*/

+long PaUtil_InitializeRingBuffer( PaUtilRingBuffer *rbuf, long numBytes, void *dataPtr );

+

+/** Clear buffer. Should only be called when buffer is NOT being read.

+

+ @param rbuf The ring buffer.

+*/

+void PaUtil_FlushRingBuffer( PaUtilRingBuffer *rbuf );

+

+/** Retrieve the number of bytes available in the ring buffer for writing.

+

+ @param rbuf The ring buffer.

+

+ @return The number of bytes available for writing.

+*/

+long PaUtil_GetRingBufferWriteAvailable( PaUtilRingBuffer *rbuf );

+

+/** Retrieve the number of bytes available in the ring buffer for reading.

+

+ @param rbuf The ring buffer.

+

+ @return The number of bytes available for reading.

+*/

+long PaUtil_GetRingBufferReadAvailable( PaUtilRingBuffer *rbuf );

+

+/** Write data to the ring buffer.

+

+ @param rbuf The ring buffer.

+

+ @param data The address of new data to write to the buffer.

+

+ @param numBytes The number of bytes to be written.

+

+ @return The number of bytes written.

+*/

+long PaUtil_WriteRingBuffer( PaUtilRingBuffer *rbuf, const void *data, long numBytes );

+

+/** Read data from the ring buffer.

+

+ @param rbuf The ring buffer.

+

+ @param data The address where the data should be stored.

+

+ @param numBytes The number of bytes to be read.

+

+ @return The number of bytes read.

+*/

+long PaUtil_ReadRingBuffer( PaUtilRingBuffer *rbuf, void *data, long numBytes );

+

+/** Get address of region(s) to which we can write data.

+

+ @param rbuf The ring buffer.

+

+ @param numBytes The number of bytes desired.

+

+ @param dataPtr1 The address where the first (or only) region pointer will be

+ stored.

+

+ @param sizePtr1 The address where the first (or only) region length will be

+ stored.

+

+ @param dataPtr2 The address where the second region pointer will be stored if

+ the first region is too small to satisfy numBytes.

+

+ @param sizePtr2 The address where the second region length will be stored if

+ the first region is too small to satisfy numBytes.

+

+ @return The room available to be written or numBytes, whichever is smaller.

+*/

+long PaUtil_GetRingBufferWriteRegions( PaUtilRingBuffer *rbuf, long numBytes,

+                                       void **dataPtr1, long *sizePtr1,

+                                       void **dataPtr2, long *sizePtr2 );

+

+/** Advance the write index to the next location to be written.

+

+ @param rbuf The ring buffer.

+

+ @param numBytes The number of bytes to advance.

+

+ @return The new position.

+*/

+long PaUtil_AdvanceRingBufferWriteIndex( PaUtilRingBuffer *rbuf, long numBytes );

+

+/** Get address of region(s) from which we can write data.

+

+ @param rbuf The ring buffer.

+

+ @param numBytes The number of bytes desired.

+

+ @param dataPtr1 The address where the first (or only) region pointer will be

+ stored.

+

+ @param sizePtr1 The address where the first (or only) region length will be

+ stored.

+

+ @param dataPtr2 The address where the second region pointer will be stored if

+ the first region is too small to satisfy numBytes.

+

+ @param sizePtr2 The address where the second region length will be stored if

+ the first region is too small to satisfy numBytes.

+

+ @return The number of bytes available for reading.

+*/

+long PaUtil_GetRingBufferReadRegions( PaUtilRingBuffer *rbuf, long numBytes,

+                                      void **dataPtr1, long *sizePtr1,

+                                      void **dataPtr2, long *sizePtr2 );

+

+/** Advance the read index to the next location to be read.

+

+ @param rbuf The ring buffer.

+

+ @param numBytes The number of bytes to advance.

+

+ @return The new position.

+*/

+long PaUtil_AdvanceRingBufferReadIndex( PaUtilRingBuffer *rbuf, long numBytes );

+

+#ifdef __cplusplus

+}

+#endif /* __cplusplus */

+#endif /* PA_RINGBUFFER_H */

diff --git a/src/engine/external/portaudio/pa_skeleton.c b/src/engine/external/portaudio/pa_skeleton.c
new file mode 100644
index 00000000..ef4b6f6d
--- /dev/null
+++ b/src/engine/external/portaudio/pa_skeleton.c
@@ -0,0 +1,816 @@
+/*

+ * $Id: pa_skeleton.c 1097 2006-08-26 08:27:53Z rossb $

+ * Portable Audio I/O Library skeleton implementation

+ * demonstrates how to use the common functions to implement support

+ * for a host API

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup common_src

+

+ @brief Skeleton implementation of support for a host API.

+

+ @note This file is provided as a starting point for implementing support for

+ a new host API. IMPLEMENT ME comments are used to indicate functionality

+ which much be customised for each implementation.

+*/

+

+

+#include <string.h> /* strlen() */

+

+#include "pa_util.h"

+#include "pa_allocation.h"

+#include "pa_hostapi.h"

+#include "pa_stream.h"

+#include "pa_cpuload.h"

+#include "pa_process.h"

+

+

+/* prototypes for functions declared in this file */

+

+#ifdef __cplusplus

+extern "C"

+{

+#endif /* __cplusplus */

+

+PaError PaSkeleton_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );

+

+#ifdef __cplusplus

+}

+#endif /* __cplusplus */

+

+

+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );

+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,

+                                  const PaStreamParameters *inputParameters,

+                                  const PaStreamParameters *outputParameters,

+                                  double sampleRate );

+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,

+                           PaStream** s,

+                           const PaStreamParameters *inputParameters,

+                           const PaStreamParameters *outputParameters,

+                           double sampleRate,

+                           unsigned long framesPerBuffer,

+                           PaStreamFlags streamFlags,

+                           PaStreamCallback *streamCallback,

+                           void *userData );

+static PaError CloseStream( PaStream* stream );

+static PaError StartStream( PaStream *stream );

+static PaError StopStream( PaStream *stream );

+static PaError AbortStream( PaStream *stream );

+static PaError IsStreamStopped( PaStream *s );

+static PaError IsStreamActive( PaStream *stream );

+static PaTime GetStreamTime( PaStream *stream );

+static double GetStreamCpuLoad( PaStream* stream );

+static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );

+static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );

+static signed long GetStreamReadAvailable( PaStream* stream );

+static signed long GetStreamWriteAvailable( PaStream* stream );

+

+

+/* IMPLEMENT ME: a macro like the following one should be used for reporting

+ host errors */

+#define PA_SKELETON_SET_LAST_HOST_ERROR( errorCode, errorText ) \

+    PaUtil_SetLastHostErrorInfo( paInDevelopment, errorCode, errorText )

+

+/* PaSkeletonHostApiRepresentation - host api datastructure specific to this implementation */

+

+typedef struct

+{

+    PaUtilHostApiRepresentation inheritedHostApiRep;

+    PaUtilStreamInterface callbackStreamInterface;

+    PaUtilStreamInterface blockingStreamInterface;

+

+    PaUtilAllocationGroup *allocations;

+

+    /* implementation specific data goes here */

+}

+PaSkeletonHostApiRepresentation;  /* IMPLEMENT ME: rename this */

+

+

+PaError PaSkeleton_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )

+{

+    PaError result = paNoError;

+    int i, deviceCount;

+    PaSkeletonHostApiRepresentation *skeletonHostApi;

+    PaDeviceInfo *deviceInfoArray;

+

+    skeletonHostApi = (PaSkeletonHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaSkeletonHostApiRepresentation) );

+    if( !skeletonHostApi )

+    {

+        result = paInsufficientMemory;

+        goto error;

+    }

+

+    skeletonHostApi->allocations = PaUtil_CreateAllocationGroup();

+    if( !skeletonHostApi->allocations )

+    {

+        result = paInsufficientMemory;

+        goto error;

+    }

+

+    *hostApi = &skeletonHostApi->inheritedHostApiRep;

+    (*hostApi)->info.structVersion = 1;

+    (*hostApi)->info.type = paInDevelopment;            /* IMPLEMENT ME: change to correct type id */

+    (*hostApi)->info.name = "skeleton implementation";  /* IMPLEMENT ME: change to correct name */

+

+    (*hostApi)->info.defaultInputDevice = paNoDevice;  /* IMPLEMENT ME */

+    (*hostApi)->info.defaultOutputDevice = paNoDevice; /* IMPLEMENT ME */

+

+    (*hostApi)->info.deviceCount = 0;  

+

+    deviceCount = 0; /* IMPLEMENT ME */

+    

+    if( deviceCount > 0 )

+    {

+        (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(

+                skeletonHostApi->allocations, sizeof(PaDeviceInfo*) * deviceCount );

+        if( !(*hostApi)->deviceInfos )

+        {

+            result = paInsufficientMemory;

+            goto error;

+        }

+

+        /* allocate all device info structs in a contiguous block */

+        deviceInfoArray = (PaDeviceInfo*)PaUtil_GroupAllocateMemory(

+                skeletonHostApi->allocations, sizeof(PaDeviceInfo) * deviceCount );

+        if( !deviceInfoArray )

+        {

+            result = paInsufficientMemory;

+            goto error;

+        }

+

+        for( i=0; i < deviceCount; ++i )

+        {

+            PaDeviceInfo *deviceInfo = &deviceInfoArray[i];

+            deviceInfo->structVersion = 2;

+            deviceInfo->hostApi = hostApiIndex;

+            deviceInfo->name = 0; /* IMPLEMENT ME: allocate block and copy name eg:

+                deviceName = (char*)PaUtil_GroupAllocateMemory( skeletonHostApi->allocations, strlen(srcName) + 1 );

+                if( !deviceName )

+                {

+                    result = paInsufficientMemory;

+                    goto error;

+                }

+                strcpy( deviceName, srcName );

+                deviceInfo->name = deviceName;

+            */

+

+            deviceInfo->maxInputChannels = 0;  /* IMPLEMENT ME */

+            deviceInfo->maxOutputChannels = 0;  /* IMPLEMENT ME */

+            

+            deviceInfo->defaultLowInputLatency = 0.;  /* IMPLEMENT ME */

+            deviceInfo->defaultLowOutputLatency = 0.;  /* IMPLEMENT ME */

+            deviceInfo->defaultHighInputLatency = 0.;  /* IMPLEMENT ME */

+            deviceInfo->defaultHighOutputLatency = 0.;  /* IMPLEMENT ME */  

+

+            deviceInfo->defaultSampleRate = 0.; /* IMPLEMENT ME */

+            

+            (*hostApi)->deviceInfos[i] = deviceInfo;

+            ++(*hostApi)->info.deviceCount;

+        }

+    }

+

+    (*hostApi)->Terminate = Terminate;

+    (*hostApi)->OpenStream = OpenStream;

+    (*hostApi)->IsFormatSupported = IsFormatSupported;

+

+    PaUtil_InitializeStreamInterface( &skeletonHostApi->callbackStreamInterface, CloseStream, StartStream,

+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,

+                                      GetStreamTime, GetStreamCpuLoad,

+                                      PaUtil_DummyRead, PaUtil_DummyWrite,

+                                      PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );

+

+    PaUtil_InitializeStreamInterface( &skeletonHostApi->blockingStreamInterface, CloseStream, StartStream,

+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,

+                                      GetStreamTime, PaUtil_DummyGetCpuLoad,

+                                      ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );

+

+    return result;

+

+error:

+    if( skeletonHostApi )

+    {

+        if( skeletonHostApi->allocations )

+        {

+            PaUtil_FreeAllAllocations( skeletonHostApi->allocations );

+            PaUtil_DestroyAllocationGroup( skeletonHostApi->allocations );

+        }

+                

+        PaUtil_FreeMemory( skeletonHostApi );

+    }

+    return result;

+}

+

+

+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )

+{

+    PaSkeletonHostApiRepresentation *skeletonHostApi = (PaSkeletonHostApiRepresentation*)hostApi;

+

+    /*

+        IMPLEMENT ME:

+            - clean up any resources not handled by the allocation group

+    */

+

+    if( skeletonHostApi->allocations )

+    {

+        PaUtil_FreeAllAllocations( skeletonHostApi->allocations );

+        PaUtil_DestroyAllocationGroup( skeletonHostApi->allocations );

+    }

+

+    PaUtil_FreeMemory( skeletonHostApi );

+}

+

+

+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,

+                                  const PaStreamParameters *inputParameters,

+                                  const PaStreamParameters *outputParameters,

+                                  double sampleRate )

+{

+    int inputChannelCount, outputChannelCount;

+    PaSampleFormat inputSampleFormat, outputSampleFormat;

+    

+    if( inputParameters )

+    {

+        inputChannelCount = inputParameters->channelCount;

+        inputSampleFormat = inputParameters->sampleFormat;

+

+        /* all standard sample formats are supported by the buffer adapter,

+            this implementation doesn't support any custom sample formats */

+        if( inputSampleFormat & paCustomFormat )

+            return paSampleFormatNotSupported;

+            

+        /* unless alternate device specification is supported, reject the use of

+            paUseHostApiSpecificDeviceSpecification */

+

+        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )

+            return paInvalidDevice;

+

+        /* check that input device can support inputChannelCount */

+        if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )

+            return paInvalidChannelCount;

+

+        /* validate inputStreamInfo */

+        if( inputParameters->hostApiSpecificStreamInfo )

+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */

+    }

+    else

+    {

+        inputChannelCount = 0;

+    }

+

+    if( outputParameters )

+    {

+        outputChannelCount = outputParameters->channelCount;

+        outputSampleFormat = outputParameters->sampleFormat;

+

+        /* all standard sample formats are supported by the buffer adapter,

+            this implementation doesn't support any custom sample formats */

+        if( outputSampleFormat & paCustomFormat )

+            return paSampleFormatNotSupported;

+            

+        /* unless alternate device specification is supported, reject the use of

+            paUseHostApiSpecificDeviceSpecification */

+

+        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )

+            return paInvalidDevice;

+

+        /* check that output device can support outputChannelCount */

+        if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )

+            return paInvalidChannelCount;

+

+        /* validate outputStreamInfo */

+        if( outputParameters->hostApiSpecificStreamInfo )

+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */

+    }

+    else

+    {

+        outputChannelCount = 0;

+    }

+    

+    /*

+        IMPLEMENT ME:

+

+            - if a full duplex stream is requested, check that the combination

+                of input and output parameters is supported if necessary

+

+            - check that the device supports sampleRate

+

+        Because the buffer adapter handles conversion between all standard

+        sample formats, the following checks are only required if paCustomFormat

+        is implemented, or under some other unusual conditions.

+

+            - check that input device can support inputSampleFormat, or that

+                we have the capability to convert from inputSampleFormat to

+                a native format

+

+            - check that output device can support outputSampleFormat, or that

+                we have the capability to convert from outputSampleFormat to

+                a native format

+    */

+

+

+    /* suppress unused variable warnings */

+    (void) sampleRate;

+

+    return paFormatIsSupported;

+}

+

+/* PaSkeletonStream - a stream data structure specifically for this implementation */

+

+typedef struct PaSkeletonStream

+{ /* IMPLEMENT ME: rename this */

+    PaUtilStreamRepresentation streamRepresentation;

+    PaUtilCpuLoadMeasurer cpuLoadMeasurer;

+    PaUtilBufferProcessor bufferProcessor;

+

+    /* IMPLEMENT ME:

+            - implementation specific data goes here

+    */

+    unsigned long framesPerHostCallback; /* just an example */

+}

+PaSkeletonStream;

+

+/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */

+

+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,

+                           PaStream** s,

+                           const PaStreamParameters *inputParameters,

+                           const PaStreamParameters *outputParameters,

+                           double sampleRate,

+                           unsigned long framesPerBuffer,

+                           PaStreamFlags streamFlags,

+                           PaStreamCallback *streamCallback,

+                           void *userData )

+{

+    PaError result = paNoError;

+    PaSkeletonHostApiRepresentation *skeletonHostApi = (PaSkeletonHostApiRepresentation*)hostApi;

+    PaSkeletonStream *stream = 0;

+    unsigned long framesPerHostBuffer = framesPerBuffer; /* these may not be equivalent for all implementations */

+    int inputChannelCount, outputChannelCount;

+    PaSampleFormat inputSampleFormat, outputSampleFormat;

+    PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;

+

+

+    if( inputParameters )

+    {

+        inputChannelCount = inputParameters->channelCount;

+        inputSampleFormat = inputParameters->sampleFormat;

+

+        /* unless alternate device specification is supported, reject the use of

+            paUseHostApiSpecificDeviceSpecification */

+

+        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )

+            return paInvalidDevice;

+

+        /* check that input device can support inputChannelCount */

+        if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )

+            return paInvalidChannelCount;

+

+        /* validate inputStreamInfo */

+        if( inputParameters->hostApiSpecificStreamInfo )

+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */

+

+        /* IMPLEMENT ME - establish which  host formats are available */

+        hostInputSampleFormat =

+            PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, inputSampleFormat );

+    }

+    else

+    {

+        inputChannelCount = 0;

+        inputSampleFormat = hostInputSampleFormat = paInt16; /* Surpress 'uninitialised var' warnings. */

+    }

+

+    if( outputParameters )

+    {

+        outputChannelCount = outputParameters->channelCount;

+        outputSampleFormat = outputParameters->sampleFormat;

+        

+        /* unless alternate device specification is supported, reject the use of

+            paUseHostApiSpecificDeviceSpecification */

+

+        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )

+            return paInvalidDevice;

+

+        /* check that output device can support inputChannelCount */

+        if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )

+            return paInvalidChannelCount;

+

+        /* validate outputStreamInfo */

+        if( outputParameters->hostApiSpecificStreamInfo )

+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */

+

+        /* IMPLEMENT ME - establish which  host formats are available */

+        hostOutputSampleFormat =

+            PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, outputSampleFormat );

+    }

+    else

+    {

+        outputChannelCount = 0;

+        outputSampleFormat = hostOutputSampleFormat = paInt16; /* Surpress 'uninitialized var' warnings. */

+    }

+

+    /*

+        IMPLEMENT ME:

+

+        ( the following two checks are taken care of by PaUtil_InitializeBufferProcessor() FIXME - checks needed? )

+

+            - check that input device can support inputSampleFormat, or that

+                we have the capability to convert from outputSampleFormat to

+                a native format

+

+            - check that output device can support outputSampleFormat, or that

+                we have the capability to convert from outputSampleFormat to

+                a native format

+

+            - if a full duplex stream is requested, check that the combination

+                of input and output parameters is supported

+

+            - check that the device supports sampleRate

+

+            - alter sampleRate to a close allowable rate if possible / necessary

+

+            - validate suggestedInputLatency and suggestedOutputLatency parameters,

+                use default values where necessary

+    */

+

+

+

+

+    /* validate platform specific flags */

+    if( (streamFlags & paPlatformSpecificFlags) != 0 )

+        return paInvalidFlag; /* unexpected platform specific flag */

+

+

+    stream = (PaSkeletonStream*)PaUtil_AllocateMemory( sizeof(PaSkeletonStream) );

+    if( !stream )

+    {

+        result = paInsufficientMemory;

+        goto error;

+    }

+

+    if( streamCallback )

+    {

+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,

+                                               &skeletonHostApi->callbackStreamInterface, streamCallback, userData );

+    }

+    else

+    {

+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,

+                                               &skeletonHostApi->blockingStreamInterface, streamCallback, userData );

+    }

+

+    PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );

+

+

+    /* we assume a fixed host buffer size in this example, but the buffer processor

+        can also support bounded and unknown host buffer sizes by passing 

+        paUtilBoundedHostBufferSize or paUtilUnknownHostBufferSize instead of

+        paUtilFixedHostBufferSize below. */

+        

+    result =  PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,

+              inputChannelCount, inputSampleFormat, hostInputSampleFormat,

+              outputChannelCount, outputSampleFormat, hostOutputSampleFormat,

+              sampleRate, streamFlags, framesPerBuffer,

+              framesPerHostBuffer, paUtilFixedHostBufferSize,

+              streamCallback, userData );

+    if( result != paNoError )

+        goto error;

+

+

+    /*

+        IMPLEMENT ME: initialise the following fields with estimated or actual

+        values.

+    */

+    stream->streamRepresentation.streamInfo.inputLatency =

+            PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor);

+    stream->streamRepresentation.streamInfo.outputLatency =

+            PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor);

+    stream->streamRepresentation.streamInfo.sampleRate = sampleRate;

+

+    

+    /*

+        IMPLEMENT ME:

+            - additional stream setup + opening

+    */

+

+    stream->framesPerHostCallback = framesPerHostBuffer;

+

+    *s = (PaStream*)stream;

+

+    return result;

+

+error:

+    if( stream )

+        PaUtil_FreeMemory( stream );

+

+    return result;

+}

+

+/*

+    ExampleHostProcessingLoop() illustrates the kind of processing which may

+    occur in a host implementation.

+ 

+*/

+static void ExampleHostProcessingLoop( void *inputBuffer, void *outputBuffer, void *userData )

+{

+    PaSkeletonStream *stream = (PaSkeletonStream*)userData;

+    PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /* IMPLEMENT ME */

+    int callbackResult;

+    unsigned long framesProcessed;

+    

+    PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );

+    

+    /*

+        IMPLEMENT ME:

+            - generate timing information

+            - handle buffer slips

+    */

+

+    /*

+        If you need to byte swap or shift inputBuffer to convert it into a

+        portaudio format, do it here.

+    */

+

+

+

+    PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, 0 /* IMPLEMENT ME: pass underflow/overflow flags when necessary */ );

+

+    /*

+        depending on whether the host buffers are interleaved, non-interleaved

+        or a mixture, you will want to call PaUtil_SetInterleaved*Channels(),

+        PaUtil_SetNonInterleaved*Channel() or PaUtil_Set*Channel() here.

+    */

+    

+    PaUtil_SetInputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ );

+    PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor,

+            0, /* first channel of inputBuffer is channel 0 */

+            inputBuffer,

+            0 ); /* 0 - use inputChannelCount passed to init buffer processor */

+

+    PaUtil_SetOutputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ );

+    PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor,

+            0, /* first channel of outputBuffer is channel 0 */

+            outputBuffer,

+            0 ); /* 0 - use outputChannelCount passed to init buffer processor */

+

+    /* you must pass a valid value of callback result to PaUtil_EndBufferProcessing()

+        in general you would pass paContinue for normal operation, and

+        paComplete to drain the buffer processor's internal output buffer.

+        You can check whether the buffer processor's output buffer is empty

+        using PaUtil_IsBufferProcessorOuputEmpty( bufferProcessor )

+    */

+    callbackResult = paContinue;

+    framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult );

+

+    

+    /*

+        If you need to byte swap or shift outputBuffer to convert it to

+        host format, do it here.

+    */

+

+    PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );

+

+

+    if( callbackResult == paContinue )

+    {

+        /* nothing special to do */

+    }

+    else if( callbackResult == paAbort )

+    {

+        /* IMPLEMENT ME - finish playback immediately  */

+

+        /* once finished, call the finished callback */

+        if( stream->streamRepresentation.streamFinishedCallback != 0 )

+            stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );

+    }

+    else

+    {

+        /* User callback has asked us to stop with paComplete or other non-zero value */

+

+        /* IMPLEMENT ME - finish playback once currently queued audio has completed  */

+

+        /* once finished, call the finished callback */

+        if( stream->streamRepresentation.streamFinishedCallback != 0 )

+            stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );

+    }

+}

+

+

+/*

+    When CloseStream() is called, the multi-api layer ensures that

+    the stream has already been stopped or aborted.

+*/

+static PaError CloseStream( PaStream* s )

+{

+    PaError result = paNoError;

+    PaSkeletonStream *stream = (PaSkeletonStream*)s;

+

+    /*

+        IMPLEMENT ME:

+            - additional stream closing + cleanup

+    */

+

+    PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );

+    PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );

+    PaUtil_FreeMemory( stream );

+

+    return result;

+}

+

+

+static PaError StartStream( PaStream *s )

+{

+    PaError result = paNoError;

+    PaSkeletonStream *stream = (PaSkeletonStream*)s;

+

+    PaUtil_ResetBufferProcessor( &stream->bufferProcessor );

+

+    /* IMPLEMENT ME, see portaudio.h for required behavior */

+

+    /* suppress unused function warning. the code in ExampleHostProcessingLoop or

+       something similar should be implemented to feed samples to and from the

+       host after StartStream() is called.

+    */

+    (void) ExampleHostProcessingLoop;

+

+    return result;

+}

+

+

+static PaError StopStream( PaStream *s )

+{

+    PaError result = paNoError;

+    PaSkeletonStream *stream = (PaSkeletonStream*)s;

+

+    /* suppress unused variable warnings */

+    (void) stream;

+

+    /* IMPLEMENT ME, see portaudio.h for required behavior */

+

+    return result;

+}

+

+

+static PaError AbortStream( PaStream *s )

+{

+    PaError result = paNoError;

+    PaSkeletonStream *stream = (PaSkeletonStream*)s;

+

+    /* suppress unused variable warnings */

+    (void) stream;

+    

+    /* IMPLEMENT ME, see portaudio.h for required behavior */

+

+    return result;

+}

+

+

+static PaError IsStreamStopped( PaStream *s )

+{

+    PaSkeletonStream *stream = (PaSkeletonStream*)s;

+

+    /* suppress unused variable warnings */

+    (void) stream;

+    

+    /* IMPLEMENT ME, see portaudio.h for required behavior */

+

+    return 0;

+}

+

+

+static PaError IsStreamActive( PaStream *s )

+{

+    PaSkeletonStream *stream = (PaSkeletonStream*)s;

+

+    /* suppress unused variable warnings */

+    (void) stream;

+    

+    /* IMPLEMENT ME, see portaudio.h for required behavior */

+

+    return 0;

+}

+

+

+static PaTime GetStreamTime( PaStream *s )

+{

+    PaSkeletonStream *stream = (PaSkeletonStream*)s;

+

+    /* suppress unused variable warnings */

+    (void) stream;

+    

+    /* IMPLEMENT ME, see portaudio.h for required behavior*/

+

+    return 0;

+}

+

+

+static double GetStreamCpuLoad( PaStream* s )

+{

+    PaSkeletonStream *stream = (PaSkeletonStream*)s;

+

+    return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );

+}

+

+

+/*

+    As separate stream interfaces are used for blocking and callback

+    streams, the following functions can be guaranteed to only be called

+    for blocking streams.

+*/

+

+static PaError ReadStream( PaStream* s,

+                           void *buffer,

+                           unsigned long frames )

+{

+    PaSkeletonStream *stream = (PaSkeletonStream*)s;

+

+    /* suppress unused variable warnings */

+    (void) buffer;

+    (void) frames;

+    (void) stream;

+    

+    /* IMPLEMENT ME, see portaudio.h for required behavior*/

+

+    return paNoError;

+}

+

+

+static PaError WriteStream( PaStream* s,

+                            const void *buffer,

+                            unsigned long frames )

+{

+    PaSkeletonStream *stream = (PaSkeletonStream*)s;

+

+    /* suppress unused variable warnings */

+    (void) buffer;

+    (void) frames;

+    (void) stream;

+    

+    /* IMPLEMENT ME, see portaudio.h for required behavior*/

+

+    return paNoError;

+}

+

+

+static signed long GetStreamReadAvailable( PaStream* s )

+{

+    PaSkeletonStream *stream = (PaSkeletonStream*)s;

+

+    /* suppress unused variable warnings */

+    (void) stream;

+    

+    /* IMPLEMENT ME, see portaudio.h for required behavior*/

+

+    return 0;

+}

+

+

+static signed long GetStreamWriteAvailable( PaStream* s )

+{

+    PaSkeletonStream *stream = (PaSkeletonStream*)s;

+

+    /* suppress unused variable warnings */

+    (void) stream;

+    

+    /* IMPLEMENT ME, see portaudio.h for required behavior*/

+

+    return 0;

+}

+

+

+

+

diff --git a/src/engine/external/portaudio/pa_stream.c b/src/engine/external/portaudio/pa_stream.c
new file mode 100644
index 00000000..4b07615e
--- /dev/null
+++ b/src/engine/external/portaudio/pa_stream.c
@@ -0,0 +1,150 @@
+/*

+ * $Id: pa_stream.c 1097 2006-08-26 08:27:53Z rossb $

+ * Portable Audio I/O Library

+ * 

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 2002 Ross Bencina

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup common_src

+

+ @brief Interface used by pa_front to virtualize functions which operate on

+ streams.

+*/

+

+

+#include "pa_stream.h"

+

+

+void PaUtil_InitializeStreamInterface( PaUtilStreamInterface *streamInterface,

+                                       PaError (*Close)( PaStream* ),

+                                       PaError (*Start)( PaStream* ),

+                                       PaError (*Stop)( PaStream* ),

+                                       PaError (*Abort)( PaStream* ),

+                                       PaError (*IsStopped)( PaStream* ),

+                                       PaError (*IsActive)( PaStream* ),

+                                       PaTime (*GetTime)( PaStream* ),

+                                       double (*GetCpuLoad)( PaStream* ),

+                                       PaError (*Read)( PaStream*, void *, unsigned long ),

+                                       PaError (*Write)( PaStream*, const void *, unsigned long ),

+                                       signed long (*GetReadAvailable)( PaStream* ),

+                                       signed long (*GetWriteAvailable)( PaStream* )  )

+{

+    streamInterface->Close = Close;

+    streamInterface->Start = Start;

+    streamInterface->Stop = Stop;

+    streamInterface->Abort = Abort;

+    streamInterface->IsStopped = IsStopped;

+    streamInterface->IsActive = IsActive;

+    streamInterface->GetTime = GetTime;

+    streamInterface->GetCpuLoad = GetCpuLoad;

+    streamInterface->Read = Read;

+    streamInterface->Write = Write;

+    streamInterface->GetReadAvailable = GetReadAvailable;

+    streamInterface->GetWriteAvailable = GetWriteAvailable;

+}

+

+

+void PaUtil_InitializeStreamRepresentation( PaUtilStreamRepresentation *streamRepresentation,

+        PaUtilStreamInterface *streamInterface,

+        PaStreamCallback *streamCallback,

+        void *userData )

+{

+    streamRepresentation->magic = PA_STREAM_MAGIC;

+    streamRepresentation->nextOpenStream = 0;

+    streamRepresentation->streamInterface = streamInterface;

+    streamRepresentation->streamCallback = streamCallback;

+    streamRepresentation->streamFinishedCallback = 0;

+

+    streamRepresentation->userData = userData;

+

+    streamRepresentation->streamInfo.inputLatency = 0.;

+    streamRepresentation->streamInfo.outputLatency = 0.;

+    streamRepresentation->streamInfo.sampleRate = 0.;

+}

+

+

+void PaUtil_TerminateStreamRepresentation( PaUtilStreamRepresentation *streamRepresentation )

+{

+    streamRepresentation->magic = 0;

+}

+

+

+PaError PaUtil_DummyRead( PaStream* stream,

+                               void *buffer,

+                               unsigned long frames )

+{

+    (void)stream; /* unused parameter */

+    (void)buffer; /* unused parameter */

+    (void)frames; /* unused parameter */

+

+    return paCanNotReadFromACallbackStream;

+}

+

+

+PaError PaUtil_DummyWrite( PaStream* stream,

+                               const void *buffer,

+                               unsigned long frames )

+{

+    (void)stream; /* unused parameter */

+    (void)buffer; /* unused parameter */

+    (void)frames; /* unused parameter */

+

+    return paCanNotWriteToACallbackStream;

+}

+

+

+signed long PaUtil_DummyGetReadAvailable( PaStream* stream )

+{

+    (void)stream; /* unused parameter */

+

+    return paCanNotReadFromACallbackStream;

+}

+

+

+signed long PaUtil_DummyGetWriteAvailable( PaStream* stream )

+{

+    (void)stream; /* unused parameter */

+

+    return paCanNotWriteToACallbackStream;

+}

+

+

+double PaUtil_DummyGetCpuLoad( PaStream* stream )

+{

+    (void)stream; /* unused parameter */

+

+    return 0.0;

+}

diff --git a/src/engine/external/portaudio/pa_stream.h b/src/engine/external/portaudio/pa_stream.h
new file mode 100644
index 00000000..6f14620e
--- /dev/null
+++ b/src/engine/external/portaudio/pa_stream.h
@@ -0,0 +1,205 @@
+#ifndef PA_STREAM_H

+#define PA_STREAM_H

+/*

+ * $Id: pa_stream.h 1097 2006-08-26 08:27:53Z rossb $

+ * Portable Audio I/O Library

+ * stream interface

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup common_src

+

+ @brief Interface used by pa_front to virtualize functions which operate on

+ streams.

+*/

+

+

+#include "portaudio.h"

+

+#ifdef __cplusplus

+extern "C"

+{

+#endif /* __cplusplus */

+

+

+#define PA_STREAM_MAGIC (0x18273645)

+

+

+/** A structure representing an (abstract) interface to a host API. Contains

+ pointers to functions which implement the interface.

+

+ All PaStreamInterface functions are guaranteed to be called with a non-null,

+ valid stream parameter.

+*/

+typedef struct {

+    PaError (*Close)( PaStream* stream );

+    PaError (*Start)( PaStream *stream );

+    PaError (*Stop)( PaStream *stream );

+    PaError (*Abort)( PaStream *stream );

+    PaError (*IsStopped)( PaStream *stream );

+    PaError (*IsActive)( PaStream *stream );

+    PaTime (*GetTime)( PaStream *stream );

+    double (*GetCpuLoad)( PaStream* stream );

+    PaError (*Read)( PaStream* stream, void *buffer, unsigned long frames );

+    PaError (*Write)( PaStream* stream, const void *buffer, unsigned long frames );

+    signed long (*GetReadAvailable)( PaStream* stream );

+    signed long (*GetWriteAvailable)( PaStream* stream );

+} PaUtilStreamInterface;

+

+

+/** Initialize the fields of a PaUtilStreamInterface structure.

+*/

+void PaUtil_InitializeStreamInterface( PaUtilStreamInterface *streamInterface,

+    PaError (*Close)( PaStream* ),

+    PaError (*Start)( PaStream* ),

+    PaError (*Stop)( PaStream* ),

+    PaError (*Abort)( PaStream* ),

+    PaError (*IsStopped)( PaStream* ),

+    PaError (*IsActive)( PaStream* ),

+    PaTime (*GetTime)( PaStream* ),

+    double (*GetCpuLoad)( PaStream* ),

+    PaError (*Read)( PaStream* stream, void *buffer, unsigned long frames ),

+    PaError (*Write)( PaStream* stream, const void *buffer, unsigned long frames ),

+    signed long (*GetReadAvailable)( PaStream* stream ),

+    signed long (*GetWriteAvailable)( PaStream* stream ) );

+

+

+/** Dummy Read function for use in interfaces to a callback based streams.

+ Pass to the Read parameter of PaUtil_InitializeStreamInterface.

+ @return An error code indicating that the function has no effect

+ because the stream is a callback stream.

+*/

+PaError PaUtil_DummyRead( PaStream* stream,

+                       void *buffer,

+                       unsigned long frames );

+

+

+/** Dummy Write function for use in an interfaces to callback based streams.

+ Pass to the Write parameter of PaUtil_InitializeStreamInterface.

+ @return An error code indicating that the function has no effect

+ because the stream is a callback stream.

+*/

+PaError PaUtil_DummyWrite( PaStream* stream,

+                       const void *buffer,

+                       unsigned long frames );

+

+

+/** Dummy GetReadAvailable function for use in interfaces to callback based

+ streams. Pass to the GetReadAvailable parameter of PaUtil_InitializeStreamInterface.

+ @return An error code indicating that the function has no effect

+ because the stream is a callback stream.

+*/

+signed long PaUtil_DummyGetReadAvailable( PaStream* stream );

+

+

+/** Dummy GetWriteAvailable function for use in interfaces to callback based

+ streams. Pass to the GetWriteAvailable parameter of PaUtil_InitializeStreamInterface.

+ @return An error code indicating that the function has no effect

+ because the stream is a callback stream.

+*/

+signed long PaUtil_DummyGetWriteAvailable( PaStream* stream );

+

+

+

+/** Dummy GetCpuLoad function for use in an interface to a read/write stream.

+ Pass to the GetCpuLoad parameter of PaUtil_InitializeStreamInterface.

+ @return Returns 0.

+*/

+double PaUtil_DummyGetCpuLoad( PaStream* stream );

+

+

+/** Non host specific data for a stream. This data is used by pa_front to

+ forward to the appropriate functions in the streamInterface structure.

+*/

+typedef struct PaUtilStreamRepresentation {

+    unsigned long magic;    /**< set to PA_STREAM_MAGIC */

+    struct PaUtilStreamRepresentation *nextOpenStream; /**< field used by multi-api code */

+    PaUtilStreamInterface *streamInterface;

+    PaStreamCallback *streamCallback;

+    PaStreamFinishedCallback *streamFinishedCallback;

+    void *userData;

+    PaStreamInfo streamInfo;

+} PaUtilStreamRepresentation;

+

+

+/** Initialize a PaUtilStreamRepresentation structure.

+

+ @see PaUtil_InitializeStreamRepresentation

+*/

+void PaUtil_InitializeStreamRepresentation(

+        PaUtilStreamRepresentation *streamRepresentation,

+        PaUtilStreamInterface *streamInterface,

+        PaStreamCallback *streamCallback,

+        void *userData );

+        

+

+/** Clean up a PaUtilStreamRepresentation structure previously initialized

+ by a call to PaUtil_InitializeStreamRepresentation.

+

+ @see PaUtil_InitializeStreamRepresentation

+*/

+void PaUtil_TerminateStreamRepresentation( PaUtilStreamRepresentation *streamRepresentation );

+

+

+/** Check that the stream pointer is valid.

+

+ @return Returns paNoError if the stream pointer appears to be OK, otherwise

+ returns an error indicating the cause of failure.

+*/

+PaError PaUtil_ValidateStreamPointer( PaStream *stream );

+

+

+/** Cast an opaque stream pointer into a pointer to a PaUtilStreamRepresentation.

+

+ @see PaUtilStreamRepresentation

+*/

+#define PA_STREAM_REP( stream )\

+    ((PaUtilStreamRepresentation*) (stream) )

+

+

+/** Cast an opaque stream pointer into a pointer to a PaUtilStreamInterface.

+

+ @see PaUtilStreamRepresentation, PaUtilStreamInterface

+*/

+#define PA_STREAM_INTERFACE( stream )\

+    PA_STREAM_REP( (stream) )->streamInterface

+

+

+    

+#ifdef __cplusplus

+}

+#endif /* __cplusplus */

+#endif /* PA_STREAM_H */

diff --git a/src/engine/external/portaudio/pa_trace.c b/src/engine/external/portaudio/pa_trace.c
new file mode 100644
index 00000000..41f1034d
--- /dev/null
+++ b/src/engine/external/portaudio/pa_trace.c
@@ -0,0 +1,97 @@
+/*

+ * $Id: pa_trace.c 1097 2006-08-26 08:27:53Z rossb $

+ * Portable Audio I/O Library Trace Facility

+ * Store trace information in real-time for later printing.

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2000 Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup common_src

+

+ @brief Event trace mechanism for debugging.

+*/

+

+

+#include <stdio.h>

+#include <stdlib.h>

+#include <string.h>

+#include "pa_trace.h"

+

+#if PA_TRACE_REALTIME_EVENTS

+

+static char *traceTextArray[PA_MAX_TRACE_RECORDS];

+static int traceIntArray[PA_MAX_TRACE_RECORDS];

+static int traceIndex = 0;

+static int traceBlock = 0;

+

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

+void PaUtil_ResetTraceMessages()

+{

+    traceIndex = 0;

+}

+

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

+void PaUtil_DumpTraceMessages()

+{

+    int i;

+    int messageCount = (traceIndex < PA_MAX_TRACE_RECORDS) ? traceIndex : PA_MAX_TRACE_RECORDS;

+

+    printf("DumpTraceMessages: traceIndex = %d\n", traceIndex );

+    for( i=0; i<messageCount; i++ )

+    {

+        printf("%3d: %s = 0x%08X\n",

+               i, traceTextArray[i], traceIntArray[i] );

+    }

+    PaUtil_ResetTraceMessages();

+    fflush(stdout);

+}

+

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

+void PaUtil_AddTraceMessage( const char *msg, int data )

+{

+    if( (traceIndex == PA_MAX_TRACE_RECORDS) && (traceBlock == 0) )

+    {

+        traceBlock = 1;

+        /*  PaUtil_DumpTraceMessages(); */

+    }

+    else if( traceIndex < PA_MAX_TRACE_RECORDS )

+    {

+        traceTextArray[traceIndex] = msg;

+        traceIntArray[traceIndex] = data;

+        traceIndex++;

+    }

+}

+

+#endif /* TRACE_REALTIME_EVENTS */

diff --git a/src/engine/external/portaudio/pa_trace.h b/src/engine/external/portaudio/pa_trace.h
new file mode 100644
index 00000000..b2dfe3a6
--- /dev/null
+++ b/src/engine/external/portaudio/pa_trace.h
@@ -0,0 +1,79 @@
+#ifndef PA_TRACE_H

+#define PA_TRACE_H

+/*

+ * $Id: pa_trace.h 1097 2006-08-26 08:27:53Z rossb $

+ * Portable Audio I/O Library Trace Facility

+ * Store trace information in real-time for later printing.

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2000 Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup common_src

+

+ @brief Event trace mechanism for debugging.

+

+ Allows data to be written to the buffer at interrupt time and dumped later.

+*/

+

+

+#define PA_TRACE_REALTIME_EVENTS     (0)   /* Keep log of various real-time events. */

+#define PA_MAX_TRACE_RECORDS      (2048)

+

+#ifdef __cplusplus

+extern "C"

+{

+#endif /* __cplusplus */

+

+

+#if PA_TRACE_REALTIME_EVENTS

+

+void PaUtil_ResetTraceMessages();

+void PaUtil_AddTraceMessage( const char *msg, int data );

+void PaUtil_DumpTraceMessages();

+    

+#else

+

+#define PaUtil_ResetTraceMessages() /* noop */

+#define PaUtil_AddTraceMessage(msg,data) /* noop */

+#define PaUtil_DumpTraceMessages() /* noop */

+

+#endif

+

+

+#ifdef __cplusplus

+}

+#endif /* __cplusplus */

+

+#endif /* PA_TRACE_H */

diff --git a/src/engine/external/portaudio/pa_types.h b/src/engine/external/portaudio/pa_types.h
new file mode 100644
index 00000000..f1c261d6
--- /dev/null
+++ b/src/engine/external/portaudio/pa_types.h
@@ -0,0 +1,107 @@
+#ifndef PA_TYPES_H

+#define PA_TYPES_H

+

+/* 

+ * Portable Audio I/O Library

+ * integer type definitions

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2006 Ross Bencina, Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup common_src

+

+ @brief Definition of 16 and 32 bit integer types (PaInt16, PaInt32 etc)

+

+ SIZEOF_SHORT, SIZEOF_INT and SIZEOF_LONG are set by the configure script

+ when it is used. Otherwise we default to the common 32 bit values, if your

+ platform doesn't use configure, and doesn't use the default values below

+ you will need to explicitly define these symbols in your make file.

+

+ A PA_VALIDATE_SIZES macro is provided to assert that the values set in this

+ file are correct.

+*/

+

+#ifndef SIZEOF_SHORT

+#define SIZEOF_SHORT 2

+#endif

+

+#ifndef SIZEOF_INT

+#define SIZEOF_INT 4

+#endif

+

+#ifndef SIZEOF_LONG

+#define SIZEOF_LONG 4

+#endif

+

+

+#if SIZEOF_SHORT == 2

+typedef signed short PaInt16;

+typedef unsigned short PaUint16;

+#elif SIZEOF_INT == 2

+typedef signed int PaInt16;

+typedef unsigned int PaUint16;

+#else

+#error pa_types.h was unable to determine which type to use for 16bit integers on the target platform

+#endif

+

+#if SIZEOF_SHORT == 4

+typedef signed short PaInt32;

+typedef unsigned short PaUint32;

+#elif SIZEOF_INT == 4

+typedef signed int PaInt32;

+typedef unsigned int PaUint32;

+#elif SIZEOF_LONG == 4

+typedef signed long PaInt32;

+typedef unsigned long PaUint32;

+#else

+#error pa_types.h was unable to determine which type to use for 32bit integers on the target platform

+#endif

+

+

+/* PA_VALIDATE_TYPE_SIZES compares the size of the integer types at runtime to

+ ensure that PortAudio was configured correctly, and raises an assertion if

+ they don't match the expected values. <assert.h> must be included in the

+ context in which this macro is used.

+*/

+#define PA_VALIDATE_TYPE_SIZES \

+    { \

+        assert( "PortAudio: type sizes are not correct in pa_types.h" && sizeof( PaUint16 ) == 2 ); \

+        assert( "PortAudio: type sizes are not correct in pa_types.h" && sizeof( PaInt16 ) == 2 ); \

+        assert( "PortAudio: type sizes are not correct in pa_types.h" && sizeof( PaUint32 ) == 4 ); \

+        assert( "PortAudio: type sizes are not correct in pa_types.h" && sizeof( PaInt32 ) == 4 ); \

+    }

+

+

+#endif /* PA_TYPES_H */

diff --git a/src/engine/external/portaudio/pa_unix_hostapis.c b/src/engine/external/portaudio/pa_unix_hostapis.c
new file mode 100644
index 00000000..66eb7f10
--- /dev/null
+++ b/src/engine/external/portaudio/pa_unix_hostapis.c
@@ -0,0 +1,78 @@
+/*

+ * $Id: pa_unix_hostapis.c 1097 2006-08-26 08:27:53Z rossb $

+ * Portable Audio I/O Library UNIX initialization table

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup unix_src

+*/

+

+#include "pa_hostapi.h"

+

+PaError PaJack_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );

+PaError PaAlsa_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );

+PaError PaOSS_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );

+/* Added for IRIX, Pieter, oct 2, 2003: */

+PaError PaSGI_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );

+/* Linux AudioScience HPI */

+PaError PaAsiHpi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );

+

+

+PaUtilHostApiInitializer *paHostApiInitializers[] =

+    {

+#ifdef PA_USE_OSS

+        PaOSS_Initialize,

+#endif

+

+#ifdef PA_USE_ALSA

+        PaAlsa_Initialize,

+#endif

+

+#ifdef PA_USE_JACK

+        PaJack_Initialize,

+#endif

+                    /* Added for IRIX, Pieter, oct 2, 2003: */

+#ifdef PA_USE_SGI 

+        PaSGI_Initialize,

+#endif

+

+#ifdef PA_USE_ASIHPI

+        PaAsiHpi_Initialize,

+#endif

+        0   /* NULL terminated array */

+    };

+

+int paDefaultHostApiIndex = 0;

diff --git a/src/engine/external/portaudio/pa_unix_oss.c b/src/engine/external/portaudio/pa_unix_oss.c
new file mode 100644
index 00000000..30abe7d7
--- /dev/null
+++ b/src/engine/external/portaudio/pa_unix_oss.c
@@ -0,0 +1,1946 @@
+/*

+ * $Id: pa_unix_oss.c 1238 2007-07-15 16:58:50Z aknudsen $

+ * PortAudio Portable Real-Time Audio Library

+ * Latest Version at: http://www.portaudio.com

+ * OSS implementation by:

+ *   Douglas Repetto

+ *   Phil Burk

+ *   Dominic Mazzoni

+ *   Arve Knudsen

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however,

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also

+ * requested that these non-binding requests be included along with the

+ * license above.

+ */

+

+/**

+ @file

+ @ingroup hostapi_src

+*/

+

+#include <stdio.h>

+#include <string.h>

+#include <math.h>

+#include <fcntl.h>

+#include <sys/ioctl.h>

+#include <unistd.h>

+#include <pthread.h>

+#include <stdlib.h>

+#include <assert.h>

+#include <errno.h>

+#include <sys/types.h>

+#include <sys/stat.h>

+#include <sys/poll.h>

+#include <limits.h>

+#include <semaphore.h>

+

+#ifdef HAVE_SYS_SOUNDCARD_H

+# include <sys/soundcard.h>

+# define DEVICE_NAME_BASE            "/dev/dsp"

+#elif defined(HAVE_LINUX_SOUNDCARD_H)

+# include <linux/soundcard.h>

+# define DEVICE_NAME_BASE            "/dev/dsp"

+#elif defined(HAVE_MACHINE_SOUNDCARD_H)

+# include <machine/soundcard.h> /* JH20010905 */

+# define DEVICE_NAME_BASE            "/dev/audio"

+#else

+# error No sound card header file

+#endif

+

+#include "portaudio.h"

+#include "pa_util.h"

+#include "pa_allocation.h"

+#include "pa_hostapi.h"

+#include "pa_stream.h"

+#include "pa_cpuload.h"

+#include "pa_process.h"

+#include "pa_unix_util.h"

+#include "pa_debugprint.h"

+

+static int sysErr_;

+static pthread_t mainThread_;

+

+/* Check return value of system call, and map it to PaError */

+#define ENSURE_(expr, code) \

+    do { \

+        if( UNLIKELY( (sysErr_ = (expr)) < 0 ) ) \

+        { \

+            /* PaUtil_SetLastHostErrorInfo should only be used in the main thread */ \

+            if( (code) == paUnanticipatedHostError && pthread_self() == mainThread_ ) \

+            { \

+                PaUtil_SetLastHostErrorInfo( paALSA, sysErr_, strerror( errno ) ); \

+            } \

+            \

+            PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \

+            result = (code); \

+            goto error; \

+        } \

+    } while( 0 );

+

+#ifndef AFMT_S16_NE

+#define AFMT_S16_NE  Get_AFMT_S16_NE()

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

+ * Some versions of OSS do not define AFMT_S16_NE. So check CPU.

+ * PowerPC is Big Endian. X86 is Little Endian.

+ */

+static int Get_AFMT_S16_NE( void )

+{

+    long testData = 1;

+    char *ptr = (char *) &testData;

+    int isLittle = ( *ptr == 1 ); /* Does address point to least significant byte? */

+    return isLittle ? AFMT_S16_LE : AFMT_S16_BE;

+}

+#endif

+

+/* PaOSSHostApiRepresentation - host api datastructure specific to this implementation */

+

+typedef struct

+{

+    PaUtilHostApiRepresentation inheritedHostApiRep;

+    PaUtilStreamInterface callbackStreamInterface;

+    PaUtilStreamInterface blockingStreamInterface;

+

+    PaUtilAllocationGroup *allocations;

+

+    PaHostApiIndex hostApiIndex;

+}

+PaOSSHostApiRepresentation;

+

+/** Per-direction structure for PaOssStream.

+ *

+ * Aspect StreamChannels: In case the user requests to open the same device for both capture and playback,

+ * but with different number of channels we will have to adapt between the number of user and host

+ * channels for at least one direction, since the configuration space is the same for both directions

+ * of an OSS device.

+ */

+typedef struct

+{

+    int fd;

+    const char *devName;

+    int userChannelCount, hostChannelCount;

+    int userInterleaved;

+    void *buffer;

+    PaSampleFormat userFormat, hostFormat;

+    double latency;

+    unsigned long hostFrames, numBufs;

+    void **userBuffers; /* For non-interleaved blocking */

+} PaOssStreamComponent;

+

+/** Implementation specific representation of a PaStream.

+ *

+ */

+typedef struct PaOssStream

+{

+    PaUtilStreamRepresentation streamRepresentation;

+    PaUtilCpuLoadMeasurer cpuLoadMeasurer;

+    PaUtilBufferProcessor bufferProcessor;

+

+    PaUtilThreading threading;

+

+    int sharedDevice;

+    unsigned long framesPerHostBuffer;

+    int triggered;  /* Have the devices been triggered yet (first start) */

+

+    int isActive;

+    int isStopped;

+

+    int lastPosPtr;

+    double lastStreamBytes;

+

+    int framesProcessed;

+

+    double sampleRate;

+

+    int callbackMode;

+    int callbackStop, callbackAbort;

+

+    PaOssStreamComponent *capture, *playback;

+    unsigned long pollTimeout;

+    sem_t semaphore;

+}

+PaOssStream;

+

+typedef enum {

+    StreamMode_In,

+    StreamMode_Out

+} StreamMode;

+

+/* prototypes for functions declared in this file */

+

+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );

+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,

+                                  const PaStreamParameters *inputParameters,

+                                  const PaStreamParameters *outputParameters,

+                                  double sampleRate );

+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,

+                           PaStream** s,

+                           const PaStreamParameters *inputParameters,

+                           const PaStreamParameters *outputParameters,

+                           double sampleRate,

+                           unsigned long framesPerBuffer,

+                           PaStreamFlags streamFlags,

+                           PaStreamCallback *streamCallback,

+                           void *userData );

+static PaError CloseStream( PaStream* stream );

+static PaError StartStream( PaStream *stream );

+static PaError StopStream( PaStream *stream );

+static PaError AbortStream( PaStream *stream );

+static PaError IsStreamStopped( PaStream *s );

+static PaError IsStreamActive( PaStream *stream );

+static PaTime GetStreamTime( PaStream *stream );

+static double GetStreamCpuLoad( PaStream* stream );

+static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );

+static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );

+static signed long GetStreamReadAvailable( PaStream* stream );

+static signed long GetStreamWriteAvailable( PaStream* stream );

+static PaError BuildDeviceList( PaOSSHostApiRepresentation *hostApi );

+

+

+/** Initialize the OSS API implementation.

+ *

+ * This function will initialize host API datastructures and query host devices for information.

+ *

+ * Aspect DeviceCapabilities: Enumeration of host API devices is initiated from here

+ *

+ * Aspect FreeResources: If an error is encountered under way we have to free each resource allocated in this function,

+ * this happens with the usual "error" label.

+ */

+PaError PaOSS_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )

+{

+    PaError result = paNoError;

+    PaOSSHostApiRepresentation *ossHostApi = NULL;

+

+    PA_UNLESS( ossHostApi = (PaOSSHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaOSSHostApiRepresentation) ),

+            paInsufficientMemory );

+    PA_UNLESS( ossHostApi->allocations = PaUtil_CreateAllocationGroup(), paInsufficientMemory );

+    ossHostApi->hostApiIndex = hostApiIndex;

+

+    /* Initialize host API structure */

+    *hostApi = &ossHostApi->inheritedHostApiRep;

+    (*hostApi)->info.structVersion = 1;

+    (*hostApi)->info.type = paOSS;

+    (*hostApi)->info.name = "OSS";

+    (*hostApi)->Terminate = Terminate;

+    (*hostApi)->OpenStream = OpenStream;

+    (*hostApi)->IsFormatSupported = IsFormatSupported;

+

+    PA_ENSURE( BuildDeviceList( ossHostApi ) );

+

+    PaUtil_InitializeStreamInterface( &ossHostApi->callbackStreamInterface, CloseStream, StartStream,

+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,

+                                      GetStreamTime, GetStreamCpuLoad,

+                                      PaUtil_DummyRead, PaUtil_DummyWrite,

+                                      PaUtil_DummyGetReadAvailable,

+                                      PaUtil_DummyGetWriteAvailable );

+

+    PaUtil_InitializeStreamInterface( &ossHostApi->blockingStreamInterface, CloseStream, StartStream,

+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,

+                                      GetStreamTime, PaUtil_DummyGetCpuLoad,

+                                      ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );

+

+    mainThread_ = pthread_self();

+

+    return result;

+

+error:

+    if( ossHostApi )

+    {

+        if( ossHostApi->allocations )

+        {

+            PaUtil_FreeAllAllocations( ossHostApi->allocations );

+            PaUtil_DestroyAllocationGroup( ossHostApi->allocations );

+        }

+

+        PaUtil_FreeMemory( ossHostApi );

+    }

+    return result;

+}

+

+PaError PaUtil_InitializeDeviceInfo( PaDeviceInfo *deviceInfo, const char *name, PaHostApiIndex hostApiIndex, int maxInputChannels,

+        int maxOutputChannels, PaTime defaultLowInputLatency, PaTime defaultLowOutputLatency, PaTime defaultHighInputLatency,

+        PaTime defaultHighOutputLatency, double defaultSampleRate, PaUtilAllocationGroup *allocations  )

+{

+    PaError result = paNoError;

+

+    deviceInfo->structVersion = 2;

+    if( allocations )

+    {

+        size_t len = strlen( name ) + 1;

+        PA_UNLESS( deviceInfo->name = PaUtil_GroupAllocateMemory( allocations, len ), paInsufficientMemory );

+        strncpy( (char *)deviceInfo->name, name, len );

+    }

+    else

+        deviceInfo->name = name;

+

+    deviceInfo->hostApi = hostApiIndex;

+    deviceInfo->maxInputChannels = maxInputChannels;

+    deviceInfo->maxOutputChannels = maxOutputChannels;

+    deviceInfo->defaultLowInputLatency = defaultLowInputLatency;

+    deviceInfo->defaultLowOutputLatency = defaultLowOutputLatency;

+    deviceInfo->defaultHighInputLatency = defaultHighInputLatency;

+    deviceInfo->defaultHighOutputLatency = defaultHighOutputLatency;

+    deviceInfo->defaultSampleRate = defaultSampleRate;

+

+error:

+    return result;

+}

+

+static PaError QueryDirection( const char *deviceName, StreamMode mode, double *defaultSampleRate, int *maxChannelCount,

+        double *defaultLowLatency, double *defaultHighLatency )

+{

+    PaError result = paNoError;

+    int numChannels, maxNumChannels;

+    int busy = 0;

+    int devHandle = -1;

+    int sr;

+    *maxChannelCount = 0;  /* Default value in case this fails */

+

+    if ( (devHandle = open( deviceName, (mode == StreamMode_In ? O_RDONLY : O_WRONLY) | O_NONBLOCK ))  < 0 )

+    {

+        if( errno == EBUSY || errno == EAGAIN )

+        {

+            PA_DEBUG(( "%s: Device %s busy\n", __FUNCTION__, deviceName ));

+        }

+        else

+        {

+            PA_DEBUG(( "%s: Can't access device: %s\n", __FUNCTION__, strerror( errno ) ));

+        }

+

+        return paDeviceUnavailable;

+    }

+

+    /* Negotiate for the maximum number of channels for this device. PLB20010927

+     * Consider up to 16 as the upper number of channels.

+     * Variable maxNumChannels should contain the actual upper limit after the call.

+     * Thanks to John Lazzaro and Heiko Purnhagen for suggestions.

+     */

+    maxNumChannels = 0;

+    for( numChannels = 1; numChannels <= 16; numChannels++ )

+    {

+        int temp = numChannels;

+        if( ioctl( devHandle, SNDCTL_DSP_CHANNELS, &temp ) < 0 )

+        {

+            busy = EAGAIN == errno || EBUSY == errno;

+            /* ioctl() failed so bail out if we already have stereo */

+            if( maxNumChannels >= 2 )

+                break;

+        }

+        else

+        {

+            /* ioctl() worked but bail out if it does not support numChannels.

+             * We don't want to leave gaps in the numChannels supported.

+             */

+            if( (numChannels > 2) && (temp != numChannels) )

+                break;

+            if( temp > maxNumChannels )

+                maxNumChannels = temp; /* Save maximum. */

+        }

+    }

+    /* A: We're able to open a device for capture if it's busy playing back and vice versa,

+     * but we can't configure anything */

+    if( 0 == maxNumChannels && busy )

+    {

+        result = paDeviceUnavailable;

+        goto error;

+    }

+

+    /* The above negotiation may fail for an old driver so try this older technique. */

+    if( maxNumChannels < 1 )

+    {

+        int stereo = 1;

+        if( ioctl( devHandle, SNDCTL_DSP_STEREO, &stereo ) < 0 )

+        {

+            maxNumChannels = 1;

+        }

+        else

+        {

+            maxNumChannels = (stereo) ? 2 : 1;

+        }

+        PA_DEBUG(( "%s: use SNDCTL_DSP_STEREO, maxNumChannels = %d\n", __FUNCTION__, maxNumChannels ));

+    }

+

+    /* During channel negotiation, the last ioctl() may have failed. This can

+     * also cause sample rate negotiation to fail. Hence the following, to return

+     * to a supported number of channels. SG20011005 */

+    {

+        /* use most reasonable default value */

+        int temp = PA_MIN( maxNumChannels, 2 );

+        ENSURE_( ioctl( devHandle, SNDCTL_DSP_CHANNELS, &temp ), paUnanticipatedHostError );

+    }

+

+    /* Get supported sample rate closest to 44100 Hz */

+    if( *defaultSampleRate < 0 )

+    {

+        sr = 44100;

+        if( ioctl( devHandle, SNDCTL_DSP_SPEED, &sr ) < 0 )

+        {

+            result = paUnanticipatedHostError;

+            goto error;

+        }

+

+        *defaultSampleRate = sr;

+    }

+

+    *maxChannelCount = maxNumChannels;

+    /* TODO */

+    *defaultLowLatency = 512. / *defaultSampleRate;

+    *defaultHighLatency = 2048. / *defaultSampleRate;

+

+error:

+    if( devHandle >= 0 )

+        close( devHandle );

+

+    return result;

+}

+

+/** Query OSS device.

+ *

+ * This is where PaDeviceInfo objects are constructed and filled in with relevant information.

+ *

+ * Aspect DeviceCapabilities: The inferred device capabilities are recorded in a PaDeviceInfo object that is constructed

+ * in place.

+ */

+static PaError QueryDevice( char *deviceName, PaOSSHostApiRepresentation *ossApi, PaDeviceInfo **deviceInfo )

+{

+    PaError result = paNoError;

+    double sampleRate = -1.;

+    int maxInputChannels, maxOutputChannels;

+    PaTime defaultLowInputLatency, defaultLowOutputLatency, defaultHighInputLatency, defaultHighOutputLatency;

+    PaError tmpRes = paNoError;

+    int busy = 0;

+    *deviceInfo = NULL;

+

+    /* douglas:

+       we have to do this querying in a slightly different order. apparently

+       some sound cards will give you different info based on their settins.

+       e.g. a card might give you stereo at 22kHz but only mono at 44kHz.

+       the correct order for OSS is: format, channels, sample rate

+    */

+

+    /* Aspect StreamChannels: The number of channels supported for a device may depend on the mode it is

+     * opened in, it may have more channels available for capture than playback and vice versa. Therefore

+     * we will open the device in both read- and write-only mode to determine the supported number.

+     */

+    if( (tmpRes = QueryDirection( deviceName, StreamMode_In, &sampleRate, &maxInputChannels, &defaultLowInputLatency,

+                &defaultHighInputLatency )) != paNoError )

+    {

+        if( tmpRes != paDeviceUnavailable )

+        {

+            PA_DEBUG(( "%s: Querying device %s for capture failed!\n", __FUNCTION__, deviceName ));

+            /* PA_ENSURE( tmpRes ); */

+        }

+        ++busy;

+    }

+    if( (tmpRes = QueryDirection( deviceName, StreamMode_Out, &sampleRate, &maxOutputChannels, &defaultLowOutputLatency,

+                &defaultHighOutputLatency )) != paNoError )

+    {

+        if( tmpRes != paDeviceUnavailable )

+        {

+            PA_DEBUG(( "%s: Querying device %s for playback failed!\n", __FUNCTION__, deviceName ));

+            /* PA_ENSURE( tmpRes ); */

+        }

+        ++busy;

+    }

+    assert( 0 <= busy && busy <= 2 );

+    if( 2 == busy )     /* Both directions are unavailable to us */

+    {

+        result = paDeviceUnavailable;

+        goto error;

+    }

+

+    PA_UNLESS( *deviceInfo = PaUtil_GroupAllocateMemory( ossApi->allocations, sizeof (PaDeviceInfo) ), paInsufficientMemory );

+    PA_ENSURE( PaUtil_InitializeDeviceInfo( *deviceInfo, deviceName, ossApi->hostApiIndex, maxInputChannels, maxOutputChannels,

+                defaultLowInputLatency, defaultLowOutputLatency, defaultHighInputLatency, defaultHighOutputLatency, sampleRate,

+                ossApi->allocations ) );

+

+error:

+    return result;

+}

+

+/** Query host devices.

+ *

+ * Loop over host devices and query their capabilitiesu

+ *

+ * Aspect DeviceCapabilities: This function calls QueryDevice on each device entry and receives a filled in PaDeviceInfo object

+ * per device, these are placed in the host api representation's deviceInfos array.

+ */

+static PaError BuildDeviceList( PaOSSHostApiRepresentation *ossApi )

+{

+    PaError result = paNoError;

+    PaUtilHostApiRepresentation *commonApi = &ossApi->inheritedHostApiRep;

+    int i;

+    int numDevices = 0, maxDeviceInfos = 1;

+    PaDeviceInfo **deviceInfos = NULL;

+

+    /* These two will be set to the first working input and output device, respectively */

+    commonApi->info.defaultInputDevice = paNoDevice;

+    commonApi->info.defaultOutputDevice = paNoDevice;

+

+    /* Find devices by calling QueryDevice on each

+     * potential device names.  When we find a valid one,

+     * add it to a linked list.

+     * A: Can there only be 10 devices? */

+

+    for( i = 0; i < 10; i++ )

+    {

+       char deviceName[32];

+       PaDeviceInfo *deviceInfo;

+       int testResult;

+       struct stat stbuf;

+

+       if( i == 0 )

+          snprintf(deviceName, sizeof (deviceName), "%s", DEVICE_NAME_BASE);

+       else

+          snprintf(deviceName, sizeof (deviceName), "%s%d", DEVICE_NAME_BASE, i);

+

+       /* PA_DEBUG(("PaOSS BuildDeviceList: trying device %s\n", deviceName )); */

+       if( stat( deviceName, &stbuf ) < 0 )

+       {

+           if( ENOENT != errno )

+               PA_DEBUG(( "%s: Error stat'ing %s: %s\n", __FUNCTION__, deviceName, strerror( errno ) ));

+           continue;

+       }

+       if( (testResult = QueryDevice( deviceName, ossApi, &deviceInfo )) != paNoError )

+       {

+           if( testResult != paDeviceUnavailable )

+               PA_ENSURE( testResult );

+

+           continue;

+       }

+

+       ++numDevices;

+       if( !deviceInfos || numDevices > maxDeviceInfos )

+       {

+           maxDeviceInfos *= 2;

+           PA_UNLESS( deviceInfos = (PaDeviceInfo **) realloc( deviceInfos, maxDeviceInfos * sizeof (PaDeviceInfo *) ),

+                   paInsufficientMemory );

+       }

+       {

+           int devIdx = numDevices - 1;

+           deviceInfos[devIdx] = deviceInfo;

+

+           if( commonApi->info.defaultInputDevice == paNoDevice && deviceInfo->maxInputChannels > 0 )

+               commonApi->info.defaultInputDevice = devIdx;

+           if( commonApi->info.defaultOutputDevice == paNoDevice && deviceInfo->maxOutputChannels > 0 )

+               commonApi->info.defaultOutputDevice = devIdx;

+       }

+    }

+

+    /* Make an array of PaDeviceInfo pointers out of the linked list */

+

+    PA_DEBUG(("PaOSS %s: Total number of devices found: %d\n", __FUNCTION__, numDevices));

+

+    commonApi->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(

+        ossApi->allocations, sizeof(PaDeviceInfo*) * numDevices );

+    memcpy( commonApi->deviceInfos, deviceInfos, numDevices * sizeof (PaDeviceInfo *) );

+

+    commonApi->info.deviceCount = numDevices;

+

+error:

+    free( deviceInfos );

+

+    return result;

+}

+

+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )

+{

+    PaOSSHostApiRepresentation *ossHostApi = (PaOSSHostApiRepresentation*)hostApi;

+

+    if( ossHostApi->allocations )

+    {

+        PaUtil_FreeAllAllocations( ossHostApi->allocations );

+        PaUtil_DestroyAllocationGroup( ossHostApi->allocations );

+    }

+

+    PaUtil_FreeMemory( ossHostApi );

+}

+

+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,

+                                  const PaStreamParameters *inputParameters,

+                                  const PaStreamParameters *outputParameters,

+                                  double sampleRate )

+{

+    PaError result = paNoError;

+    PaDeviceIndex device;

+    PaDeviceInfo *deviceInfo;

+    char *deviceName;

+    int inputChannelCount, outputChannelCount;

+    int tempDevHandle = -1;

+    int flags;

+    PaSampleFormat inputSampleFormat, outputSampleFormat;

+

+    if( inputParameters )

+    {

+        inputChannelCount = inputParameters->channelCount;

+        inputSampleFormat = inputParameters->sampleFormat;

+

+        /* unless alternate device specification is supported, reject the use of

+            paUseHostApiSpecificDeviceSpecification */

+

+        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )

+            return paInvalidDevice;

+

+        /* check that input device can support inputChannelCount */

+        if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )

+            return paInvalidChannelCount;

+

+        /* validate inputStreamInfo */

+        if( inputParameters->hostApiSpecificStreamInfo )

+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */

+    }

+    else

+    {

+        inputChannelCount = 0;

+    }

+

+    if( outputParameters )

+    {

+        outputChannelCount = outputParameters->channelCount;

+        outputSampleFormat = outputParameters->sampleFormat;

+

+        /* unless alternate device specification is supported, reject the use of

+            paUseHostApiSpecificDeviceSpecification */

+

+        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )

+            return paInvalidDevice;

+

+        /* check that output device can support inputChannelCount */

+        if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )

+            return paInvalidChannelCount;

+

+        /* validate outputStreamInfo */

+        if( outputParameters->hostApiSpecificStreamInfo )

+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */

+    }

+    else

+    {

+        outputChannelCount = 0;

+    }

+

+    if (inputChannelCount == 0 && outputChannelCount == 0)

+        return paInvalidChannelCount;

+

+    /* if full duplex, make sure that they're the same device */

+

+    if (inputChannelCount > 0 && outputChannelCount > 0 &&

+        inputParameters->device != outputParameters->device)

+        return paInvalidDevice;

+

+    /* if full duplex, also make sure that they're the same number of channels */

+

+    if (inputChannelCount > 0 && outputChannelCount > 0 &&

+        inputChannelCount != outputChannelCount)

+       return paInvalidChannelCount;

+

+    /* open the device so we can do more tests */

+

+    if( inputChannelCount > 0 )

+    {

+        result = PaUtil_DeviceIndexToHostApiDeviceIndex(&device, inputParameters->device, hostApi);

+        if (result != paNoError)

+            return result;

+    }

+    else

+    {

+        result = PaUtil_DeviceIndexToHostApiDeviceIndex(&device, outputParameters->device, hostApi);

+        if (result != paNoError)

+            return result;

+    }

+

+    deviceInfo = hostApi->deviceInfos[device];

+    deviceName = (char *)deviceInfo->name;

+

+    flags = O_NONBLOCK;

+    if (inputChannelCount > 0 && outputChannelCount > 0)

+       flags |= O_RDWR;

+    else if (inputChannelCount > 0)

+       flags |= O_RDONLY;

+    else

+       flags |= O_WRONLY;

+

+    ENSURE_( tempDevHandle = open( deviceInfo->name, flags ), paDeviceUnavailable );

+

+    /* PaOssStream_Configure will do the rest of the checking for us */

+    /* PA_ENSURE( PaOssStream_Configure( tempDevHandle, deviceName, outputChannelCount, &sampleRate ) ); */

+

+    /* everything succeeded! */

+

+ error:

+    if( tempDevHandle >= 0 )

+        close( tempDevHandle );

+

+    return result;

+}

+

+/** Validate stream parameters.

+ *

+ * Aspect StreamChannels: We verify that the number of channels is within the allowed range for the device

+ */

+static PaError ValidateParameters( const PaStreamParameters *parameters, const PaDeviceInfo *deviceInfo, StreamMode mode )

+{

+    int maxChans;

+

+    assert( parameters );

+

+    if( parameters->device == paUseHostApiSpecificDeviceSpecification )

+    {

+        return paInvalidDevice;

+    }

+

+    maxChans = (mode == StreamMode_In ? deviceInfo->maxInputChannels :

+        deviceInfo->maxOutputChannels);

+    if( parameters->channelCount > maxChans )

+    {

+        return paInvalidChannelCount;

+    }

+

+    return paNoError;

+}

+

+static PaError PaOssStreamComponent_Initialize( PaOssStreamComponent *component, const PaStreamParameters *parameters,

+        int callbackMode, int fd, const char *deviceName )

+{

+    PaError result = paNoError;

+    assert( component );

+

+    memset( component, 0, sizeof (PaOssStreamComponent) );

+

+    component->fd = fd;

+    component->devName = deviceName;

+    component->userChannelCount = parameters->channelCount;

+    component->userFormat = parameters->sampleFormat;

+    component->latency = parameters->suggestedLatency;

+    component->userInterleaved = !(parameters->sampleFormat & paNonInterleaved);

+

+    if( !callbackMode && !component->userInterleaved )

+    {

+        /* Pre-allocate non-interleaved user provided buffers */

+        PA_UNLESS( component->userBuffers = PaUtil_AllocateMemory( sizeof (void *) * component->userChannelCount ),

+                paInsufficientMemory );

+    }

+

+error:

+    return result;

+}

+

+static void PaOssStreamComponent_Terminate( PaOssStreamComponent *component )

+{

+    assert( component );

+

+    if( component->fd >= 0 )

+        close( component->fd );

+    if( component->buffer )

+        PaUtil_FreeMemory( component->buffer );

+

+    if( component->userBuffers )

+        PaUtil_FreeMemory( component->userBuffers );

+

+    PaUtil_FreeMemory( component );

+}

+

+static PaError ModifyBlocking( int fd, int blocking )

+{

+    PaError result = paNoError;

+    int fflags;

+

+    ENSURE_( fflags = fcntl( fd, F_GETFL ), paUnanticipatedHostError );

+

+    if( blocking )

+        fflags &= ~O_NONBLOCK;

+    else

+        fflags |= O_NONBLOCK;

+

+    ENSURE_( fcntl( fd, F_SETFL, fflags ), paUnanticipatedHostError );

+

+error:

+    return result;

+}

+

+static PaError OpenDevices( const char *idevName, const char *odevName, int *idev, int *odev )

+{

+    PaError result = paNoError;

+    int flags = O_NONBLOCK, duplex = 0;

+    int enableBits = 0;

+    *idev = *odev = -1;

+

+    if( idevName && odevName )

+    {

+        duplex = 1;

+        flags |= O_RDWR;

+    }

+    else if( idevName )

+        flags |= O_RDONLY;

+    else

+        flags |= O_WRONLY;

+

+    /* open first in nonblocking mode, in case it's busy...

+     * A: then unset the non-blocking attribute */

+    assert( flags & O_NONBLOCK );

+    if( idevName )

+    {

+        ENSURE_( *idev = open( idevName, flags ), paDeviceUnavailable );

+        PA_ENSURE( ModifyBlocking( *idev, 1 ) ); /* Blocking */

+

+        /* Initially disable */

+        enableBits = ~PCM_ENABLE_INPUT;

+        ENSURE_( ioctl( *idev, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );

+    }

+    if( odevName )

+    {

+        if( !idevName )

+        {

+            ENSURE_( *odev = open( odevName, flags ), paDeviceUnavailable );

+            PA_ENSURE( ModifyBlocking( *odev, 1 ) ); /* Blocking */

+

+            /* Initially disable */

+            enableBits = ~PCM_ENABLE_OUTPUT;

+            ENSURE_( ioctl( *odev, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );

+        }

+        else

+        {

+            ENSURE_( *odev = dup( *idev ), paUnanticipatedHostError );

+        }

+    }

+

+error:

+    return result;

+}

+

+static PaError PaOssStream_Initialize( PaOssStream *stream, const PaStreamParameters *inputParameters, const PaStreamParameters *outputParameters,

+        PaStreamCallback callback, void *userData, PaStreamFlags streamFlags,

+        PaOSSHostApiRepresentation *ossApi )

+{

+    PaError result = paNoError;

+    int idev, odev;

+    PaUtilHostApiRepresentation *hostApi = &ossApi->inheritedHostApiRep;

+    const char *idevName = NULL, *odevName = NULL;

+

+    assert( stream );

+

+    memset( stream, 0, sizeof (PaOssStream) );

+    stream->isStopped = 1;

+

+    PA_ENSURE( PaUtil_InitializeThreading( &stream->threading ) );

+

+    if( inputParameters && outputParameters )

+    {

+        if( inputParameters->device == outputParameters->device )

+            stream->sharedDevice = 1;

+    }

+

+    if( inputParameters )

+        idevName = hostApi->deviceInfos[inputParameters->device]->name;

+    if( outputParameters )

+        odevName = hostApi->deviceInfos[outputParameters->device]->name;

+    PA_ENSURE( OpenDevices( idevName, odevName, &idev, &odev ) );

+    if( inputParameters )

+    {

+        PA_UNLESS( stream->capture = PaUtil_AllocateMemory( sizeof (PaOssStreamComponent) ), paInsufficientMemory );

+        PA_ENSURE( PaOssStreamComponent_Initialize( stream->capture, inputParameters, callback != NULL, idev, idevName ) );

+    }

+    if( outputParameters )

+    {

+        PA_UNLESS( stream->playback = PaUtil_AllocateMemory( sizeof (PaOssStreamComponent) ), paInsufficientMemory );

+        PA_ENSURE( PaOssStreamComponent_Initialize( stream->playback, outputParameters, callback != NULL, odev, odevName ) );

+    }

+

+    if( callback != NULL )

+    {

+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,

+                                               &ossApi->callbackStreamInterface, callback, userData );

+        stream->callbackMode = 1;

+    }

+    else

+    {

+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,

+                                               &ossApi->blockingStreamInterface, callback, userData );

+    }

+

+    ENSURE_( sem_init( &stream->semaphore, 0, 0 ), paInternalError );

+

+error:

+    return result;

+}

+

+static void PaOssStream_Terminate( PaOssStream *stream )

+{

+    assert( stream );

+

+    PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );

+    PaUtil_TerminateThreading( &stream->threading );

+

+    if( stream->capture )

+        PaOssStreamComponent_Terminate( stream->capture );

+    if( stream->playback )

+        PaOssStreamComponent_Terminate( stream->playback );

+

+    sem_destroy( &stream->semaphore );

+

+    PaUtil_FreeMemory( stream );

+}

+

+/** Translate from PA format to OSS native.

+ *

+ */

+static PaError Pa2OssFormat( PaSampleFormat paFormat, int *ossFormat )

+{

+    switch( paFormat )

+    {

+        case paUInt8:

+            *ossFormat = AFMT_U8;

+            break;

+        case paInt8:

+            *ossFormat = AFMT_S8;

+            break;

+        case paInt16:

+            *ossFormat = AFMT_S16_NE;

+            break;

+        default:

+            return paInternalError;     /* This shouldn't happen */

+    }

+

+    return paNoError;

+}

+

+/** Return the PA-compatible formats that this device can support.

+ *

+ */

+static PaError GetAvailableFormats( PaOssStreamComponent *component, PaSampleFormat *availableFormats )

+{

+    PaError result = paNoError;

+    int mask = 0;

+    PaSampleFormat frmts = 0;

+

+    ENSURE_( ioctl( component->fd, SNDCTL_DSP_GETFMTS, &mask ), paUnanticipatedHostError );

+    if( mask & AFMT_U8 )

+        frmts |= paUInt8;

+    if( mask & AFMT_S8 )

+        frmts |= paInt8;

+    if( mask & AFMT_S16_NE )

+        frmts |= paInt16;

+    else

+        result = paSampleFormatNotSupported;

+

+    *availableFormats = frmts;

+

+error:

+    return result;

+}

+

+static unsigned int PaOssStreamComponent_FrameSize( PaOssStreamComponent *component )

+{

+    return Pa_GetSampleSize( component->hostFormat ) * component->hostChannelCount;

+}

+

+/** Buffer size in bytes.

+ *

+ */

+static unsigned long PaOssStreamComponent_BufferSize( PaOssStreamComponent *component )

+{

+    return PaOssStreamComponent_FrameSize( component ) * component->hostFrames * component->numBufs;

+}

+

+static int CalcHigherLogTwo( int n )

+{

+    int log2 = 0;

+    while( (1<<log2) < n ) log2++;

+    return log2;

+}

+

+static PaError PaOssStreamComponent_Configure( PaOssStreamComponent *component, double sampleRate, unsigned long framesPerBuffer,

+        StreamMode streamMode, PaOssStreamComponent *master )

+{

+    PaError result = paNoError;

+    int temp, nativeFormat;

+    int sr = (int)sampleRate;

+    PaSampleFormat availableFormats = 0, hostFormat = 0;

+    int chans = component->userChannelCount;

+    int frgmt;

+    int numBufs;

+    int bytesPerBuf;

+    unsigned long bufSz;

+    unsigned long fragSz;

+    audio_buf_info bufInfo;

+

+    /* We may have a situation where only one component (the master) is configured, if both point to the same device.

+     * In that case, the second component will copy settings from the other */

+    if( !master )

+    {

+        /* Aspect BufferSettings: If framesPerBuffer is unspecified we have to infer a suitable fragment size.

+         * The hardware need not respect the requested fragment size, so we may have to adapt.

+         */

+        if( framesPerBuffer == paFramesPerBufferUnspecified )

+        {

+            bufSz = (unsigned long)(component->latency * sampleRate);

+            fragSz = bufSz / 4;

+        }

+        else

+        {

+            fragSz = framesPerBuffer;

+            bufSz = (unsigned long)(component->latency * sampleRate) + fragSz; /* Latency + 1 buffer */

+        }

+

+        PA_ENSURE( GetAvailableFormats( component, &availableFormats ) );

+        hostFormat = PaUtil_SelectClosestAvailableFormat( availableFormats, component->userFormat );

+

+        /* OSS demands at least 2 buffers, and 16 bytes per buffer */

+        numBufs = (int)PA_MAX( bufSz / fragSz, 2 );

+        bytesPerBuf = PA_MAX( fragSz * Pa_GetSampleSize( hostFormat ) * chans, 16 );

+

+        /* The fragment parameters are encoded like this:

+         * Most significant byte: number of fragments

+         * Least significant byte: exponent of fragment size (i.e., for 256, 8)

+         */

+        frgmt = (numBufs << 16) + (CalcHigherLogTwo( bytesPerBuf ) & 0xffff);

+        ENSURE_( ioctl( component->fd, SNDCTL_DSP_SETFRAGMENT, &frgmt ), paUnanticipatedHostError );

+

+        /* A: according to the OSS programmer's guide parameters should be set in this order:

+         * format, channels, rate */

+

+        /* This format should be deemed good before we get this far */

+        PA_ENSURE( Pa2OssFormat( hostFormat, &temp ) );

+        nativeFormat = temp;

+        ENSURE_( ioctl( component->fd, SNDCTL_DSP_SETFMT, &temp ), paUnanticipatedHostError );

+        PA_UNLESS( temp == nativeFormat, paInternalError );

+

+        /* try to set the number of channels */

+        ENSURE_( ioctl( component->fd, SNDCTL_DSP_CHANNELS, &chans ), paSampleFormatNotSupported );   /* XXX: Should be paInvalidChannelCount? */

+        /* It's possible that the minimum number of host channels is greater than what the user requested */

+        PA_UNLESS( chans >= component->userChannelCount, paInvalidChannelCount );

+

+        /* try to set the sample rate */

+        ENSURE_( ioctl( component->fd, SNDCTL_DSP_SPEED, &sr ), paInvalidSampleRate );

+

+        /* reject if there's no sample rate within 1% of the one requested */

+        if( (fabs( sampleRate - sr ) / sampleRate) > 0.01 )

+        {

+            PA_DEBUG(("%s: Wanted %f, closest sample rate was %d\n", __FUNCTION__, sampleRate, sr ));

+            PA_ENSURE( paInvalidSampleRate );

+        }

+

+        ENSURE_( ioctl( component->fd, streamMode == StreamMode_In ? SNDCTL_DSP_GETISPACE : SNDCTL_DSP_GETOSPACE, &bufInfo ),

+                paUnanticipatedHostError );

+        component->numBufs = bufInfo.fragstotal;

+

+        /* This needs to be the last ioctl call before the first read/write, according to the OSS programmer's guide */

+        ENSURE_( ioctl( component->fd, SNDCTL_DSP_GETBLKSIZE, &bytesPerBuf ), paUnanticipatedHostError );

+

+        component->hostFrames = bytesPerBuf / Pa_GetSampleSize( hostFormat ) / chans;

+        component->hostChannelCount = chans;

+        component->hostFormat = hostFormat;

+    }

+    else

+    {

+        component->hostFormat = master->hostFormat;

+        component->hostFrames = master->hostFrames;

+        component->hostChannelCount = master->hostChannelCount;

+        component->numBufs = master->numBufs;

+    }

+

+    PA_UNLESS( component->buffer = PaUtil_AllocateMemory( PaOssStreamComponent_BufferSize( component ) ),

+            paInsufficientMemory );

+

+error:

+    return result;

+}

+

+static PaError PaOssStreamComponent_Read( PaOssStreamComponent *component, unsigned long *frames )

+{

+    PaError result = paNoError;

+    size_t len = *frames * PaOssStreamComponent_FrameSize( component );

+    ssize_t bytesRead;

+

+    ENSURE_( bytesRead = read( component->fd, component->buffer, len ), paUnanticipatedHostError );

+    *frames = bytesRead / PaOssStreamComponent_FrameSize( component );

+    /* TODO: Handle condition where number of frames read doesn't equal number of frames requested */

+

+error:

+    return result;

+}

+

+static PaError PaOssStreamComponent_Write( PaOssStreamComponent *component, unsigned long *frames )

+{

+    PaError result = paNoError;

+    size_t len = *frames * PaOssStreamComponent_FrameSize( component );

+    ssize_t bytesWritten;

+

+    ENSURE_( bytesWritten = write( component->fd, component->buffer, len ), paUnanticipatedHostError );

+    *frames = bytesWritten / PaOssStreamComponent_FrameSize( component );

+    /* TODO: Handle condition where number of frames written doesn't equal number of frames requested */

+

+error:

+    return result;

+}

+

+/** Configure the stream according to input/output parameters.

+ *

+ * Aspect StreamChannels: The minimum number of channels supported by the device may exceed that requested by

+ * the user, if so we'll record the actual number of host channels and adapt later.

+ */

+static PaError PaOssStream_Configure( PaOssStream *stream, double sampleRate, unsigned long framesPerBuffer,

+        double *inputLatency, double *outputLatency )

+{

+    PaError result = paNoError;

+    int duplex = stream->capture && stream->playback;

+    unsigned long framesPerHostBuffer = 0;

+

+    /* We should request full duplex first thing after opening the device */

+    if( duplex && stream->sharedDevice )

+        ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETDUPLEX, 0 ), paUnanticipatedHostError );

+

+    if( stream->capture )

+    {

+        PaOssStreamComponent *component = stream->capture;

+        PA_ENSURE( PaOssStreamComponent_Configure( component, sampleRate, framesPerBuffer, StreamMode_In,

+                    NULL ) );

+

+        assert( component->hostChannelCount > 0 );

+        assert( component->hostFrames > 0 );

+

+        *inputLatency = component->hostFrames * (component->numBufs - 1) / sampleRate;

+    }

+    if( stream->playback )

+    {

+        PaOssStreamComponent *component = stream->playback, *master = stream->sharedDevice ? stream->capture : NULL;

+        PA_ENSURE( PaOssStreamComponent_Configure( component, sampleRate, framesPerBuffer, StreamMode_Out,

+                    master ) );

+

+        assert( component->hostChannelCount > 0 );

+        assert( component->hostFrames > 0 );

+

+        *outputLatency = component->hostFrames * (component->numBufs - 1) / sampleRate;

+    }

+

+    if( duplex )

+        framesPerHostBuffer = PA_MIN( stream->capture->hostFrames, stream->playback->hostFrames );

+    else if( stream->capture )

+        framesPerHostBuffer = stream->capture->hostFrames;

+    else if( stream->playback )

+        framesPerHostBuffer = stream->playback->hostFrames;

+

+    stream->framesPerHostBuffer = framesPerHostBuffer;

+    stream->pollTimeout = (int) ceil( 1e6 * framesPerHostBuffer / sampleRate );    /* Period in usecs, rounded up */

+

+    stream->sampleRate = stream->streamRepresentation.streamInfo.sampleRate = sampleRate;

+

+error:

+    return result;

+}

+

+/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */

+

+/** Open a PA OSS stream.

+ *

+ * Aspect StreamChannels: The number of channels is specified per direction (in/out), and can differ between the

+ * two. However, OSS doesn't support separate configuration spaces for capture and playback so if both

+ * directions are the same device we will demand the same number of channels. The number of channels can range

+ * from 1 to the maximum supported by the device.

+ *

+ * Aspect BufferSettings: If framesPerBuffer != paFramesPerBufferUnspecified the number of frames per callback

+ * must reflect this, in addition the host latency per device should approximate the corresponding

+ * suggestedLatency. Based on these constraints we need to determine a number of frames per host buffer that

+ * both capture and playback can agree on (they can be different devices), the buffer processor can adapt

+ * between host and user buffer size, but the ratio should preferably be integral.

+ */

+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,

+                           PaStream** s,

+                           const PaStreamParameters *inputParameters,

+                           const PaStreamParameters *outputParameters,

+                           double sampleRate,

+                           unsigned long framesPerBuffer,

+                           PaStreamFlags streamFlags,

+                           PaStreamCallback *streamCallback,

+                           void *userData )

+{

+    PaError result = paNoError;

+    PaOSSHostApiRepresentation *ossHostApi = (PaOSSHostApiRepresentation*)hostApi;

+    PaOssStream *stream = NULL;

+    int inputChannelCount = 0, outputChannelCount = 0;

+    PaSampleFormat inputSampleFormat = 0, outputSampleFormat = 0, inputHostFormat = 0, outputHostFormat = 0;

+    const PaDeviceInfo *inputDeviceInfo = 0, *outputDeviceInfo = 0;

+    int bpInitialized = 0;

+    double inLatency = 0., outLatency = 0.;

+

+    /* validate platform specific flags */

+    if( (streamFlags & paPlatformSpecificFlags) != 0 )

+        return paInvalidFlag; /* unexpected platform specific flag */

+

+    if( inputParameters )

+    {

+        /* unless alternate device specification is supported, reject the use of

+            paUseHostApiSpecificDeviceSpecification */

+        inputDeviceInfo = hostApi->deviceInfos[inputParameters->device];

+        PA_ENSURE( ValidateParameters( inputParameters, inputDeviceInfo, StreamMode_In ) );

+

+        inputChannelCount = inputParameters->channelCount;

+        inputSampleFormat = inputParameters->sampleFormat;

+    }

+    if( outputParameters )

+    {

+        outputDeviceInfo = hostApi->deviceInfos[outputParameters->device];

+        PA_ENSURE( ValidateParameters( outputParameters, outputDeviceInfo, StreamMode_Out ) );

+

+        outputChannelCount = outputParameters->channelCount;

+        outputSampleFormat = outputParameters->sampleFormat;

+    }

+

+    /* Aspect StreamChannels: We currently demand that number of input and output channels are the same, if the same

+     * device is opened for both directions

+     */

+    if( inputChannelCount > 0 && outputChannelCount > 0 )

+    {

+        if( inputParameters->device == outputParameters->device )

+        {

+            if( inputParameters->channelCount != outputParameters->channelCount )

+                return paInvalidChannelCount;

+        }

+    }

+

+    /* allocate and do basic initialization of the stream structure */

+    PA_UNLESS( stream = (PaOssStream*)PaUtil_AllocateMemory( sizeof(PaOssStream) ), paInsufficientMemory );

+    PA_ENSURE( PaOssStream_Initialize( stream, inputParameters, outputParameters, streamCallback, userData, streamFlags, ossHostApi ) );

+

+    PA_ENSURE( PaOssStream_Configure( stream, sampleRate, framesPerBuffer, &inLatency, &outLatency ) );

+

+    PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );

+

+    if( inputParameters )

+    {

+        inputHostFormat = stream->capture->hostFormat;

+        stream->streamRepresentation.streamInfo.inputLatency = inLatency +

+            PaUtil_GetBufferProcessorInputLatency( &stream->bufferProcessor ) / sampleRate;

+    }

+    if( outputParameters )

+    {

+        outputHostFormat = stream->playback->hostFormat;

+        stream->streamRepresentation.streamInfo.outputLatency = outLatency +

+            PaUtil_GetBufferProcessorOutputLatency( &stream->bufferProcessor ) / sampleRate;

+    }

+

+    /* Initialize buffer processor with fixed host buffer size.

+     * Aspect StreamSampleFormat: Here we commit the user and host sample formats, PA infrastructure will

+     * convert between the two.

+     */

+    PA_ENSURE( PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,

+              inputChannelCount, inputSampleFormat, inputHostFormat, outputChannelCount, outputSampleFormat,

+              outputHostFormat, sampleRate, streamFlags, framesPerBuffer, stream->framesPerHostBuffer,

+              paUtilFixedHostBufferSize, streamCallback, userData ) );

+    bpInitialized = 1;

+

+    *s = (PaStream*)stream;

+

+    return result;

+

+error:

+    if( bpInitialized )

+        PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );

+    if( stream )

+        PaOssStream_Terminate( stream );

+

+    return result;

+}

+

+/*! Poll on I/O filedescriptors.

+

+  Poll till we've determined there's data for read or write. In the full-duplex case,

+  we don't want to hang around forever waiting for either input or output frames, so

+  whenever we have a timed out filedescriptor we check if we're nearing under/overrun

+  for the other direction (critical limit set at one buffer). If so, we exit the waiting

+  state, and go on with what we got. We align the number of frames on a host buffer

+  boundary because it is possible that the buffer size differs for the two directions and

+  the host buffer size is a compromise between the two.

+  */

+static PaError PaOssStream_WaitForFrames( PaOssStream *stream, unsigned long *frames )

+{

+    PaError result = paNoError;

+    int pollPlayback = 0, pollCapture = 0;

+    int captureAvail = INT_MAX, playbackAvail = INT_MAX, commonAvail;

+    audio_buf_info bufInfo;

+    /* int ofs = 0, nfds = stream->nfds; */

+    fd_set readFds, writeFds;

+    int nfds = 0;

+    struct timeval selectTimeval = {0, 0};

+    unsigned long timeout = stream->pollTimeout;    /* In usecs */

+    int captureFd = -1, playbackFd = -1;

+

+    assert( stream );

+    assert( frames );

+

+    if( stream->capture )

+    {

+        pollCapture = 1;

+        captureFd = stream->capture->fd;

+        /* stream->capture->pfd->events = POLLIN; */

+    }

+    if( stream->playback )

+    {

+        pollPlayback = 1;

+        playbackFd = stream->playback->fd;

+        /* stream->playback->pfd->events = POLLOUT; */

+    }

+

+    FD_ZERO( &readFds );

+    FD_ZERO( &writeFds );

+

+    while( pollPlayback || pollCapture )

+    {

+        pthread_testcancel();

+

+        /* select may modify the timeout parameter */

+        selectTimeval.tv_usec = timeout;

+        nfds = 0;

+

+        if( pollCapture )

+        {

+            FD_SET( captureFd, &readFds );

+            nfds = captureFd + 1;

+        }

+        if( pollPlayback )

+        {

+            FD_SET( playbackFd, &writeFds );

+            nfds = PA_MAX( nfds, playbackFd + 1 );

+        }

+        ENSURE_( select( nfds, &readFds, &writeFds, NULL, &selectTimeval ), paUnanticipatedHostError );

+        /*

+        if( poll( stream->pfds + ofs, nfds, stream->pollTimeout ) < 0 )

+        {

+

+            ENSURE_( -1, paUnanticipatedHostError );

+        }

+        */

+        pthread_testcancel();

+

+        if( pollCapture )

+        {

+            if( FD_ISSET( captureFd, &readFds ) )

+            {

+                FD_CLR( captureFd, &readFds );

+                pollCapture = 0;

+            }

+            /*

+            if( stream->capture->pfd->revents & POLLIN )

+            {

+                --nfds;

+                ++ofs;

+                pollCapture = 0;

+            }

+            */

+            else if( stream->playback ) /* Timed out, go on with playback? */

+            {

+                /*PA_DEBUG(( "%s: Trying to poll again for capture frames, pollTimeout: %d\n",

+                            __FUNCTION__, stream->pollTimeout ));*/

+            }

+        }

+        if( pollPlayback )

+        {

+            if( FD_ISSET( playbackFd, &writeFds ) )

+            {

+                FD_CLR( playbackFd, &writeFds );

+                pollPlayback = 0;

+            }

+            /*

+            if( stream->playback->pfd->revents & POLLOUT )

+            {

+                --nfds;

+                pollPlayback = 0;

+            }

+            */

+            else if( stream->capture )  /* Timed out, go on with capture? */

+            {

+                /*PA_DEBUG(( "%s: Trying to poll again for playback frames, pollTimeout: %d\n\n",

+                            __FUNCTION__, stream->pollTimeout ));*/

+            }

+        }

+    }

+

+    if( stream->capture )

+    {

+        ENSURE_( ioctl( captureFd, SNDCTL_DSP_GETISPACE, &bufInfo ), paUnanticipatedHostError );

+        captureAvail = bufInfo.fragments * stream->capture->hostFrames;

+        if( !captureAvail )

+            PA_DEBUG(( "%s: captureAvail: 0\n", __FUNCTION__ ));

+

+        captureAvail = captureAvail == 0 ? INT_MAX : captureAvail;      /* Disregard if zero */

+    }

+    if( stream->playback )

+    {

+        ENSURE_( ioctl( playbackFd, SNDCTL_DSP_GETOSPACE, &bufInfo ), paUnanticipatedHostError );

+        playbackAvail = bufInfo.fragments * stream->playback->hostFrames;

+        if( !playbackAvail )

+        {

+            PA_DEBUG(( "%s: playbackAvail: 0\n", __FUNCTION__ ));

+        }

+

+        playbackAvail = playbackAvail == 0 ? INT_MAX : playbackAvail;      /* Disregard if zero */

+    }

+

+    commonAvail = PA_MIN( captureAvail, playbackAvail );

+    if( commonAvail == INT_MAX )

+        commonAvail = 0;

+    commonAvail -= commonAvail % stream->framesPerHostBuffer;

+

+    assert( commonAvail != INT_MAX );

+    assert( commonAvail >= 0 );

+    *frames = commonAvail;

+

+error:

+    return result;

+}

+

+/** Prepare stream for capture/playback.

+ *

+ * In order to synchronize capture and playback properly we use the SETTRIGGER command.

+ */

+static PaError PaOssStream_Prepare( PaOssStream *stream )

+{

+    PaError result = paNoError;

+    int enableBits = 0;

+

+    if( stream->triggered )

+        return result;

+

+    if( stream->playback )

+    {

+        size_t bufSz = PaOssStreamComponent_BufferSize( stream->playback );

+        memset( stream->playback->buffer, 0, bufSz );

+

+        /* Looks like we have to turn off blocking before we try this, but if we don't fill the buffer

+         * OSS will complain. */

+        PA_ENSURE( ModifyBlocking( stream->playback->fd, 0 ) );

+        while (1)

+        {

+            if( write( stream->playback->fd, stream->playback->buffer, bufSz ) < 0 )

+                break;

+        }

+        PA_ENSURE( ModifyBlocking( stream->playback->fd, 1 ) );

+    }

+

+    if( stream->sharedDevice )

+    {

+        enableBits = PCM_ENABLE_INPUT | PCM_ENABLE_OUTPUT;

+        ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );

+    }

+    else

+    {

+        if( stream->capture )

+        {

+            enableBits = PCM_ENABLE_INPUT;

+            ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );

+        }

+        if( stream->playback )

+        {

+            enableBits = PCM_ENABLE_OUTPUT;

+            ENSURE_( ioctl( stream->playback->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );

+        }

+    }

+

+    /* Ok, we have triggered the stream */

+    stream->triggered = 1;

+

+error:

+    return result;

+}

+

+/** Stop audio processing

+ *

+ */

+static PaError PaOssStream_Stop( PaOssStream *stream, int abort )

+{

+    PaError result = paNoError;

+

+    /* Looks like the only safe way to stop audio without reopening the device is SNDCTL_DSP_POST.

+     * Also disable capture/playback till the stream is started again */

+    if( stream->capture )

+    {

+        ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_POST, 0 ), paUnanticipatedHostError );

+    }

+    if( stream->playback && !stream->sharedDevice )

+    {

+        ENSURE_( ioctl( stream->playback->fd, SNDCTL_DSP_POST, 0 ), paUnanticipatedHostError );

+    }

+

+error:

+    return result;

+}

+

+/** Clean up after thread exit.

+ *

+ * Aspect StreamState: If the user has registered a streamFinishedCallback it will be called here

+ */

+static void OnExit( void *data )

+{

+    PaOssStream *stream = (PaOssStream *) data;

+    assert( data );

+

+    PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer );

+

+    PaOssStream_Stop( stream, stream->callbackAbort );

+

+    PA_DEBUG(( "OnExit: Stoppage\n" ));

+

+    /* Eventually notify user all buffers have played */

+    if( stream->streamRepresentation.streamFinishedCallback )

+        stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );

+

+    stream->callbackAbort = 0;      /* Clear state */

+    stream->isActive = 0;

+}

+

+static PaError SetUpBuffers( PaOssStream *stream, unsigned long framesAvail )

+{

+    PaError result = paNoError;

+

+    if( stream->capture )

+    {

+        PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, 0, stream->capture->buffer,

+                stream->capture->hostChannelCount );

+        PaUtil_SetInputFrameCount( &stream->bufferProcessor, framesAvail );

+    }

+    if( stream->playback )

+    {

+        PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, 0, stream->playback->buffer,

+                stream->playback->hostChannelCount );

+        PaUtil_SetOutputFrameCount( &stream->bufferProcessor, framesAvail );

+    }

+

+    return result;

+}

+

+/** Thread procedure for callback processing.

+ *

+ * Aspect StreamState: StartStream will wait on this to initiate audio processing, useful in case the

+ * callback should be used for buffer priming. When the stream is cancelled a separate function will

+ * take care of the transition to the Callback Finished state (the stream isn't considered Stopped

+ * before StopStream() or AbortStream() are called).

+ */

+static void *PaOSS_AudioThreadProc( void *userData )

+{

+    PaError result = paNoError;

+    PaOssStream *stream = (PaOssStream*)userData;

+    unsigned long framesAvail = 0, framesProcessed = 0;

+    int callbackResult = paContinue;

+    int triggered = stream->triggered;  /* See if SNDCTL_DSP_TRIGGER has been issued already */

+    int initiateProcessing = triggered;    /* Already triggered? */

+    PaStreamCallbackFlags cbFlags = 0;  /* We might want to keep state across iterations */

+    PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /* TODO: IMPLEMENT ME */

+

+    /*

+#if ( SOUND_VERSION > 0x030904 )

+        audio_errinfo errinfo;

+#endif

+*/

+

+    assert( stream );

+

+    pthread_cleanup_push( &OnExit, stream );	/* Execute OnExit when exiting */

+

+    /* The first time the stream is started we use SNDCTL_DSP_TRIGGER to accurately start capture and

+     * playback in sync, when the stream is restarted after being stopped we simply start by reading/

+     * writing.

+     */

+    PA_ENSURE( PaOssStream_Prepare( stream ) );

+

+    /* If we are to initiate processing implicitly by reading/writing data, we start off in blocking mode */

+    if( initiateProcessing )

+    {

+        /* Make sure devices are in blocking mode */

+        if( stream->capture )

+            ModifyBlocking( stream->capture->fd, 1 );

+        if( stream->playback )

+            ModifyBlocking( stream->playback->fd, 1 );

+    }

+

+    while( 1 )

+    {

+        pthread_testcancel();

+

+        if( stream->callbackStop && callbackResult == paContinue )

+        {

+            PA_DEBUG(( "Setting callbackResult to paComplete\n" ));

+            callbackResult = paComplete;

+        }

+

+        /* Aspect StreamState: Because of the messy OSS scheme we can't explicitly trigger device start unless

+         * the stream has been recently started, we will have to go right ahead and read/write in blocking

+         * fashion to trigger operation. Therefore we begin with processing one host buffer before we switch

+         * to non-blocking mode.

+         */

+        if( !initiateProcessing )

+        {

+            /* Wait on available frames */

+            PA_ENSURE( PaOssStream_WaitForFrames( stream, &framesAvail ) );

+            assert( framesAvail % stream->framesPerHostBuffer == 0 );

+        }

+        else

+        {

+            framesAvail = stream->framesPerHostBuffer;

+        }

+

+        while( framesAvail > 0 )

+        {

+            unsigned long frames = framesAvail;

+

+            pthread_testcancel();

+

+            PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );

+

+            /* Read data */

+            if ( stream->capture )

+            {

+                PA_ENSURE( PaOssStreamComponent_Read( stream->capture, &frames ) );

+                if( frames < framesAvail )

+                {

+                    PA_DEBUG(( "Read %lu less frames than requested\n", framesAvail - frames ));

+                    framesAvail = frames;

+                }

+            }

+

+#if ( SOUND_VERSION >= 0x030904 )

+            /*

+               Check with OSS to see if there have been any under/overruns

+               since last time we checked.

+               */

+            /*

+            if( ioctl( stream->deviceHandle, SNDCTL_DSP_GETERROR, &errinfo ) >= 0 )

+            {

+                if( errinfo.play_underruns )

+                    cbFlags |= paOutputUnderflow ;

+                if( errinfo.record_underruns )

+                    cbFlags |= paInputUnderflow ;

+            }

+            else

+                PA_DEBUG(( "SNDCTL_DSP_GETERROR command failed: %s\n", strerror( errno ) ));

+                */

+#endif

+

+            PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo,

+                    cbFlags );

+            cbFlags = 0;

+            PA_ENSURE( SetUpBuffers( stream, framesAvail ) );

+

+            framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor,

+                    &callbackResult );

+            assert( framesProcessed == framesAvail );

+            PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );

+

+            if ( stream->playback )

+            {

+                frames = framesAvail;

+

+                PA_ENSURE( PaOssStreamComponent_Write( stream->playback, &frames ) );

+                if( frames < framesAvail )

+                {

+                    /* TODO: handle bytesWritten != bytesRequested (slippage?) */

+                    PA_DEBUG(( "Wrote %lu less frames than requested\n", framesAvail - frames ));

+                }

+            }

+

+            framesAvail -= framesProcessed;

+            stream->framesProcessed += framesProcessed;

+

+            if( callbackResult != paContinue )

+                break;

+        }

+

+        if( initiateProcessing || !triggered )

+        {

+            /* Non-blocking */

+            if( stream->capture )

+                PA_ENSURE( ModifyBlocking( stream->capture->fd, 0 ) );

+            if( stream->playback && !stream->sharedDevice )

+                PA_ENSURE( ModifyBlocking( stream->playback->fd, 0 ) );

+

+            initiateProcessing = 0;

+            sem_post( &stream->semaphore );

+        }

+

+        if( callbackResult != paContinue )

+        {

+            stream->callbackAbort = callbackResult == paAbort;

+            if( stream->callbackAbort || PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) )

+                break;

+        }

+    }

+

+    pthread_cleanup_pop( 1 );

+

+error:

+    pthread_exit( NULL );

+}

+

+/** Close the stream.

+ *

+ */

+static PaError CloseStream( PaStream* s )

+{

+    PaError result = paNoError;

+    PaOssStream *stream = (PaOssStream*)s;

+

+    assert( stream );

+

+    PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );

+    PaOssStream_Terminate( stream );

+

+    return result;

+}

+

+/** Start the stream.

+ *

+ * Aspect StreamState: After returning, the stream shall be in the Active state, implying that an eventual

+ * callback will be repeatedly called in a separate thread. If a separate thread is started this function

+ * will block untill it has started processing audio, otherwise audio processing is started directly.

+ */

+static PaError StartStream( PaStream *s )

+{

+    PaError result = paNoError;

+    PaOssStream *stream = (PaOssStream*)s;

+

+    stream->isActive = 1;

+    stream->isStopped = 0;

+    stream->lastPosPtr = 0;

+    stream->lastStreamBytes = 0;

+    stream->framesProcessed = 0;

+

+    /* only use the thread for callback streams */

+    if( stream->bufferProcessor.streamCallback )

+    {

+        PA_ENSURE( PaUtil_StartThreading( &stream->threading, &PaOSS_AudioThreadProc, stream ) );

+        sem_wait( &stream->semaphore );

+    }

+    else

+        PA_ENSURE( PaOssStream_Prepare( stream ) );

+

+error:

+    return result;

+}

+

+static PaError RealStop( PaOssStream *stream, int abort )

+{

+    PaError result = paNoError;

+

+    if( stream->callbackMode )

+    {

+        if( abort )

+            stream->callbackAbort = 1;

+        else

+            stream->callbackStop = 1;

+

+        PA_ENSURE( PaUtil_CancelThreading( &stream->threading, !abort, NULL ) );

+

+        stream->callbackStop = stream->callbackAbort = 0;

+    }

+    else

+        PA_ENSURE( PaOssStream_Stop( stream, abort ) );

+

+    stream->isStopped = 1;

+

+error:

+    return result;

+}

+

+/** Stop the stream.

+ *

+ * Aspect StreamState: This will cause the stream to transition to the Stopped state, playing all enqueued

+ * buffers.

+ */

+static PaError StopStream( PaStream *s )

+{

+    return RealStop( (PaOssStream *)s, 0 );

+}

+

+/** Abort the stream.

+ *

+ * Aspect StreamState: This will cause the stream to transition to the Stopped state, discarding all enqueued

+ * buffers. Note that the buffers are not currently correctly discarded, this is difficult without closing

+ * the OSS device.

+ */

+static PaError AbortStream( PaStream *s )

+{

+    return RealStop( (PaOssStream *)s, 1 );

+}

+

+/** Is the stream in the Stopped state.

+ *

+ */

+static PaError IsStreamStopped( PaStream *s )

+{

+    PaOssStream *stream = (PaOssStream*)s;

+

+    return (stream->isStopped);

+}

+

+/** Is the stream in the Active state.

+ *

+ */

+static PaError IsStreamActive( PaStream *s )

+{

+    PaOssStream *stream = (PaOssStream*)s;

+

+    return (stream->isActive);

+}

+

+static PaTime GetStreamTime( PaStream *s )

+{

+    PaOssStream *stream = (PaOssStream*)s;

+    count_info info;

+    int delta;

+

+    if( stream->playback ) {

+        if( ioctl( stream->playback->fd, SNDCTL_DSP_GETOPTR, &info) == 0 ) {

+            delta = ( info.bytes - stream->lastPosPtr ) /* & 0x000FFFFF*/;

+            return (float)(stream->lastStreamBytes + delta) / PaOssStreamComponent_FrameSize( stream->playback ) / stream->sampleRate;

+        }

+    }

+    else {

+        if (ioctl( stream->capture->fd, SNDCTL_DSP_GETIPTR, &info) == 0) {

+            delta = (info.bytes - stream->lastPosPtr) /*& 0x000FFFFF*/;

+            return (float)(stream->lastStreamBytes + delta) / PaOssStreamComponent_FrameSize( stream->capture ) / stream->sampleRate;

+        }

+    }

+

+    /* the ioctl failed, but we can still give a coarse estimate */

+

+    return stream->framesProcessed / stream->sampleRate;

+}

+

+

+static double GetStreamCpuLoad( PaStream* s )

+{

+    PaOssStream *stream = (PaOssStream*)s;

+

+    return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );

+}

+

+

+/*

+    As separate stream interfaces are used for blocking and callback

+    streams, the following functions can be guaranteed to only be called

+    for blocking streams.

+*/

+

+

+static PaError ReadStream( PaStream* s,

+                           void *buffer,

+                           unsigned long frames )

+{

+    PaOssStream *stream = (PaOssStream*)s;

+    int bytesRequested, bytesRead;

+    unsigned long framesRequested;

+    void *userBuffer;

+

+    /* If user input is non-interleaved, PaUtil_CopyInput will manipulate the channel pointers,

+     * so we copy the user provided pointers */

+    if( stream->bufferProcessor.userInputIsInterleaved )

+        userBuffer = buffer;

+    else /* Copy channels into local array */

+    {

+        userBuffer = stream->capture->userBuffers;

+        memcpy( (void *)userBuffer, buffer, sizeof (void *) * stream->capture->userChannelCount );

+    }

+

+    while( frames )

+    {

+        framesRequested = PA_MIN( frames, stream->capture->hostFrames );

+

+	bytesRequested = framesRequested * PaOssStreamComponent_FrameSize( stream->capture );

+	bytesRead = read( stream->capture->fd, stream->capture->buffer, bytesRequested );

+	if ( bytesRequested != bytesRead )

+	    return paUnanticipatedHostError;

+

+	PaUtil_SetInputFrameCount( &stream->bufferProcessor, stream->capture->hostFrames );

+	PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, 0, stream->capture->buffer, stream->capture->hostChannelCount );

+        PaUtil_CopyInput( &stream->bufferProcessor, &userBuffer, framesRequested );

+	frames -= framesRequested;

+    }

+    return paNoError;

+}

+

+

+static PaError WriteStream( PaStream *s, const void *buffer, unsigned long frames )

+{

+    PaOssStream *stream = (PaOssStream*)s;

+    int bytesRequested, bytesWritten;

+    unsigned long framesConverted;

+    const void *userBuffer;

+

+    /* If user output is non-interleaved, PaUtil_CopyOutput will manipulate the channel pointers,

+     * so we copy the user provided pointers */

+    if( stream->bufferProcessor.userOutputIsInterleaved )

+        userBuffer = buffer;

+    else

+    {

+        /* Copy channels into local array */

+        userBuffer = stream->playback->userBuffers;

+        memcpy( (void *)userBuffer, buffer, sizeof (void *) * stream->playback->userChannelCount );

+    }

+

+    while( frames )

+    {

+	PaUtil_SetOutputFrameCount( &stream->bufferProcessor, stream->playback->hostFrames );

+	PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, 0, stream->playback->buffer, stream->playback->hostChannelCount );

+

+	framesConverted = PaUtil_CopyOutput( &stream->bufferProcessor, &userBuffer, frames );

+	frames -= framesConverted;

+

+	bytesRequested = framesConverted * PaOssStreamComponent_FrameSize( stream->playback );

+	bytesWritten = write( stream->playback->fd, stream->playback->buffer, bytesRequested );

+

+	if ( bytesRequested != bytesWritten )

+	    return paUnanticipatedHostError;

+    }

+    return paNoError;

+}

+

+

+static signed long GetStreamReadAvailable( PaStream* s )

+{

+    PaOssStream *stream = (PaOssStream*)s;

+    audio_buf_info info;

+

+    if( ioctl( stream->capture->fd, SNDCTL_DSP_GETISPACE, &info ) < 0 )

+        return paUnanticipatedHostError;

+    return info.fragments * stream->capture->hostFrames;

+}

+

+

+/* TODO: Compute number of allocated bytes somewhere else, can we use ODELAY with capture */

+static signed long GetStreamWriteAvailable( PaStream* s )

+{

+    PaOssStream *stream = (PaOssStream*)s;

+    int delay = 0;

+

+    if( ioctl( stream->playback->fd, SNDCTL_DSP_GETODELAY, &delay ) < 0 )

+        return paUnanticipatedHostError;

+

+    return (PaOssStreamComponent_BufferSize( stream->playback ) - delay) / PaOssStreamComponent_FrameSize( stream->playback );

+}

+

diff --git a/src/engine/external/portaudio/pa_unix_util.c b/src/engine/external/portaudio/pa_unix_util.c
new file mode 100644
index 00000000..6508320b
--- /dev/null
+++ b/src/engine/external/portaudio/pa_unix_util.c
@@ -0,0 +1,666 @@
+/*

+ * $Id: pa_unix_util.c 1232 2007-06-16 14:49:43Z rossb $

+ * Portable Audio I/O Library

+ * UNIX platform-specific support functions

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2000 Ross Bencina

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup unix_src

+*/

+ 

+#include <pthread.h>

+#include <unistd.h>

+#include <stdlib.h>

+#include <time.h>

+#include <sys/time.h>

+#include <assert.h>

+#include <string.h> /* For memset */

+#include <math.h>

+#include <errno.h>

+

+#include "pa_util.h"

+#include "pa_unix_util.h"

+#include "pa_debugprint.h"

+

+/*

+   Track memory allocations to avoid leaks.

+ */

+

+#if PA_TRACK_MEMORY

+static int numAllocations_ = 0;

+#endif

+

+

+void *PaUtil_AllocateMemory( long size )

+{

+    void *result = malloc( size );

+

+#if PA_TRACK_MEMORY

+    if( result != NULL ) numAllocations_ += 1;

+#endif

+    return result;

+}

+

+

+void PaUtil_FreeMemory( void *block )

+{

+    if( block != NULL )

+    {

+        free( block );

+#if PA_TRACK_MEMORY

+        numAllocations_ -= 1;

+#endif

+

+    }

+}

+

+

+int PaUtil_CountCurrentlyAllocatedBlocks( void )

+{

+#if PA_TRACK_MEMORY

+    return numAllocations_;

+#else

+    return 0;

+#endif

+}

+

+

+void Pa_Sleep( long msec )

+{

+#ifdef HAVE_NANOSLEEP

+    struct timespec req = {0}, rem = {0};

+    PaTime time = msec / 1.e3;

+    req.tv_sec = (time_t)time;

+    assert(time - req.tv_sec < 1.0);

+    req.tv_nsec = (long)((time - req.tv_sec) * 1.e9);

+    nanosleep(&req, &rem);

+    /* XXX: Try sleeping the remaining time (contained in rem) if interrupted by a signal? */

+#else

+    while( msec > 999 )     /* For OpenBSD and IRIX, argument */

+        {                   /* to usleep must be < 1000000.   */

+        usleep( 999000 );

+        msec -= 999;

+        }

+    usleep( msec * 1000 );

+#endif

+}

+

+/*            *** NOT USED YET: ***

+static int usePerformanceCounter_;

+static double microsecondsPerTick_;

+*/

+

+void PaUtil_InitializeClock( void )

+{

+    /* TODO */

+}

+

+

+PaTime PaUtil_GetTime( void )

+{

+#ifdef HAVE_CLOCK_GETTIME

+    struct timespec tp;

+    clock_gettime(CLOCK_REALTIME, &tp);

+    return (PaTime)(tp.tv_sec + tp.tv_nsec / 1.e9);

+#else

+    struct timeval tv;

+    gettimeofday( &tv, NULL );

+    return (PaTime) tv.tv_usec / 1000000. + tv.tv_sec;

+#endif

+}

+

+PaError PaUtil_InitializeThreading( PaUtilThreading *threading )

+{

+    (void) paUtilErr_;

+    return paNoError;

+}

+

+void PaUtil_TerminateThreading( PaUtilThreading *threading )

+{

+}

+

+PaError PaUtil_StartThreading( PaUtilThreading *threading, void *(*threadRoutine)(void *), void *data )

+{

+    pthread_create( &threading->callbackThread, NULL, threadRoutine, data );

+    return paNoError;

+}

+

+PaError PaUtil_CancelThreading( PaUtilThreading *threading, int wait, PaError *exitResult )

+{

+    PaError result = paNoError;

+    void *pret;

+

+    if( exitResult )

+        *exitResult = paNoError;

+

+    /* Only kill the thread if it isn't in the process of stopping (flushing adaptation buffers) */

+    if( !wait )

+        pthread_cancel( threading->callbackThread );   /* XXX: Safe to call this if the thread has exited on its own? */

+    pthread_join( threading->callbackThread, &pret );

+

+#ifdef PTHREAD_CANCELED

+    if( pret && PTHREAD_CANCELED != pret )

+#else

+    /* !wait means the thread may have been canceled */

+    if( pret && wait )

+#endif

+    {

+        if( exitResult )

+            *exitResult = *(PaError *) pret;

+        free( pret );

+    }

+

+    return result;

+}

+

+/* Threading */

+/* paUnixMainThread 

+ * We have to be a bit careful with defining this global variable,

+ * as explained below. */

+#ifdef __apple__

+/* apple/gcc has a "problem" with global vars and dynamic libs.

+   Initializing it seems to fix the problem.

+   Described a bit in this thread:

+   http://gcc.gnu.org/ml/gcc/2005-06/msg00179.html

+*/

+pthread_t paUnixMainThread = 0;

+#else

+/*pthreads are opaque. We don't know that asigning it an int value

+  always makes sense, so we don't initialize it unless we have to.*/

+pthread_t paUnixMainThread = 0;

+#endif

+

+PaError PaUnixThreading_Initialize()

+{

+    paUnixMainThread = pthread_self();

+    return paNoError;

+}

+

+static PaError BoostPriority( PaUnixThread* self )

+{

+    PaError result = paNoError;

+    struct sched_param spm = { 0 };

+    /* Priority should only matter between contending FIFO threads? */

+    spm.sched_priority = 1;

+

+    assert( self );

+

+    if( pthread_setschedparam( self->thread, SCHED_FIFO, &spm ) != 0 )

+    {

+        PA_UNLESS( errno == EPERM, paInternalError );  /* Lack permission to raise priority */

+        PA_DEBUG(( "Failed bumping priority\n" ));

+        result = 0;

+    }

+    else

+    {

+        result = 1; /* Success */

+    }

+error:

+    return result;

+}

+

+PaError PaUnixThread_New( PaUnixThread* self, void* (*threadFunc)( void* ), void* threadArg, PaTime waitForChild,

+        int rtSched )

+{

+    PaError result = paNoError;

+    pthread_attr_t attr;

+    int started = 0;

+

+    memset( self, 0, sizeof (PaUnixThread) );

+    PaUnixMutex_Initialize( &self->mtx );

+    PA_ASSERT_CALL( pthread_cond_init( &self->cond, NULL ), 0 );

+

+    self->parentWaiting = 0 != waitForChild;

+

+    /* Spawn thread */

+

+/* Temporarily disabled since we should test during configuration for presence of required mman.h header */

+#if 0

+#if defined _POSIX_MEMLOCK && (_POSIX_MEMLOCK != -1)

+    if( rtSched )

+    {

+        if( mlockall( MCL_CURRENT | MCL_FUTURE ) < 0 )

+        {

+            int savedErrno = errno;             /* In case errno gets overwritten */

+            assert( savedErrno != EINVAL );     /* Most likely a programmer error */

+            PA_UNLESS( (savedErrno == EPERM), paInternalError );

+            PA_DEBUG(( "%s: Failed locking memory\n", __FUNCTION__ ));

+        }

+        else

+            PA_DEBUG(( "%s: Successfully locked memory\n", __FUNCTION__ ));

+    }

+#endif

+#endif

+

+    PA_UNLESS( !pthread_attr_init( &attr ), paInternalError );

+    /* Priority relative to other processes */

+    PA_UNLESS( !pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ), paInternalError );   

+

+    PA_UNLESS( !pthread_create( &self->thread, &attr, threadFunc, threadArg ), paInternalError );

+    started = 1;

+

+    if( rtSched )

+    {

+#if 0

+        if( self->useWatchdog )

+        {

+            int err;

+            struct sched_param wdSpm = { 0 };

+            /* Launch watchdog, watchdog sets callback thread priority */

+            int prio = PA_MIN( self->rtPrio + 4, sched_get_priority_max( SCHED_FIFO ) );

+            wdSpm.sched_priority = prio;

+

+            PA_UNLESS( !pthread_attr_init( &attr ), paInternalError );

+            PA_UNLESS( !pthread_attr_setinheritsched( &attr, PTHREAD_EXPLICIT_SCHED ), paInternalError );

+            PA_UNLESS( !pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ), paInternalError );

+            PA_UNLESS( !pthread_attr_setschedpolicy( &attr, SCHED_FIFO ), paInternalError );

+            PA_UNLESS( !pthread_attr_setschedparam( &attr, &wdSpm ), paInternalError );

+            if( (err = pthread_create( &self->watchdogThread, &attr, &WatchdogFunc, self )) )

+            {

+                PA_UNLESS( err == EPERM, paInternalError );

+                /* Permission error, go on without realtime privileges */

+                PA_DEBUG(( "Failed bumping priority\n" ));

+            }

+            else

+            {

+                int policy;

+                self->watchdogRunning = 1;

+                PA_ENSURE_SYSTEM( pthread_getschedparam( self->watchdogThread, &policy, &wdSpm ), 0 );

+                /* Check if priority is right, policy could potentially differ from SCHED_FIFO (but that's alright) */

+                if( wdSpm.sched_priority != prio )

+                {

+                    PA_DEBUG(( "Watchdog priority not set correctly (%d)\n", wdSpm.sched_priority ));

+                    PA_ENSURE( paInternalError );

+                }

+            }

+        }

+        else

+#endif

+            PA_ENSURE( BoostPriority( self ) );

+

+        {

+            int policy;

+            struct sched_param spm;

+            pthread_getschedparam(self->thread, &policy, &spm);

+        }

+    }

+    

+    if( self->parentWaiting )

+    {

+        PaTime till;

+        struct timespec ts;

+        int res = 0;

+        PaTime now;

+

+        PA_ENSURE( PaUnixMutex_Lock( &self->mtx ) );

+

+        /* Wait for stream to be started */

+        now = PaUtil_GetTime();

+        till = now + waitForChild;

+

+        while( self->parentWaiting && !res )

+        {

+            if( waitForChild > 0 )

+            {

+                ts.tv_sec = (time_t) floor( till );

+                ts.tv_nsec = (long) ((till - floor( till )) * 1e9);

+                res = pthread_cond_timedwait( &self->cond, &self->mtx.mtx, &ts );

+            }

+            else

+            {

+                res = pthread_cond_wait( &self->cond, &self->mtx.mtx );

+            }

+        }

+

+        PA_ENSURE( PaUnixMutex_Unlock( &self->mtx ) );

+

+        PA_UNLESS( !res || ETIMEDOUT == res, paInternalError );

+        PA_DEBUG(( "%s: Waited for %g seconds for stream to start\n", __FUNCTION__, PaUtil_GetTime() - now ));

+        if( ETIMEDOUT == res )

+        {

+            PA_ENSURE( paTimedOut );

+        }

+    }

+

+end:

+    return result;

+error:

+    if( started )

+    {

+        PaUnixThread_Terminate( self, 0, NULL );

+    }

+

+    goto end;

+}

+

+PaError PaUnixThread_Terminate( PaUnixThread* self, int wait, PaError* exitResult )

+{

+    PaError result = paNoError;

+    void* pret;

+

+    if( exitResult )

+    {

+        *exitResult = paNoError;

+    }

+#if 0

+    if( watchdogExitResult )

+        *watchdogExitResult = paNoError;

+

+    if( th->watchdogRunning )

+    {

+        pthread_cancel( th->watchdogThread );

+        PA_ENSURE_SYSTEM( pthread_join( th->watchdogThread, &pret ), 0 );

+

+        if( pret && pret != PTHREAD_CANCELED )

+        {

+            if( watchdogExitResult )

+                *watchdogExitResult = *(PaError *) pret;

+            free( pret );

+        }

+    }

+#endif

+

+    /* Only kill the thread if it isn't in the process of stopping (flushing adaptation buffers) */

+    /* TODO: Make join time out */

+    self->stopRequested = wait;

+    if( !wait )

+    {

+        PA_DEBUG(( "%s: Canceling thread %d\n", __FUNCTION__, self->thread ));

+        /* XXX: Safe to call this if the thread has exited on its own? */

+        pthread_cancel( self->thread );

+    }

+    PA_DEBUG(( "%s: Joining thread %d\n", __FUNCTION__, self->thread ));

+    PA_ENSURE_SYSTEM( pthread_join( self->thread, &pret ), 0 );

+

+    if( pret && PTHREAD_CANCELED != pret )

+    {

+        if( exitResult )

+        {

+            *exitResult = *(PaError*)pret;

+        }

+        free( pret );

+    }

+

+error:

+    PA_ASSERT_CALL( PaUnixMutex_Terminate( &self->mtx ), paNoError );

+    PA_ASSERT_CALL( pthread_cond_destroy( &self->cond ), 0 );

+

+    return result;

+}

+

+PaError PaUnixThread_PrepareNotify( PaUnixThread* self )

+{

+    PaError result = paNoError;

+    PA_UNLESS( self->parentWaiting, paInternalError );

+

+    PA_ENSURE( PaUnixMutex_Lock( &self->mtx ) );

+    self->locked = 1;

+

+error:

+    return result;

+}

+

+PaError PaUnixThread_NotifyParent( PaUnixThread* self )

+{

+    PaError result = paNoError;

+    PA_UNLESS( self->parentWaiting, paInternalError );

+

+    if( !self->locked )

+    {

+        PA_ENSURE( PaUnixMutex_Lock( &self->mtx ) );

+        self->locked = 1;

+    }

+    self->parentWaiting = 0;

+    pthread_cond_signal( &self->cond );

+    PA_ENSURE( PaUnixMutex_Unlock( &self->mtx ) );

+    self->locked = 0;

+

+error:

+    return result;

+}

+

+int PaUnixThread_StopRequested( PaUnixThread* self )

+{

+    return self->stopRequested;

+}

+

+PaError PaUnixMutex_Initialize( PaUnixMutex* self )

+{

+    PaError result = paNoError;

+    PA_ASSERT_CALL( pthread_mutex_init( &self->mtx, NULL ), 0 );

+    return result;

+}

+

+PaError PaUnixMutex_Terminate( PaUnixMutex* self )

+{

+    PaError result = paNoError;

+    PA_ASSERT_CALL( pthread_mutex_destroy( &self->mtx ), 0 );

+    return result;

+}

+

+/** Lock mutex.

+ *

+ * We're disabling thread cancellation while the thread is holding a lock, so mutexes are 

+ * properly unlocked at termination time.

+ */

+PaError PaUnixMutex_Lock( PaUnixMutex* self )

+{

+    PaError result = paNoError;

+    int oldState;

+    

+    PA_ENSURE_SYSTEM( pthread_setcancelstate( PTHREAD_CANCEL_DISABLE, &oldState ), 0 );

+    PA_ENSURE_SYSTEM( pthread_mutex_lock( &self->mtx ), 0 );

+

+error:

+    return result;

+}

+

+/** Unlock mutex.

+ *

+ * Thread cancellation is enabled again after the mutex is properly unlocked.

+ */

+PaError PaUnixMutex_Unlock( PaUnixMutex* self )

+{

+    PaError result = paNoError;

+    int oldState;

+

+    PA_ENSURE_SYSTEM( pthread_mutex_unlock( &self->mtx ), 0 );

+    PA_ENSURE_SYSTEM( pthread_setcancelstate( PTHREAD_CANCEL_ENABLE, &oldState ), 0 );

+

+error:

+    return result;

+}

+

+

+#if 0

+static void OnWatchdogExit( void *userData )

+{

+    PaAlsaThreading *th = (PaAlsaThreading *) userData;

+    struct sched_param spm = { 0 };

+    assert( th );

+

+    PA_ASSERT_CALL( pthread_setschedparam( th->callbackThread, SCHED_OTHER, &spm ), 0 );    /* Lower before exiting */

+    PA_DEBUG(( "Watchdog exiting\n" ));

+}

+

+static void *WatchdogFunc( void *userData )

+{

+    PaError result = paNoError, *pres = NULL;

+    int err;

+    PaAlsaThreading *th = (PaAlsaThreading *) userData;

+    unsigned intervalMsec = 500;

+    const PaTime maxSeconds = 3.;   /* Max seconds between callbacks */

+    PaTime timeThen = PaUtil_GetTime(), timeNow, timeElapsed, cpuTimeThen, cpuTimeNow, cpuTimeElapsed;

+    double cpuLoad, avgCpuLoad = 0.;

+    int throttled = 0;

+

+    assert( th );

+

+    /* Execute OnWatchdogExit when exiting */

+    pthread_cleanup_push( &OnWatchdogExit, th );

+

+    /* Boost priority of callback thread */

+    PA_ENSURE( result = BoostPriority( th ) );

+    if( !result )

+    {

+        /* Boost failed, might as well exit */

+        pthread_exit( NULL );

+    }

+

+    cpuTimeThen = th->callbackCpuTime;

+    {

+        int policy;

+        struct sched_param spm = { 0 };

+        pthread_getschedparam( pthread_self(), &policy, &spm );

+        PA_DEBUG(( "%s: Watchdog priority is %d\n", __FUNCTION__, spm.sched_priority ));

+    }

+

+    while( 1 )

+    {

+        double lowpassCoeff = 0.9, lowpassCoeff1 = 0.99999 - lowpassCoeff;

+        

+        /* Test before and after in case whatever underlying sleep call isn't interrupted by pthread_cancel */

+        pthread_testcancel();

+        Pa_Sleep( intervalMsec );

+        pthread_testcancel();

+

+        if( PaUtil_GetTime() - th->callbackTime > maxSeconds )

+        {

+            PA_DEBUG(( "Watchdog: Terminating callback thread\n" ));

+            /* Tell thread to terminate */

+            err = pthread_kill( th->callbackThread, SIGKILL );

+            pthread_exit( NULL );

+        }

+

+        PA_DEBUG(( "%s: PortAudio reports CPU load: %g\n", __FUNCTION__, PaUtil_GetCpuLoad( th->cpuLoadMeasurer ) ));

+

+        /* Check if we should throttle, or unthrottle :P */

+        cpuTimeNow = th->callbackCpuTime;

+        cpuTimeElapsed = cpuTimeNow - cpuTimeThen;

+        cpuTimeThen = cpuTimeNow;

+

+        timeNow = PaUtil_GetTime();

+        timeElapsed = timeNow - timeThen;

+        timeThen = timeNow;

+        cpuLoad = cpuTimeElapsed / timeElapsed;

+        avgCpuLoad = avgCpuLoad * lowpassCoeff + cpuLoad * lowpassCoeff1;

+        /*

+        if( throttled )

+            PA_DEBUG(( "Watchdog: CPU load: %g, %g\n", avgCpuLoad, cpuTimeElapsed ));

+            */

+        if( PaUtil_GetCpuLoad( th->cpuLoadMeasurer ) > .925 )

+        {

+            static int policy;

+            static struct sched_param spm = { 0 };

+            static const struct sched_param defaultSpm = { 0 };

+            PA_DEBUG(( "%s: Throttling audio thread, priority %d\n", __FUNCTION__, spm.sched_priority ));

+

+            pthread_getschedparam( th->callbackThread, &policy, &spm );

+            if( !pthread_setschedparam( th->callbackThread, SCHED_OTHER, &defaultSpm ) )

+            {

+                throttled = 1;

+            }

+            else

+                PA_DEBUG(( "Watchdog: Couldn't lower priority of audio thread: %s\n", strerror( errno ) ));

+

+            /* Give other processes a go, before raising priority again */

+            PA_DEBUG(( "%s: Watchdog sleeping for %lu msecs before unthrottling\n", __FUNCTION__, th->throttledSleepTime ));

+            Pa_Sleep( th->throttledSleepTime );

+

+            /* Reset callback priority */

+            if( pthread_setschedparam( th->callbackThread, SCHED_FIFO, &spm ) != 0 )

+            {

+                PA_DEBUG(( "%s: Couldn't raise priority of audio thread: %s\n", __FUNCTION__, strerror( errno ) ));

+            }

+

+            if( PaUtil_GetCpuLoad( th->cpuLoadMeasurer ) >= .99 )

+                intervalMsec = 50;

+            else

+                intervalMsec = 100;

+

+            /*

+            lowpassCoeff = .97;

+            lowpassCoeff1 = .99999 - lowpassCoeff;

+            */

+        }

+        else if( throttled && avgCpuLoad < .8 )

+        {

+            intervalMsec = 500;

+            throttled = 0;

+

+            /*

+            lowpassCoeff = .9;

+            lowpassCoeff1 = .99999 - lowpassCoeff;

+            */

+        }

+    }

+

+    pthread_cleanup_pop( 1 );   /* Execute cleanup on exit */

+

+error:

+    /* Shouldn't get here in the normal case */

+

+    /* Pass on error code */

+    pres = malloc( sizeof (PaError) );

+    *pres = result;

+    

+    pthread_exit( pres );

+}

+

+static void CallbackUpdate( PaAlsaThreading *th )

+{

+    th->callbackTime = PaUtil_GetTime();

+    th->callbackCpuTime = PaUtil_GetCpuLoad( th->cpuLoadMeasurer );

+}

+

+/*

+static void *CanaryFunc( void *userData )

+{

+    const unsigned intervalMsec = 1000;

+    PaUtilThreading *th = (PaUtilThreading *) userData;

+

+    while( 1 )

+    {

+        th->canaryTime = PaUtil_GetTime();

+

+        pthread_testcancel();

+        Pa_Sleep( intervalMsec );

+    }

+

+    pthread_exit( NULL );

+}

+*/

+#endif

diff --git a/src/engine/external/portaudio/pa_unix_util.h b/src/engine/external/portaudio/pa_unix_util.h
new file mode 100644
index 00000000..2642cc65
--- /dev/null
+++ b/src/engine/external/portaudio/pa_unix_util.h
@@ -0,0 +1,224 @@
+/*

+ * $Id: pa_unix_util.h 1241 2007-07-23 20:08:31Z aknudsen $

+ * Portable Audio I/O Library

+ * UNIX platform-specific support functions

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2000 Ross Bencina

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup unix_src

+*/

+

+#ifndef PA_UNIX_UTIL_H

+#define PA_UNIX_UTIL_H

+

+#include "pa_cpuload.h"

+#include <assert.h>

+#include <pthread.h>

+#include <signal.h>

+

+#ifdef __cplusplus

+extern "C"

+{

+#endif /* __cplusplus */

+

+#define PA_MIN(x,y) ( (x) < (y) ? (x) : (y) )

+#define PA_MAX(x,y) ( (x) > (y) ? (x) : (y) )

+

+/* Utilize GCC branch prediction for error tests */

+#if defined __GNUC__ && __GNUC__ >= 3

+#define UNLIKELY(expr) __builtin_expect( (expr), 0 )

+#else

+#define UNLIKELY(expr) (expr)

+#endif

+

+#define STRINGIZE_HELPER(expr) #expr

+#define STRINGIZE(expr) STRINGIZE_HELPER(expr)

+

+#define PA_UNLESS(expr, code) \

+    do { \

+        if( UNLIKELY( (expr) == 0 ) ) \

+        { \

+            PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \

+            result = (code); \

+            goto error; \

+        } \

+    } while (0);

+

+static PaError paUtilErr_;          /* Used with PA_ENSURE */

+

+/* Check PaError */

+#define PA_ENSURE(expr) \

+    do { \

+        if( UNLIKELY( (paUtilErr_ = (expr)) < paNoError ) ) \

+        { \

+            PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \

+            result = paUtilErr_; \

+            goto error; \

+        } \

+    } while (0);

+

+#define PA_ASSERT_CALL(expr, success) \

+    paUtilErr_ = (expr); \

+    assert( success == paUtilErr_ );

+

+#define PA_ENSURE_SYSTEM(expr, success) \

+    do { \

+        if( UNLIKELY( (paUtilErr_ = (expr)) != success ) ) \

+        { \

+            /* PaUtil_SetLastHostErrorInfo should only be used in the main thread */ \

+            if( pthread_equal(pthread_self(), paUnixMainThread) ) \

+            { \

+                PaUtil_SetLastHostErrorInfo( paALSA, paUtilErr_, strerror( paUtilErr_ ) ); \

+            } \

+            PaUtil_DebugPrint( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" ); \

+            result = paUnanticipatedHostError; \

+            goto error; \

+        } \

+    } while( 0 );

+

+typedef struct {

+    pthread_t callbackThread;

+} PaUtilThreading;

+

+PaError PaUtil_InitializeThreading( PaUtilThreading *threading );

+void PaUtil_TerminateThreading( PaUtilThreading *threading );

+PaError PaUtil_StartThreading( PaUtilThreading *threading, void *(*threadRoutine)(void *), void *data );

+PaError PaUtil_CancelThreading( PaUtilThreading *threading, int wait, PaError *exitResult );

+

+/* State accessed by utility functions */

+

+/*

+void PaUnix_SetRealtimeScheduling( int rt );

+

+void PaUtil_InitializeThreading( PaUtilThreading *th, PaUtilCpuLoadMeasurer *clm );

+

+PaError PaUtil_CreateCallbackThread( PaUtilThreading *th, void *(*CallbackThreadFunc)( void * ), PaStream *s );

+

+PaError PaUtil_KillCallbackThread( PaUtilThreading *th, PaError *exitResult );

+

+void PaUtil_CallbackUpdate( PaUtilThreading *th );

+*/

+

+extern pthread_t paUnixMainThread;

+

+typedef struct

+{

+    pthread_mutex_t mtx;

+} PaUnixMutex;

+

+PaError PaUnixMutex_Initialize( PaUnixMutex* self );

+PaError PaUnixMutex_Terminate( PaUnixMutex* self );

+PaError PaUnixMutex_Lock( PaUnixMutex* self );

+PaError PaUnixMutex_Unlock( PaUnixMutex* self );

+

+typedef struct

+{

+    pthread_t thread;

+    int parentWaiting;

+    int stopRequested;

+    int locked;

+    PaUnixMutex mtx;

+    pthread_cond_t cond;

+    volatile sig_atomic_t stopRequest;

+} PaUnixThread;

+

+/** Initialize global threading state.

+ */

+PaError PaUnixThreading_Initialize();

+

+/** Perish, passing on eventual error code.

+ *

+ * A thin wrapper around pthread_exit, will automatically pass on any error code to the joining thread.

+ * If the result indicates an error, i.e. it is not equal to paNoError, this function will automatically

+ * allocate a pointer so the error is passed on with pthread_exit. If the result indicates that all is

+ * well however, only a NULL pointer will be handed to pthread_exit. Thus, the joining thread should

+ * check whether a non-NULL result pointer is obtained from pthread_join and make sure to free it.

+ * @param result: The error code to pass on to the joining thread.

+ */

+#define PaUnixThreading_EXIT(result) \

+    do { \

+        PaError* pres = NULL; \

+        if( paNoError != (result) ) \

+        { \

+            pres = malloc( sizeof (PaError) ); \

+            *pres = (result); \

+        } \

+        pthread_exit( pres ); \

+    } while (0);

+

+/** Spawn a thread.

+ *

+ * Intended for spawning the callback thread from the main thread. This function can even block (for a certain

+ * time or indefinitely) untill notified by the callback thread (using PaUnixThread_NotifyParent), which can be

+ * useful in order to make sure that callback has commenced before returning from Pa_StartStream.

+ * @param threadFunc: The function to be executed in the child thread.

+ * @param waitForChild: If not 0, wait for child thread to call PaUnixThread_NotifyParent. Less than 0 means

+ * wait for ever, greater than 0 wait for the specified time.

+ * @param rtSched: Enable realtime scheduling?

+ * @return: If timed out waiting on child, paTimedOut.

+ */

+PaError PaUnixThread_New( PaUnixThread* self, void* (*threadFunc)( void* ), void* threadArg, PaTime waitForChild,

+        int rtSched );

+

+/** Terminate thread.

+ *

+ * @param wait: If true, request that background thread stop and wait untill it does, else cancel it.

+ * @param exitResult: If non-null this will upon return contain the exit status of the thread.

+ */

+PaError PaUnixThread_Terminate( PaUnixThread* self, int wait, PaError* exitResult );

+

+/** Prepare to notify waiting parent thread.

+ *

+ * An internal lock must be held before the parent is notified in PaUnixThread_NotifyParent, call this to

+ * acquire it beforehand.

+ * @return: If parent is not waiting, paInternalError.

+ */

+PaError PaUnixThread_PrepareNotify( PaUnixThread* self );

+

+/** Notify waiting parent thread.

+ *

+ * @return: If parent timed out waiting, paTimedOut. If parent was never waiting, paInternalError.

+ */

+PaError PaUnixThread_NotifyParent( PaUnixThread* self );

+

+/** Has the parent thread requested this thread to stop?

+ */

+int PaUnixThread_StopRequested( PaUnixThread* self );

+

+#ifdef __cplusplus

+}

+#endif /* __cplusplus */

+#endif

diff --git a/src/engine/external/portaudio/pa_util.h b/src/engine/external/portaudio/pa_util.h
new file mode 100644
index 00000000..da7f82f1
--- /dev/null
+++ b/src/engine/external/portaudio/pa_util.h
@@ -0,0 +1,159 @@
+#ifndef PA_UTIL_H

+#define PA_UTIL_H

+/*

+ * $Id: pa_util.h 1229 2007-06-15 16:11:11Z rossb $

+ * Portable Audio I/O Library implementation utilities header

+ * common implementation utilities and interfaces

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup common_src

+

+    @brief Prototypes for utility functions used by PortAudio implementations.

+

+    @todo Document and adhere to the alignment guarantees provided by

+    PaUtil_AllocateMemory().

+*/

+

+

+#include "portaudio.h"

+

+#ifdef __cplusplus

+extern "C"

+{

+#endif /* __cplusplus */

+

+

+struct PaUtilHostApiRepresentation;

+

+

+/** Retrieve a specific host API representation. This function can be used

+ by implementations to retrieve a pointer to their representation in

+ host api specific extension functions which aren't passed a rep pointer

+ by pa_front.c.

+

+ @param hostApi A pointer to a host API represenation pointer. Apon success

+ this will receive the requested representation pointer.

+

+ @param type A valid host API type identifier.

+

+ @returns An error code. If the result is PaNoError then a pointer to the

+ requested host API representation will be stored in *hostApi. If the host API

+ specified by type is not found, this function returns paHostApiNotFound.

+*/

+PaError PaUtil_GetHostApiRepresentation( struct PaUtilHostApiRepresentation **hostApi,

+        PaHostApiTypeId type );

+

+

+/** Convert a PortAudio device index into a host API specific device index.

+ @param hostApiDevice Pointer to a device index, on success this will recieve the

+ converted device index value.

+ @param device The PortAudio device index to convert.

+ @param hostApi The host api which the index should be converted for.

+

+ @returns On success returns PaNoError and places the converted index in the

+ hostApiDevice parameter.

+*/

+PaError PaUtil_DeviceIndexToHostApiDeviceIndex(

+        PaDeviceIndex *hostApiDevice, PaDeviceIndex device,

+        struct PaUtilHostApiRepresentation *hostApi );

+

+

+/** Set the host error information returned by Pa_GetLastHostErrorInfo. This

+ function and the paUnanticipatedHostError error code should be used as a

+ last resort.  Implementors should use existing PA error codes where possible,

+ or nominate new ones. Note that at it is always better to use

+ PaUtil_SetLastHostErrorInfo() and paUnanticipatedHostError than to return an

+ ambiguous or inaccurate PaError code.

+

+ @param hostApiType  The host API which encountered the error (ie of the caller)

+

+ @param errorCode The error code returned by the native API function.

+

+ @param errorText A string describing the error. PaUtil_SetLastHostErrorInfo

+ makes a copy of the string, so it is not necessary for the pointer to remain

+ valid after the call to PaUtil_SetLastHostErrorInfo() returns.

+

+*/

+void PaUtil_SetLastHostErrorInfo( PaHostApiTypeId hostApiType, long errorCode,

+        const char *errorText );

+

+

+        

+/* the following functions are implemented in a platform platform specific

+ .c file

+*/

+

+/** Allocate size bytes, guaranteed to be aligned to a FIXME byte boundary */

+void *PaUtil_AllocateMemory( long size );

+

+

+/** Realease block if non-NULL. block may be NULL */

+void PaUtil_FreeMemory( void *block );

+

+

+/** Return the number of currently allocated blocks. This function can be

+ used for detecting memory leaks.

+

+ @note Allocations will only be tracked if PA_TRACK_MEMORY is #defined. If

+ it isn't, this function will always return 0.

+*/

+int PaUtil_CountCurrentlyAllocatedBlocks( void );

+

+

+/** Initialize the clock used by PaUtil_GetTime(). Call this before calling

+ PaUtil_GetTime.

+

+ @see PaUtil_GetTime

+*/

+void PaUtil_InitializeClock( void );

+

+

+/** Return the system time in seconds. Used to implement CPU load functions

+

+ @see PaUtil_InitializeClock

+*/

+double PaUtil_GetTime( void );

+

+

+/* void Pa_Sleep( long msec );  must also be implemented in per-platform .c file */

+

+

+

+#ifdef __cplusplus

+}

+#endif /* __cplusplus */

+#endif /* PA_UTIL_H */

diff --git a/src/engine/external/portaudio/pa_win_ds.c b/src/engine/external/portaudio/pa_win_ds.c
new file mode 100644
index 00000000..09b29577
--- /dev/null
+++ b/src/engine/external/portaudio/pa_win_ds.c
@@ -0,0 +1,2197 @@
+/*

+ * $Id: pa_win_ds.c 1229 2007-06-15 16:11:11Z rossb $

+ * Portable Audio I/O Library DirectSound implementation

+ *

+ * Authors: Phil Burk, Robert Marsanyi & Ross Bencina

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2006 Ross Bencina, Phil Burk, Robert Marsanyi

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup hostaip_src

+

+    @todo implement paInputOverflow callback status flag

+    

+    @todo implement paNeverDropInput.

+

+    @todo implement host api specific extension to set i/o buffer sizes in frames

+

+    @todo implement initialisation of PaDeviceInfo default*Latency fields (currently set to 0.)

+

+    @todo implement ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable

+

+    @todo audit handling of DirectSound result codes - in many cases we could convert a HRESULT into

+        a native portaudio error code. Standard DirectSound result codes are documented at msdn.

+

+    @todo implement IsFormatSupported

+

+    @todo check that CoInitialize() CoUninitialize() are always correctly

+        paired, even in error cases.

+

+    @todo call PaUtil_SetLastHostErrorInfo with a specific error string (currently just "DSound error").

+

+    @todo make sure all buffers have been played before stopping the stream

+        when the stream callback returns paComplete

+

+    old TODOs from phil, need to work out if these have been done:

+        O- fix "patest_stop.c"

+*/

+

+#include <stdio.h>

+#include <string.h> /* strlen() */

+

+#include "pa_util.h"

+#include "pa_allocation.h"

+#include "pa_hostapi.h"

+#include "pa_stream.h"

+#include "pa_cpuload.h"

+#include "pa_process.h"

+#include "pa_debugprint.h"

+

+#include "pa_win_ds_dynlink.h"

+

+#if (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */

+#pragma comment( lib, "dsound.lib" )

+#pragma comment( lib, "winmm.lib" )

+#endif

+

+/*

+ provided in newer platform sdks and x64

+ */

+#ifndef DWORD_PTR

+#define DWORD_PTR DWORD

+#endif

+

+#define PRINT(x) PA_DEBUG(x);

+#define ERR_RPT(x) PRINT(x)

+#define DBUG(x)   PRINT(x)

+#define DBUGX(x)  PRINT(x)

+

+#define PA_USE_HIGH_LATENCY   (0)

+#if PA_USE_HIGH_LATENCY

+#define PA_WIN_9X_LATENCY     (500)

+#define PA_WIN_NT_LATENCY     (600)

+#else

+#define PA_WIN_9X_LATENCY     (140)

+#define PA_WIN_NT_LATENCY     (280)

+#endif

+

+#define PA_WIN_WDM_LATENCY       (120)

+

+#define SECONDS_PER_MSEC      (0.001)

+#define MSEC_PER_SECOND       (1000)

+

+/* prototypes for functions declared in this file */

+

+#ifdef __cplusplus

+extern "C"

+{

+#endif /* __cplusplus */

+

+PaError PaWinDs_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );

+

+#ifdef __cplusplus

+}

+#endif /* __cplusplus */

+

+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );

+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,

+                           PaStream** s,

+                           const PaStreamParameters *inputParameters,

+                           const PaStreamParameters *outputParameters,

+                           double sampleRate,

+                           unsigned long framesPerBuffer,

+                           PaStreamFlags streamFlags,

+                           PaStreamCallback *streamCallback,

+                           void *userData );

+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,

+                                  const PaStreamParameters *inputParameters,

+                                  const PaStreamParameters *outputParameters,

+                                  double sampleRate );

+static PaError CloseStream( PaStream* stream );

+static PaError StartStream( PaStream *stream );

+static PaError StopStream( PaStream *stream );

+static PaError AbortStream( PaStream *stream );

+static PaError IsStreamStopped( PaStream *s );

+static PaError IsStreamActive( PaStream *stream );

+static PaTime GetStreamTime( PaStream *stream );

+static double GetStreamCpuLoad( PaStream* stream );

+static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );

+static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );

+static signed long GetStreamReadAvailable( PaStream* stream );

+static signed long GetStreamWriteAvailable( PaStream* stream );

+

+

+/* FIXME: should convert hr to a string */

+#define PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr ) \

+    PaUtil_SetLastHostErrorInfo( paDirectSound, hr, "DirectSound error" )

+

+/************************************************* DX Prototypes **********/

+static BOOL CALLBACK CollectGUIDsProc(LPGUID lpGUID,

+                                     LPCTSTR lpszDesc,

+                                     LPCTSTR lpszDrvName,

+                                     LPVOID lpContext );

+

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

+/********************** Structures **************************************************/

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

+/* PaWinDsHostApiRepresentation - host api datastructure specific to this implementation */

+

+typedef struct PaWinDsDeviceInfo

+{

+    GUID                             guid;

+    GUID                            *lpGUID;

+    double                           sampleRates[3];

+} PaWinDsDeviceInfo;

+

+typedef struct

+{

+    PaUtilHostApiRepresentation inheritedHostApiRep;

+    PaUtilStreamInterface    callbackStreamInterface;

+    PaUtilStreamInterface    blockingStreamInterface;

+

+    PaUtilAllocationGroup   *allocations;

+

+    /* implementation specific data goes here */

+    PaWinDsDeviceInfo       *winDsDeviceInfos;

+

+} PaWinDsHostApiRepresentation;

+

+

+/* PaWinDsStream - a stream data structure specifically for this implementation */

+

+typedef struct PaWinDsStream

+{

+    PaUtilStreamRepresentation streamRepresentation;

+    PaUtilCpuLoadMeasurer cpuLoadMeasurer;

+    PaUtilBufferProcessor bufferProcessor;

+

+/* DirectSound specific data. */

+

+/* Output */

+    LPDIRECTSOUND        pDirectSound;

+    LPDIRECTSOUNDBUFFER  pDirectSoundOutputBuffer;

+    DWORD                outputBufferWriteOffsetBytes;     /* last write position */

+    INT                  outputBufferSizeBytes;

+    INT                  bytesPerOutputFrame;

+    /* Try to detect play buffer underflows. */

+    LARGE_INTEGER        perfCounterTicksPerBuffer; /* counter ticks it should take to play a full buffer */

+    LARGE_INTEGER        previousPlayTime;

+    UINT                 previousPlayCursor;

+    UINT                 outputUnderflowCount;

+    BOOL                 outputIsRunning;

+    /* use double which lets us can play for several thousand years with enough precision */

+    double               dsw_framesWritten;

+    double               framesPlayed;

+/* Input */

+    LPDIRECTSOUNDCAPTURE pDirectSoundCapture;

+    LPDIRECTSOUNDCAPTUREBUFFER   pDirectSoundInputBuffer;

+    INT                  bytesPerInputFrame;

+    UINT                 readOffset;      /* last read position */

+    UINT                 inputSize;

+

+    

+    MMRESULT         timerID;

+    int              framesPerDSBuffer;

+    double           framesWritten;

+    double           secondsPerHostByte; /* Used to optimize latency calculation for outTime */

+

+    PaStreamCallbackFlags callbackFlags;

+    

+/* FIXME - move all below to PaUtilStreamRepresentation */

+    volatile int     isStarted;

+    volatile int     isActive;

+    volatile int     stopProcessing; /* stop thread once existing buffers have been returned */

+    volatile int     abortProcessing; /* stop thread immediately */

+} PaWinDsStream;

+

+

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

+** Duplicate the input string using the allocations allocator.

+** A NULL string is converted to a zero length string.

+** If memory cannot be allocated, NULL is returned.

+**/

+static char *DuplicateDeviceNameString( PaUtilAllocationGroup *allocations, const char* src )

+{

+    char *result = 0;

+    

+    if( src != NULL )

+    {

+        size_t len = strlen(src);

+        result = (char*)PaUtil_GroupAllocateMemory( allocations, (long)(len + 1) );

+        if( result )

+            memcpy( (void *) result, src, len+1 );

+    }

+    else

+    {

+        result = (char*)PaUtil_GroupAllocateMemory( allocations, 1 );

+        if( result )

+            result[0] = '\0';

+    }

+

+    return result;

+}

+

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

+** DSDeviceNameAndGUID, DSDeviceNameAndGUIDVector used for collecting preliminary

+** information during device enumeration.

+*/

+typedef struct DSDeviceNameAndGUID{

+    char *name; // allocated from parent's allocations, never deleted by this structure

+    GUID guid;

+    LPGUID lpGUID;

+} DSDeviceNameAndGUID;

+

+typedef struct DSDeviceNameAndGUIDVector{

+    PaUtilAllocationGroup *allocations;

+    PaError enumerationError;

+

+    int count;

+    int free;

+    DSDeviceNameAndGUID *items; // Allocated using LocalAlloc()

+} DSDeviceNameAndGUIDVector;

+

+static PaError InitializeDSDeviceNameAndGUIDVector(

+        DSDeviceNameAndGUIDVector *guidVector, PaUtilAllocationGroup *allocations )

+{

+    PaError result = paNoError;

+

+    guidVector->allocations = allocations;

+    guidVector->enumerationError = paNoError;

+

+    guidVector->count = 0;

+    guidVector->free = 8;

+    guidVector->items = (DSDeviceNameAndGUID*)LocalAlloc( LMEM_FIXED, sizeof(DSDeviceNameAndGUID) * guidVector->free );

+    if( guidVector->items == NULL )

+        result = paInsufficientMemory;

+    

+    return result;

+}

+

+static PaError ExpandDSDeviceNameAndGUIDVector( DSDeviceNameAndGUIDVector *guidVector )

+{

+    PaError result = paNoError;

+    DSDeviceNameAndGUID *newItems;

+    int i;

+    

+    /* double size of vector */

+    int size = guidVector->count + guidVector->free;

+    guidVector->free += size;

+

+    newItems = (DSDeviceNameAndGUID*)LocalAlloc( LMEM_FIXED, sizeof(DSDeviceNameAndGUID) * size * 2 );

+    if( newItems == NULL )

+    {

+        result = paInsufficientMemory;

+    }

+    else

+    {

+        for( i=0; i < guidVector->count; ++i )

+        {

+            newItems[i].name = guidVector->items[i].name;

+            if( guidVector->items[i].lpGUID == NULL )

+            {

+                newItems[i].lpGUID = NULL;

+            }

+            else

+            {

+                newItems[i].lpGUID = &newItems[i].guid;

+                memcpy( &newItems[i].guid, guidVector->items[i].lpGUID, sizeof(GUID) );;

+            }

+        }

+

+        LocalFree( guidVector->items );

+        guidVector->items = newItems;

+    }                                

+

+    return result;

+}

+

+/*

+    it's safe to call DSDeviceNameAndGUIDVector multiple times

+*/

+static PaError TerminateDSDeviceNameAndGUIDVector( DSDeviceNameAndGUIDVector *guidVector )

+{

+    PaError result = paNoError;

+

+    if( guidVector->items != NULL )

+    {

+        if( LocalFree( guidVector->items ) != NULL )

+            result = paInsufficientMemory;              /** @todo this isn't the correct error to return from a deallocation failure */

+

+        guidVector->items = NULL;

+    }

+

+    return result;

+}

+

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

+** Collect preliminary device information during DirectSound enumeration 

+*/

+static BOOL CALLBACK CollectGUIDsProc(LPGUID lpGUID,

+                                     LPCTSTR lpszDesc,

+                                     LPCTSTR lpszDrvName,

+                                     LPVOID lpContext )

+{

+    DSDeviceNameAndGUIDVector *namesAndGUIDs = (DSDeviceNameAndGUIDVector*)lpContext;

+    PaError error;

+

+    (void) lpszDrvName; /* unused variable */

+

+    if( namesAndGUIDs->free == 0 )

+    {

+        error = ExpandDSDeviceNameAndGUIDVector( namesAndGUIDs );

+        if( error != paNoError )

+        {

+            namesAndGUIDs->enumerationError = error;

+            return FALSE;

+        }

+    }

+    

+    /* Set GUID pointer, copy GUID to storage in DSDeviceNameAndGUIDVector. */

+    if( lpGUID == NULL )

+    {

+        namesAndGUIDs->items[namesAndGUIDs->count].lpGUID = NULL;

+    }

+    else

+    {

+        namesAndGUIDs->items[namesAndGUIDs->count].lpGUID =

+                &namesAndGUIDs->items[namesAndGUIDs->count].guid;

+      

+        memcpy( &namesAndGUIDs->items[namesAndGUIDs->count].guid, lpGUID, sizeof(GUID) );

+    }

+

+    namesAndGUIDs->items[namesAndGUIDs->count].name =

+            DuplicateDeviceNameString( namesAndGUIDs->allocations, lpszDesc );

+    if( namesAndGUIDs->items[namesAndGUIDs->count].name == NULL )

+    {

+        namesAndGUIDs->enumerationError = paInsufficientMemory;

+        return FALSE;

+    }

+

+    ++namesAndGUIDs->count;

+    --namesAndGUIDs->free;

+    

+    return TRUE;

+}

+

+

+/* 

+    GUIDs for emulated devices which we blacklist below.

+    are there more than two of them??

+*/

+

+GUID IID_IRolandVSCEmulated1 = {0xc2ad1800, 0xb243, 0x11ce, 0xa8, 0xa4, 0x00, 0xaa, 0x00, 0x6c, 0x45, 0x01};

+GUID IID_IRolandVSCEmulated2 = {0xc2ad1800, 0xb243, 0x11ce, 0xa8, 0xa4, 0x00, 0xaa, 0x00, 0x6c, 0x45, 0x02};

+

+

+#define PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_  (13) /* must match array length below */

+static double defaultSampleRateSearchOrder_[] =

+    { 44100.0, 48000.0, 32000.0, 24000.0, 22050.0, 88200.0, 96000.0, 192000.0,

+        16000.0, 12000.0, 11025.0, 9600.0, 8000.0 };

+

+

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

+** Extract capabilities from an output device, and add it to the device info list

+** if successful. This function assumes that there is enough room in the

+** device info list to accomodate all entries.

+**

+** The device will not be added to the device list if any errors are encountered.

+*/

+static PaError AddOutputDeviceInfoFromDirectSound(

+        PaWinDsHostApiRepresentation *winDsHostApi, char *name, LPGUID lpGUID )

+{

+    PaUtilHostApiRepresentation  *hostApi = &winDsHostApi->inheritedHostApiRep;

+    PaDeviceInfo                 *deviceInfo = hostApi->deviceInfos[hostApi->info.deviceCount];

+    PaWinDsDeviceInfo            *winDsDeviceInfo = &winDsHostApi->winDsDeviceInfos[hostApi->info.deviceCount];

+    HRESULT                       hr;

+    LPDIRECTSOUND                 lpDirectSound;

+    DSCAPS                        caps;

+    int                           deviceOK = TRUE;

+    PaError                       result = paNoError;

+    int                           i;

+    

+    /* Copy GUID to the device info structure. Set pointer. */

+    if( lpGUID == NULL )

+    {

+        winDsDeviceInfo->lpGUID = NULL;

+    }

+    else

+    {

+        memcpy( &winDsDeviceInfo->guid, lpGUID, sizeof(GUID) );

+        winDsDeviceInfo->lpGUID = &winDsDeviceInfo->guid;

+    }

+

+    

+    if( lpGUID )

+    {

+        if (IsEqualGUID (&IID_IRolandVSCEmulated1,lpGUID) ||

+            IsEqualGUID (&IID_IRolandVSCEmulated2,lpGUID) )

+        {

+            PA_DEBUG(("BLACKLISTED: %s \n",name));

+            return paNoError;

+        }

+    }

+

+    /* Create a DirectSound object for the specified GUID

+        Note that using CoCreateInstance doesn't work on windows CE.

+    */

+    hr = paWinDsDSoundEntryPoints.DirectSoundCreate( lpGUID, &lpDirectSound, NULL );

+

+    /** try using CoCreateInstance because DirectSoundCreate was hanging under

+        some circumstances - note this was probably related to the

+        #define BOOL short bug which has now been fixed

+        @todo delete this comment and the following code once we've ensured

+        there is no bug.

+    */

+    /*

+    hr = CoCreateInstance( &CLSID_DirectSound, NULL, CLSCTX_INPROC_SERVER,

+            &IID_IDirectSound, (void**)&lpDirectSound );

+

+    if( hr == S_OK )

+    {

+        hr = IDirectSound_Initialize( lpDirectSound, lpGUID );

+    }

+    */

+    

+    if( hr != DS_OK )

+    {

+        if (hr == DSERR_ALLOCATED)

+            PA_DEBUG(("AddOutputDeviceInfoFromDirectSound %s DSERR_ALLOCATED\n",name));

+        DBUG(("Cannot create DirectSound for %s. Result = 0x%x\n", name, hr ));

+        if (lpGUID)

+            DBUG(("%s's GUID: {0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x,0x%x, 0x%x} \n",

+                 name,

+                 lpGUID->Data1,

+                 lpGUID->Data2,

+                 lpGUID->Data3,

+                 lpGUID->Data4[0],

+                 lpGUID->Data4[1],

+                 lpGUID->Data4[2],

+                 lpGUID->Data4[3],

+                 lpGUID->Data4[4],

+                 lpGUID->Data4[5],

+                 lpGUID->Data4[6],

+                 lpGUID->Data4[7]));

+

+        deviceOK = FALSE;

+    }

+    else

+    {

+        /* Query device characteristics. */

+        memset( &caps, 0, sizeof(caps) ); 

+        caps.dwSize = sizeof(caps);

+        hr = IDirectSound_GetCaps( lpDirectSound, &caps );

+        if( hr != DS_OK )

+        {

+            DBUG(("Cannot GetCaps() for DirectSound device %s. Result = 0x%x\n", name, hr ));

+            deviceOK = FALSE;

+        }

+        else

+        {

+

+#ifndef PA_NO_WMME

+            if( caps.dwFlags & DSCAPS_EMULDRIVER )

+            {

+                /* If WMME supported, then reject Emulated drivers because they are lousy. */

+                deviceOK = FALSE;

+            }

+#endif

+

+            if( deviceOK )

+            {

+                deviceInfo->maxInputChannels = 0;

+                /* Mono or stereo device? */

+                deviceInfo->maxOutputChannels = ( caps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1;

+

+                deviceInfo->defaultLowInputLatency = 0.;    /** @todo IMPLEMENT ME */

+                deviceInfo->defaultLowOutputLatency = 0.;   /** @todo IMPLEMENT ME */

+                deviceInfo->defaultHighInputLatency = 0.;   /** @todo IMPLEMENT ME */

+                deviceInfo->defaultHighOutputLatency = 0.;  /** @todo IMPLEMENT ME */

+                

+                /* initialize defaultSampleRate */

+                

+                if( caps.dwFlags & DSCAPS_CONTINUOUSRATE )

+                {

+                    /* initialize to caps.dwMaxSecondarySampleRate incase none of the standard rates match */

+                    deviceInfo->defaultSampleRate = caps.dwMaxSecondarySampleRate;

+

+                    for( i = 0; i < PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_; ++i )

+                    {

+                        if( defaultSampleRateSearchOrder_[i] >= caps.dwMinSecondarySampleRate

+                                && defaultSampleRateSearchOrder_[i] <= caps.dwMaxSecondarySampleRate ){

+

+                            deviceInfo->defaultSampleRate = defaultSampleRateSearchOrder_[i];

+                            break;

+                        }

+                    }

+                }

+                else if( caps.dwMinSecondarySampleRate == caps.dwMaxSecondarySampleRate )

+                {

+                    if( caps.dwMinSecondarySampleRate == 0 )

+                    {

+                        /*

+                        ** On my Thinkpad 380Z, DirectSoundV6 returns min-max=0 !!

+                        ** But it supports continuous sampling.

+                        ** So fake range of rates, and hope it really supports it.

+                        */

+                        deviceInfo->defaultSampleRate = 44100.0f;

+

+                        DBUG(("PA - Reported rates both zero. Setting to fake values for device #%s\n", name ));

+                    }

+                    else

+                    {

+	                    deviceInfo->defaultSampleRate = caps.dwMaxSecondarySampleRate;

+                    }

+                }

+                else if( (caps.dwMinSecondarySampleRate < 1000.0) && (caps.dwMaxSecondarySampleRate > 50000.0) )

+                {

+                    /* The EWS88MT drivers lie, lie, lie. The say they only support two rates, 100 & 100000.

+                    ** But we know that they really support a range of rates!

+                    ** So when we see a ridiculous set of rates, assume it is a range.

+                    */

+                  deviceInfo->defaultSampleRate = 44100.0f;

+                  DBUG(("PA - Sample rate range used instead of two odd values for device #%s\n", name ));

+                }

+                else deviceInfo->defaultSampleRate = caps.dwMaxSecondarySampleRate;

+

+

+                //printf( "min %d max %d\n", caps.dwMinSecondarySampleRate, caps.dwMaxSecondarySampleRate );

+                // dwFlags | DSCAPS_CONTINUOUSRATE 

+            }

+        }

+

+        IDirectSound_Release( lpDirectSound );

+    }

+

+    if( deviceOK )

+    {

+        deviceInfo->name = name;

+

+        if( lpGUID == NULL )

+            hostApi->info.defaultOutputDevice = hostApi->info.deviceCount;

+            

+        hostApi->info.deviceCount++;

+    }

+

+    return result;

+}

+

+

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

+** Extract capabilities from an input device, and add it to the device info list

+** if successful. This function assumes that there is enough room in the

+** device info list to accomodate all entries.

+**

+** The device will not be added to the device list if any errors are encountered.

+*/

+static PaError AddInputDeviceInfoFromDirectSoundCapture(

+        PaWinDsHostApiRepresentation *winDsHostApi, char *name, LPGUID lpGUID )

+{

+    PaUtilHostApiRepresentation  *hostApi = &winDsHostApi->inheritedHostApiRep;

+    PaDeviceInfo                 *deviceInfo = hostApi->deviceInfos[hostApi->info.deviceCount];

+    PaWinDsDeviceInfo            *winDsDeviceInfo = &winDsHostApi->winDsDeviceInfos[hostApi->info.deviceCount];

+    HRESULT                       hr;

+    LPDIRECTSOUNDCAPTURE          lpDirectSoundCapture;

+    DSCCAPS                       caps;

+    int                           deviceOK = TRUE;

+    PaError                       result = paNoError;

+    

+    /* Copy GUID to the device info structure. Set pointer. */

+    if( lpGUID == NULL )

+    {

+        winDsDeviceInfo->lpGUID = NULL;

+    }

+    else

+    {

+        winDsDeviceInfo->lpGUID = &winDsDeviceInfo->guid;

+        memcpy( &winDsDeviceInfo->guid, lpGUID, sizeof(GUID) );

+    }

+

+

+    hr = paWinDsDSoundEntryPoints.DirectSoundCaptureCreate( lpGUID, &lpDirectSoundCapture, NULL );

+

+    /** try using CoCreateInstance because DirectSoundCreate was hanging under

+        some circumstances - note this was probably related to the

+        #define BOOL short bug which has now been fixed

+        @todo delete this comment and the following code once we've ensured

+        there is no bug.

+    */

+    /*

+    hr = CoCreateInstance( &CLSID_DirectSoundCapture, NULL, CLSCTX_INPROC_SERVER,

+            &IID_IDirectSoundCapture, (void**)&lpDirectSoundCapture );

+    */

+    if( hr != DS_OK )

+    {

+        DBUG(("Cannot create Capture for %s. Result = 0x%x\n", name, hr ));

+        deviceOK = FALSE;

+    }

+    else

+    {

+        /* Query device characteristics. */

+        memset( &caps, 0, sizeof(caps) );

+        caps.dwSize = sizeof(caps);

+        hr = IDirectSoundCapture_GetCaps( lpDirectSoundCapture, &caps );

+        if( hr != DS_OK )

+        {

+            DBUG(("Cannot GetCaps() for Capture device %s. Result = 0x%x\n", name, hr ));

+            deviceOK = FALSE;

+        }

+        else

+        {

+#ifndef PA_NO_WMME

+            if( caps.dwFlags & DSCAPS_EMULDRIVER )

+            {

+                /* If WMME supported, then reject Emulated drivers because they are lousy. */

+                deviceOK = FALSE;

+            }

+#endif

+

+            if( deviceOK )

+            {

+                deviceInfo->maxInputChannels = caps.dwChannels;

+                deviceInfo->maxOutputChannels = 0;

+

+                deviceInfo->defaultLowInputLatency = 0.;    /** @todo IMPLEMENT ME */

+                deviceInfo->defaultLowOutputLatency = 0.;   /** @todo IMPLEMENT ME */

+                deviceInfo->defaultHighInputLatency = 0.;   /** @todo IMPLEMENT ME */

+                deviceInfo->defaultHighOutputLatency = 0.;  /** @todo IMPLEMENT ME */

+

+/*  constants from a WINE patch by Francois Gouget, see:

+    http://www.winehq.com/hypermail/wine-patches/2003/01/0290.html

+

+    ---

+    Date: Fri, 14 May 2004 10:38:12 +0200 (CEST)

+    From: Francois Gouget <fgouget@ ... .fr>

+    To: Ross Bencina <rbencina@ ... .au>

+    Subject: Re: Permission to use wine 48/96 wave patch in BSD licensed library

+

+    [snip]

+

+    I give you permission to use the patch below under the BSD license.

+    http://www.winehq.com/hypermail/wine-patches/2003/01/0290.html

+

+    [snip]

+*/

+#ifndef WAVE_FORMAT_48M08

+#define WAVE_FORMAT_48M08      0x00001000    /* 48     kHz, Mono,   8-bit  */

+#define WAVE_FORMAT_48S08      0x00002000    /* 48     kHz, Stereo, 8-bit  */

+#define WAVE_FORMAT_48M16      0x00004000    /* 48     kHz, Mono,   16-bit */

+#define WAVE_FORMAT_48S16      0x00008000    /* 48     kHz, Stereo, 16-bit */

+#define WAVE_FORMAT_96M08      0x00010000    /* 96     kHz, Mono,   8-bit  */

+#define WAVE_FORMAT_96S08      0x00020000    /* 96     kHz, Stereo, 8-bit  */

+#define WAVE_FORMAT_96M16      0x00040000    /* 96     kHz, Mono,   16-bit */

+#define WAVE_FORMAT_96S16      0x00080000    /* 96     kHz, Stereo, 16-bit */

+#endif

+

+                /* defaultSampleRate */

+                if( caps.dwChannels == 2 )

+                {

+                    if( caps.dwFormats & WAVE_FORMAT_4S16 )

+                        deviceInfo->defaultSampleRate = 44100.0;

+                    else if( caps.dwFormats & WAVE_FORMAT_48S16 )

+                        deviceInfo->defaultSampleRate = 48000.0;

+                    else if( caps.dwFormats & WAVE_FORMAT_2S16 )

+                        deviceInfo->defaultSampleRate = 22050.0;

+                    else if( caps.dwFormats & WAVE_FORMAT_1S16 )

+                        deviceInfo->defaultSampleRate = 11025.0;

+                    else if( caps.dwFormats & WAVE_FORMAT_96S16 )

+                        deviceInfo->defaultSampleRate = 96000.0;

+                    else

+                        deviceInfo->defaultSampleRate = 0.;

+                }

+                else if( caps.dwChannels == 1 )

+                {

+                    if( caps.dwFormats & WAVE_FORMAT_4M16 )

+                        deviceInfo->defaultSampleRate = 44100.0;

+                    else if( caps.dwFormats & WAVE_FORMAT_48M16 )

+                        deviceInfo->defaultSampleRate = 48000.0;

+                    else if( caps.dwFormats & WAVE_FORMAT_2M16 )

+                        deviceInfo->defaultSampleRate = 22050.0;

+                    else if( caps.dwFormats & WAVE_FORMAT_1M16 )

+                        deviceInfo->defaultSampleRate = 11025.0;

+                    else if( caps.dwFormats & WAVE_FORMAT_96M16 )

+                        deviceInfo->defaultSampleRate = 96000.0;

+                    else

+                        deviceInfo->defaultSampleRate = 0.;

+                }

+                else deviceInfo->defaultSampleRate = 0.;

+            }

+        }

+        

+        IDirectSoundCapture_Release( lpDirectSoundCapture );

+    }

+

+    if( deviceOK )

+    {

+        deviceInfo->name = name;

+

+        if( lpGUID == NULL )

+            hostApi->info.defaultInputDevice = hostApi->info.deviceCount;

+

+        hostApi->info.deviceCount++;

+    }

+

+    return result;

+}

+

+

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

+PaError PaWinDs_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )

+{

+    PaError result = paNoError;

+    int i, deviceCount;

+    PaWinDsHostApiRepresentation *winDsHostApi;

+    DSDeviceNameAndGUIDVector inputNamesAndGUIDs, outputNamesAndGUIDs;

+    PaDeviceInfo *deviceInfoArray;

+

+    HRESULT hr = CoInitialize(NULL);        /** @todo: should uninitialize too */

+    if( FAILED(hr) ){

+        return paUnanticipatedHostError;

+    }            

+

+    /* initialise guid vectors so they can be safely deleted on error */

+    inputNamesAndGUIDs.items = NULL;

+    outputNamesAndGUIDs.items = NULL;

+

+    PaWinDs_InitializeDSoundEntryPoints();

+

+    winDsHostApi = (PaWinDsHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaWinDsHostApiRepresentation) );

+    if( !winDsHostApi )

+    {

+        result = paInsufficientMemory;

+        goto error;

+    }

+

+    winDsHostApi->allocations = PaUtil_CreateAllocationGroup();

+    if( !winDsHostApi->allocations )

+    {

+        result = paInsufficientMemory;

+        goto error;

+    }

+

+    *hostApi = &winDsHostApi->inheritedHostApiRep;

+    (*hostApi)->info.structVersion = 1;

+    (*hostApi)->info.type = paDirectSound;

+    (*hostApi)->info.name = "Windows DirectSound";

+    

+    (*hostApi)->info.deviceCount = 0;

+    (*hostApi)->info.defaultInputDevice = paNoDevice;

+    (*hostApi)->info.defaultOutputDevice = paNoDevice;

+

+    

+/* DSound - enumerate devices to count them and to gather their GUIDs */

+

+

+    result = InitializeDSDeviceNameAndGUIDVector( &inputNamesAndGUIDs, winDsHostApi->allocations );

+    if( result != paNoError )

+        goto error;

+

+    result = InitializeDSDeviceNameAndGUIDVector( &outputNamesAndGUIDs, winDsHostApi->allocations );

+    if( result != paNoError )

+        goto error;

+

+    paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK)CollectGUIDsProc, (void *)&inputNamesAndGUIDs );

+

+    paWinDsDSoundEntryPoints.DirectSoundEnumerate( (LPDSENUMCALLBACK)CollectGUIDsProc, (void *)&outputNamesAndGUIDs );

+

+    if( inputNamesAndGUIDs.enumerationError != paNoError )

+    {

+        result = inputNamesAndGUIDs.enumerationError;

+        goto error;

+    }

+

+    if( outputNamesAndGUIDs.enumerationError != paNoError )

+    {

+        result = outputNamesAndGUIDs.enumerationError;

+        goto error;

+    }

+

+    deviceCount = inputNamesAndGUIDs.count + outputNamesAndGUIDs.count;

+

+    if( deviceCount > 0 )

+    {

+        /* allocate array for pointers to PaDeviceInfo structs */

+        (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(

+                winDsHostApi->allocations, sizeof(PaDeviceInfo*) * deviceCount );

+        if( !(*hostApi)->deviceInfos )

+        {

+            result = paInsufficientMemory;

+            goto error;

+        }

+

+        /* allocate all PaDeviceInfo structs in a contiguous block */

+        deviceInfoArray = (PaDeviceInfo*)PaUtil_GroupAllocateMemory(

+                winDsHostApi->allocations, sizeof(PaDeviceInfo) * deviceCount );

+        if( !deviceInfoArray )

+        {

+            result = paInsufficientMemory;

+            goto error;

+        }

+

+        /* allocate all DSound specific info structs in a contiguous block */

+        winDsHostApi->winDsDeviceInfos = (PaWinDsDeviceInfo*)PaUtil_GroupAllocateMemory(

+                winDsHostApi->allocations, sizeof(PaWinDsDeviceInfo) * deviceCount );

+        if( !winDsHostApi->winDsDeviceInfos )

+        {

+            result = paInsufficientMemory;

+            goto error;

+        }

+

+        for( i=0; i < deviceCount; ++i )

+        {

+            PaDeviceInfo *deviceInfo = &deviceInfoArray[i];

+            deviceInfo->structVersion = 2;

+            deviceInfo->hostApi = hostApiIndex;

+            deviceInfo->name = 0;

+            (*hostApi)->deviceInfos[i] = deviceInfo;

+        }

+

+        for( i=0; i< inputNamesAndGUIDs.count; ++i )

+        {

+            result = AddInputDeviceInfoFromDirectSoundCapture( winDsHostApi,

+                    inputNamesAndGUIDs.items[i].name,

+                    inputNamesAndGUIDs.items[i].lpGUID );

+            if( result != paNoError )

+                goto error;

+        }

+

+        for( i=0; i< outputNamesAndGUIDs.count; ++i )

+        {

+            result = AddOutputDeviceInfoFromDirectSound( winDsHostApi,

+                    outputNamesAndGUIDs.items[i].name,

+                    outputNamesAndGUIDs.items[i].lpGUID );

+            if( result != paNoError )

+                goto error;

+        }

+    }    

+

+    result = TerminateDSDeviceNameAndGUIDVector( &inputNamesAndGUIDs );

+    if( result != paNoError )

+        goto error;

+

+    result = TerminateDSDeviceNameAndGUIDVector( &outputNamesAndGUIDs );

+    if( result != paNoError )

+        goto error;

+

+    

+    (*hostApi)->Terminate = Terminate;

+    (*hostApi)->OpenStream = OpenStream;

+    (*hostApi)->IsFormatSupported = IsFormatSupported;

+

+    PaUtil_InitializeStreamInterface( &winDsHostApi->callbackStreamInterface, CloseStream, StartStream,

+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,

+                                      GetStreamTime, GetStreamCpuLoad,

+                                      PaUtil_DummyRead, PaUtil_DummyWrite,

+                                      PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );

+

+    PaUtil_InitializeStreamInterface( &winDsHostApi->blockingStreamInterface, CloseStream, StartStream,

+                                      StopStream, AbortStream, IsStreamStopped, IsStreamActive,

+                                      GetStreamTime, PaUtil_DummyGetCpuLoad,

+                                      ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );

+

+    return result;

+

+error:

+    if( winDsHostApi )

+    {

+        if( winDsHostApi->allocations )

+        {

+            PaUtil_FreeAllAllocations( winDsHostApi->allocations );

+            PaUtil_DestroyAllocationGroup( winDsHostApi->allocations );

+        }

+                

+        PaUtil_FreeMemory( winDsHostApi );

+    }

+

+    TerminateDSDeviceNameAndGUIDVector( &inputNamesAndGUIDs );

+    TerminateDSDeviceNameAndGUIDVector( &outputNamesAndGUIDs );

+

+    return result;

+}

+

+

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

+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )

+{

+    PaWinDsHostApiRepresentation *winDsHostApi = (PaWinDsHostApiRepresentation*)hostApi;

+

+    /*

+        IMPLEMENT ME:

+            - clean up any resources not handled by the allocation group

+    */

+

+    if( winDsHostApi->allocations )

+    {

+        PaUtil_FreeAllAllocations( winDsHostApi->allocations );

+        PaUtil_DestroyAllocationGroup( winDsHostApi->allocations );

+    }

+

+    PaUtil_FreeMemory( winDsHostApi );

+

+    PaWinDs_TerminateDSoundEntryPoints();

+

+    CoUninitialize();

+}

+

+

+/* Set minimal latency based on whether NT or Win95.

+ * NT has higher latency.

+ */

+static int PaWinDS_GetMinSystemLatency( void )

+{

+    int minLatencyMsec;

+    /* Set minimal latency based on whether NT or other OS.

+     * NT has higher latency.

+     */

+    OSVERSIONINFO osvi;

+	osvi.dwOSVersionInfoSize = sizeof( osvi );

+	GetVersionEx( &osvi );

+    DBUG(("PA - PlatformId = 0x%x\n", osvi.dwPlatformId ));

+    DBUG(("PA - MajorVersion = 0x%x\n", osvi.dwMajorVersion ));

+    DBUG(("PA - MinorVersion = 0x%x\n", osvi.dwMinorVersion ));

+    /* Check for NT */

+	if( (osvi.dwMajorVersion == 4) && (osvi.dwPlatformId == 2) )

+	{

+		minLatencyMsec = PA_WIN_NT_LATENCY;

+	}

+	else if(osvi.dwMajorVersion >= 5)

+	{

+		minLatencyMsec = PA_WIN_WDM_LATENCY;

+	}

+	else

+	{

+		minLatencyMsec = PA_WIN_9X_LATENCY;

+	}

+    return minLatencyMsec;

+}

+

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

+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,

+                                  const PaStreamParameters *inputParameters,

+                                  const PaStreamParameters *outputParameters,

+                                  double sampleRate )

+{

+    int inputChannelCount, outputChannelCount;

+    PaSampleFormat inputSampleFormat, outputSampleFormat;

+    

+    if( inputParameters )

+    {

+        inputChannelCount = inputParameters->channelCount;

+        inputSampleFormat = inputParameters->sampleFormat;

+

+        /* unless alternate device specification is supported, reject the use of

+            paUseHostApiSpecificDeviceSpecification */

+

+        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )

+            return paInvalidDevice;

+

+        /* check that input device can support inputChannelCount */

+        if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )

+            return paInvalidChannelCount;

+

+        /* validate inputStreamInfo */

+        if( inputParameters->hostApiSpecificStreamInfo )

+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */

+    }

+    else

+    {

+        inputChannelCount = 0;

+    }

+

+    if( outputParameters )

+    {

+        outputChannelCount = outputParameters->channelCount;

+        outputSampleFormat = outputParameters->sampleFormat;

+        

+        /* unless alternate device specification is supported, reject the use of

+            paUseHostApiSpecificDeviceSpecification */

+

+        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )

+            return paInvalidDevice;

+

+        /* check that output device can support inputChannelCount */

+        if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )

+            return paInvalidChannelCount;

+

+        /* validate outputStreamInfo */

+        if( outputParameters->hostApiSpecificStreamInfo )

+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */

+    }

+    else

+    {

+        outputChannelCount = 0;

+    }

+    

+    /*

+        IMPLEMENT ME:

+

+            - if a full duplex stream is requested, check that the combination

+                of input and output parameters is supported if necessary

+

+            - check that the device supports sampleRate

+

+        Because the buffer adapter handles conversion between all standard

+        sample formats, the following checks are only required if paCustomFormat

+        is implemented, or under some other unusual conditions.

+

+            - check that input device can support inputSampleFormat, or that

+                we have the capability to convert from outputSampleFormat to

+                a native format

+

+            - check that output device can support outputSampleFormat, or that

+                we have the capability to convert from outputSampleFormat to

+                a native format

+    */

+

+    return paFormatIsSupported;

+}

+

+

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

+** Determine minimum number of buffers required for this host based

+** on minimum latency. Latency can be optionally set by user by setting

+** an environment variable. For example, to set latency to 200 msec, put:

+**

+**    set PA_MIN_LATENCY_MSEC=200

+**

+** in the AUTOEXEC.BAT file and reboot.

+** If the environment variable is not set, then the latency will be determined

+** based on the OS. Windows NT has higher latency than Win95.

+*/

+#define PA_LATENCY_ENV_NAME  ("PA_MIN_LATENCY_MSEC")

+#define PA_ENV_BUF_SIZE  (32)

+

+static int PaWinDs_GetMinLatencyFrames( double sampleRate )

+{

+    char      envbuf[PA_ENV_BUF_SIZE];

+    DWORD     hresult;

+    int       minLatencyMsec = 0;

+

+    /* Let user determine minimal latency by setting environment variable. */

+    hresult = GetEnvironmentVariable( PA_LATENCY_ENV_NAME, envbuf, PA_ENV_BUF_SIZE );

+    if( (hresult > 0) && (hresult < PA_ENV_BUF_SIZE) )

+    {

+        minLatencyMsec = atoi( envbuf );

+    }

+    else

+    {

+        minLatencyMsec = PaWinDS_GetMinSystemLatency();

+#if PA_USE_HIGH_LATENCY

+        PRINT(("PA - Minimum Latency set to %d msec!\n", minLatencyMsec ));

+#endif

+

+    }

+

+    return (int) (minLatencyMsec * sampleRate * SECONDS_PER_MSEC);

+}

+

+

+static HRESULT InitInputBuffer( PaWinDsStream *stream, unsigned long nFrameRate, WORD nChannels, int bytesPerBuffer )

+{

+    DSCBUFFERDESC  captureDesc;

+    WAVEFORMATEX   wfFormat;

+    HRESULT        result;

+    

+    stream->bytesPerInputFrame = nChannels * sizeof(short);

+

+    // Define the buffer format

+    wfFormat.wFormatTag      = WAVE_FORMAT_PCM;

+    wfFormat.nChannels       = nChannels;

+    wfFormat.nSamplesPerSec  = nFrameRate;

+    wfFormat.wBitsPerSample  = 8 * sizeof(short);

+    wfFormat.nBlockAlign     = (WORD)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));

+    wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;

+    wfFormat.cbSize          = 0;   /* No extended format info. */

+    stream->inputSize = bytesPerBuffer;

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

+    // Setup the secondary buffer description

+    ZeroMemory(&captureDesc, sizeof(DSCBUFFERDESC));

+    captureDesc.dwSize = sizeof(DSCBUFFERDESC);

+    captureDesc.dwFlags =  0;

+    captureDesc.dwBufferBytes = bytesPerBuffer;

+    captureDesc.lpwfxFormat = &wfFormat;

+    // Create the capture buffer

+    if ((result = IDirectSoundCapture_CreateCaptureBuffer( stream->pDirectSoundCapture,

+                  &captureDesc, &stream->pDirectSoundInputBuffer, NULL)) != DS_OK) return result;

+    stream->readOffset = 0;  // reset last read position to start of buffer

+    return DS_OK;

+}

+

+

+static HRESULT InitOutputBuffer( PaWinDsStream *stream, unsigned long nFrameRate, WORD nChannels, int bytesPerBuffer )

+{

+    DWORD          dwDataLen;

+    DWORD          playCursor;

+    HRESULT        result;

+    LPDIRECTSOUNDBUFFER pPrimaryBuffer;

+    HWND           hWnd;

+    HRESULT        hr;

+    WAVEFORMATEX   wfFormat;

+    DSBUFFERDESC   primaryDesc;

+    DSBUFFERDESC   secondaryDesc;

+    unsigned char* pDSBuffData;

+    LARGE_INTEGER  counterFrequency;

+

+    stream->outputBufferSizeBytes = bytesPerBuffer;

+    stream->outputIsRunning = FALSE;

+    stream->outputUnderflowCount = 0;

+    stream->dsw_framesWritten = 0;

+    stream->bytesPerOutputFrame = nChannels * sizeof(short);

+

+    // We were using getForegroundWindow() but sometimes the ForegroundWindow may not be the

+    // applications's window. Also if that window is closed before the Buffer is closed

+    // then DirectSound can crash. (Thanks for Scott Patterson for reporting this.)

+    // So we will use GetDesktopWindow() which was suggested by Miller Puckette.

+    // hWnd = GetForegroundWindow();

+    //

+    //  FIXME: The example code I have on the net creates a hidden window that

+    //      is managed by our code - I think we should do that - one hidden

+    //      window for the whole of Pa_DS

+    //

+    hWnd = GetDesktopWindow();

+

+    // Set cooperative level to DSSCL_EXCLUSIVE so that we can get 16 bit output, 44.1 KHz.

+    // Exclusize also prevents unexpected sounds from other apps during a performance.

+    if ((hr = IDirectSound_SetCooperativeLevel( stream->pDirectSound,

+              hWnd, DSSCL_EXCLUSIVE)) != DS_OK)

+    {

+        return hr;

+    }

+

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

+    // Create primary buffer and set format just so we can specify our custom format.

+    // Otherwise we would be stuck with the default which might be 8 bit or 22050 Hz.

+    // Setup the primary buffer description

+    ZeroMemory(&primaryDesc, sizeof(DSBUFFERDESC));

+    primaryDesc.dwSize        = sizeof(DSBUFFERDESC);

+    primaryDesc.dwFlags       = DSBCAPS_PRIMARYBUFFER; // all panning, mixing, etc done by synth

+    primaryDesc.dwBufferBytes = 0;

+    primaryDesc.lpwfxFormat   = NULL;

+    // Create the buffer

+    if ((result = IDirectSound_CreateSoundBuffer( stream->pDirectSound,

+                  &primaryDesc, &pPrimaryBuffer, NULL)) != DS_OK) return result;

+    // Define the buffer format

+    wfFormat.wFormatTag = WAVE_FORMAT_PCM;

+    wfFormat.nChannels = nChannels;

+    wfFormat.nSamplesPerSec = nFrameRate;

+    wfFormat.wBitsPerSample = 8 * sizeof(short);

+    wfFormat.nBlockAlign = (WORD)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));

+    wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;

+    wfFormat.cbSize = 0;  /* No extended format info. */

+    // Set the primary buffer's format

+    if((result = IDirectSoundBuffer_SetFormat( pPrimaryBuffer, &wfFormat)) != DS_OK) return result;

+

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

+    // Setup the secondary buffer description

+    ZeroMemory(&secondaryDesc, sizeof(DSBUFFERDESC));

+    secondaryDesc.dwSize = sizeof(DSBUFFERDESC);

+    secondaryDesc.dwFlags =  DSBCAPS_GLOBALFOCUS | DSBCAPS_GETCURRENTPOSITION2;

+    secondaryDesc.dwBufferBytes = bytesPerBuffer;

+    secondaryDesc.lpwfxFormat = &wfFormat;

+    // Create the secondary buffer

+    if ((result = IDirectSound_CreateSoundBuffer( stream->pDirectSound,

+                  &secondaryDesc, &stream->pDirectSoundOutputBuffer, NULL)) != DS_OK) return result;

+    // Lock the DS buffer

+    if ((result = IDirectSoundBuffer_Lock( stream->pDirectSoundOutputBuffer, 0, stream->outputBufferSizeBytes, (LPVOID*)&pDSBuffData,

+                                           &dwDataLen, NULL, 0, 0)) != DS_OK) return result;

+    // Zero the DS buffer

+    ZeroMemory(pDSBuffData, dwDataLen);

+    // Unlock the DS buffer

+    if ((result = IDirectSoundBuffer_Unlock( stream->pDirectSoundOutputBuffer, pDSBuffData, dwDataLen, NULL, 0)) != DS_OK) return result;

+    if( QueryPerformanceFrequency( &counterFrequency ) )

+    {

+        int framesInBuffer = bytesPerBuffer / (nChannels * sizeof(short));

+        stream->perfCounterTicksPerBuffer.QuadPart = (counterFrequency.QuadPart * framesInBuffer) / nFrameRate;

+    }

+    else

+    {

+        stream->perfCounterTicksPerBuffer.QuadPart = 0;

+    }

+    // Let DSound set the starting write position because if we set it to zero, it looks like the

+    // buffer is full to begin with. This causes a long pause before sound starts when using large buffers.

+    hr = IDirectSoundBuffer_GetCurrentPosition( stream->pDirectSoundOutputBuffer,

+            &playCursor, &stream->outputBufferWriteOffsetBytes );

+    if( hr != DS_OK )

+    {

+        return hr;

+    }

+    stream->dsw_framesWritten = stream->outputBufferWriteOffsetBytes / stream->bytesPerOutputFrame;

+    /* printf("DSW_InitOutputBuffer: playCursor = %d, writeCursor = %d\n", playCursor, dsw->dsw_WriteOffset ); */

+    return DS_OK;

+}

+

+

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

+/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */

+

+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,

+                           PaStream** s,

+                           const PaStreamParameters *inputParameters,

+                           const PaStreamParameters *outputParameters,

+                           double sampleRate,

+                           unsigned long framesPerBuffer,

+                           PaStreamFlags streamFlags,

+                           PaStreamCallback *streamCallback,

+                           void *userData )

+{

+    PaError result = paNoError;

+    PaWinDsHostApiRepresentation *winDsHostApi = (PaWinDsHostApiRepresentation*)hostApi;

+    PaWinDsStream *stream = 0;

+    int inputChannelCount, outputChannelCount;

+    PaSampleFormat inputSampleFormat, outputSampleFormat;

+    PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;

+    unsigned long suggestedInputLatencyFrames, suggestedOutputLatencyFrames;

+

+    if( inputParameters )

+    {

+        inputChannelCount = inputParameters->channelCount;

+        inputSampleFormat = inputParameters->sampleFormat;

+        suggestedInputLatencyFrames = (unsigned long)(inputParameters->suggestedLatency * sampleRate);

+

+        /* IDEA: the following 3 checks could be performed by default by pa_front

+            unless some flag indicated otherwise */

+            

+        /* unless alternate device specification is supported, reject the use of

+            paUseHostApiSpecificDeviceSpecification */

+        if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )

+            return paInvalidDevice;

+

+        /* check that input device can support inputChannelCount */

+        if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )

+            return paInvalidChannelCount;

+            

+        /* validate hostApiSpecificStreamInfo */

+        if( inputParameters->hostApiSpecificStreamInfo )

+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */

+    }

+    else

+    {

+        inputChannelCount = 0;

+		inputSampleFormat = 0;

+        suggestedInputLatencyFrames = 0;

+    }

+

+

+    if( outputParameters )

+    {

+        outputChannelCount = outputParameters->channelCount;

+        outputSampleFormat = outputParameters->sampleFormat;

+        suggestedOutputLatencyFrames = (unsigned long)(outputParameters->suggestedLatency * sampleRate);

+

+        /* unless alternate device specification is supported, reject the use of

+            paUseHostApiSpecificDeviceSpecification */

+        if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )

+            return paInvalidDevice;

+

+        /* check that output device can support inputChannelCount */

+        if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )

+            return paInvalidChannelCount;

+

+        /* validate hostApiSpecificStreamInfo */

+        if( outputParameters->hostApiSpecificStreamInfo )

+            return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */            

+    }

+    else

+    {

+        outputChannelCount = 0;

+		outputSampleFormat = 0;

+        suggestedOutputLatencyFrames = 0;

+    }

+

+

+    /*

+        IMPLEMENT ME:

+

+        ( the following two checks are taken care of by PaUtil_InitializeBufferProcessor() )

+

+            - check that input device can support inputSampleFormat, or that

+                we have the capability to convert from outputSampleFormat to

+                a native format

+

+            - check that output device can support outputSampleFormat, or that

+                we have the capability to convert from outputSampleFormat to

+                a native format

+

+            - if a full duplex stream is requested, check that the combination

+                of input and output parameters is supported

+

+            - check that the device supports sampleRate

+

+            - alter sampleRate to a close allowable rate if possible / necessary

+

+            - validate suggestedInputLatency and suggestedOutputLatency parameters,

+                use default values where necessary

+    */

+

+

+    /* validate platform specific flags */

+    if( (streamFlags & paPlatformSpecificFlags) != 0 )

+        return paInvalidFlag; /* unexpected platform specific flag */

+

+

+    stream = (PaWinDsStream*)PaUtil_AllocateMemory( sizeof(PaWinDsStream) );

+    if( !stream )

+    {

+        result = paInsufficientMemory;

+        goto error;

+    }

+

+    memset( stream, 0, sizeof(PaWinDsStream) ); /* initialize all stream variables to 0 */

+

+    if( streamCallback )

+    {

+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,

+                                               &winDsHostApi->callbackStreamInterface, streamCallback, userData );

+    }

+    else

+    {

+        PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,

+                                               &winDsHostApi->blockingStreamInterface, streamCallback, userData );

+    }

+    

+    PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );

+

+

+    if( inputParameters )

+    {

+        /* IMPLEMENT ME - establish which  host formats are available */

+        hostInputSampleFormat =

+            PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, inputParameters->sampleFormat );

+    }

+	else

+	{

+		hostInputSampleFormat = 0;

+	}

+

+    if( outputParameters )

+    {

+        /* IMPLEMENT ME - establish which  host formats are available */

+        hostOutputSampleFormat =

+            PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, outputParameters->sampleFormat );

+    }

+    else

+	{

+		hostOutputSampleFormat = 0;

+	}

+

+    result =  PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,

+                    inputChannelCount, inputSampleFormat, hostInputSampleFormat,

+                    outputChannelCount, outputSampleFormat, hostOutputSampleFormat,

+                    sampleRate, streamFlags, framesPerBuffer,

+                    framesPerBuffer, /* ignored in paUtilVariableHostBufferSizePartialUsageAllowed mode. */

+                /* This next mode is required because DS can split the host buffer when it wraps around. */

+                    paUtilVariableHostBufferSizePartialUsageAllowed,

+                    streamCallback, userData );

+    if( result != paNoError )

+        goto error;

+

+

+    stream->streamRepresentation.streamInfo.inputLatency =

+            PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor);   /* FIXME: not initialised anywhere else */

+    stream->streamRepresentation.streamInfo.outputLatency =

+            PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor);    /* FIXME: not initialised anywhere else */

+    stream->streamRepresentation.streamInfo.sampleRate = sampleRate;

+

+    

+/* DirectSound specific initialization */ 

+    {

+        HRESULT          hr;

+        int              bytesPerDirectSoundBuffer;

+        int              userLatencyFrames;

+        int              minLatencyFrames;

+

+        stream->timerID = 0;

+

+    /* Get system minimum latency. */

+        minLatencyFrames = PaWinDs_GetMinLatencyFrames( sampleRate );

+

+    /* Let user override latency by passing latency parameter. */

+        userLatencyFrames = (suggestedInputLatencyFrames > suggestedOutputLatencyFrames)

+                    ? suggestedInputLatencyFrames

+                    : suggestedOutputLatencyFrames;

+        if( userLatencyFrames > 0 ) minLatencyFrames = userLatencyFrames;

+

+    /* Calculate stream->framesPerDSBuffer depending on framesPerBuffer */

+        if( framesPerBuffer == paFramesPerBufferUnspecified )

+        {

+        /* App support variable framesPerBuffer */

+            stream->framesPerDSBuffer = minLatencyFrames;

+

+            stream->streamRepresentation.streamInfo.outputLatency = (double)(minLatencyFrames - 1) / sampleRate;

+        }

+        else

+        {

+        /* Round up to number of buffers needed to guarantee that latency. */

+            int numUserBuffers = (minLatencyFrames + framesPerBuffer - 1) / framesPerBuffer;

+            if( numUserBuffers < 1 ) numUserBuffers = 1;

+            numUserBuffers += 1; /* So we have latency worth of buffers ahead of current buffer. */

+            stream->framesPerDSBuffer = framesPerBuffer * numUserBuffers;

+

+            stream->streamRepresentation.streamInfo.outputLatency = (double)(framesPerBuffer * (numUserBuffers-1)) / sampleRate;

+        }

+

+        {

+            /** @todo REVIEW: this calculation seems incorrect to me - rossb. */

+            int msecLatency = (int) ((stream->framesPerDSBuffer * MSEC_PER_SECOND) / sampleRate);

+            PRINT(("PortAudio on DirectSound - Latency = %d frames, %d msec\n", stream->framesPerDSBuffer, msecLatency ));

+        }

+

+

+        /* ------------------ OUTPUT */

+        if( outputParameters )

+        {

+            /*

+            PaDeviceInfo *deviceInfo = hostApi->deviceInfos[ outputParameters->device ];

+            DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", outputParameters->device));

+            */

+            

+            bytesPerDirectSoundBuffer = stream->framesPerDSBuffer * outputParameters->channelCount * sizeof(short);

+            if( bytesPerDirectSoundBuffer < DSBSIZE_MIN )

+            {

+                result = paBufferTooSmall;

+                goto error;

+            }

+            else if( bytesPerDirectSoundBuffer > DSBSIZE_MAX )

+            {

+                result = paBufferTooBig;

+                goto error;

+            }

+

+

+            hr = paWinDsDSoundEntryPoints.DirectSoundCreate( winDsHostApi->winDsDeviceInfos[outputParameters->device].lpGUID,

+                        &stream->pDirectSound, NULL );

+            if( hr != DS_OK )

+            {

+                ERR_RPT(("PortAudio: DirectSoundCreate() failed!\n"));

+                result = paUnanticipatedHostError;

+                PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );

+                goto error;

+            }

+            hr = InitOutputBuffer( stream,

+                                       (unsigned long) (sampleRate + 0.5),

+                                       (WORD)outputParameters->channelCount, bytesPerDirectSoundBuffer );

+            DBUG(("InitOutputBuffer() returns %x\n", hr));

+            if( hr != DS_OK )

+            {

+                result = paUnanticipatedHostError;

+                PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );

+                goto error;

+            }

+            /* Calculate value used in latency calculation to avoid real-time divides. */

+            stream->secondsPerHostByte = 1.0 /

+                (stream->bufferProcessor.bytesPerHostOutputSample *

+                outputChannelCount * sampleRate);

+        }

+

+        /* ------------------ INPUT */

+        if( inputParameters )

+        {

+            /*

+            PaDeviceInfo *deviceInfo = hostApi->deviceInfos[ inputParameters->device ];

+            DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", inputParameters->device));

+            */

+            

+            bytesPerDirectSoundBuffer = stream->framesPerDSBuffer * inputParameters->channelCount * sizeof(short);

+            if( bytesPerDirectSoundBuffer < DSBSIZE_MIN )

+            {

+                result = paBufferTooSmall;

+                goto error;

+            }

+            else if( bytesPerDirectSoundBuffer > DSBSIZE_MAX )

+            {

+                result = paBufferTooBig;

+                goto error;

+            }

+

+            hr = paWinDsDSoundEntryPoints.DirectSoundCaptureCreate( winDsHostApi->winDsDeviceInfos[inputParameters->device].lpGUID,

+                        &stream->pDirectSoundCapture,   NULL );

+            if( hr != DS_OK )

+            {

+                ERR_RPT(("PortAudio: DirectSoundCaptureCreate() failed!\n"));

+                result = paUnanticipatedHostError;

+                PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );

+                goto error;

+            }

+            hr = InitInputBuffer( stream,

+                                      (unsigned long) (sampleRate + 0.5),

+                                      (WORD)inputParameters->channelCount, bytesPerDirectSoundBuffer );

+            DBUG(("InitInputBuffer() returns %x\n", hr));

+            if( hr != DS_OK )

+            {

+                ERR_RPT(("PortAudio: DSW_InitInputBuffer() returns %x\n", hr));

+                result = paUnanticipatedHostError;

+                PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );

+                goto error;

+            }

+        }

+

+    }

+

+    *s = (PaStream*)stream;

+

+    return result;

+

+error:

+    if( stream )

+        PaUtil_FreeMemory( stream );

+

+    return result;

+}

+

+

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

+ * Determine how much space can be safely written to in DS buffer.

+ * Detect underflows and overflows.

+ * Does not allow writing into safety gap maintained by DirectSound.

+ */

+static HRESULT QueryOutputSpace( PaWinDsStream *stream, long *bytesEmpty )

+{

+    HRESULT hr;

+    DWORD   playCursor;

+    DWORD   writeCursor;

+    long    numBytesEmpty;

+    long    playWriteGap;

+    // Query to see how much room is in buffer.

+    hr = IDirectSoundBuffer_GetCurrentPosition( stream->pDirectSoundOutputBuffer,

+            &playCursor, &writeCursor );

+    if( hr != DS_OK )

+    {

+        return hr;

+    }

+    // Determine size of gap between playIndex and WriteIndex that we cannot write into.

+    playWriteGap = writeCursor - playCursor;

+    if( playWriteGap < 0 ) playWriteGap += stream->outputBufferSizeBytes; // unwrap

+    /* DirectSound doesn't have a large enough playCursor so we cannot detect wrap-around. */

+    /* Attempt to detect playCursor wrap-around and correct it. */

+    if( stream->outputIsRunning && (stream->perfCounterTicksPerBuffer.QuadPart != 0) )

+    {

+        /* How much time has elapsed since last check. */

+        LARGE_INTEGER   currentTime;

+        LARGE_INTEGER   elapsedTime;

+        long            bytesPlayed;

+        long            bytesExpected;

+        long            buffersWrapped;

+        QueryPerformanceCounter( &currentTime );

+        elapsedTime.QuadPart = currentTime.QuadPart - stream->previousPlayTime.QuadPart;

+        stream->previousPlayTime = currentTime;

+        /* How many bytes does DirectSound say have been played. */

+        bytesPlayed = playCursor - stream->previousPlayCursor;

+        if( bytesPlayed < 0 ) bytesPlayed += stream->outputBufferSizeBytes; // unwrap

+        stream->previousPlayCursor = playCursor;

+        /* Calculate how many bytes we would have expected to been played by now. */

+        bytesExpected = (long) ((elapsedTime.QuadPart * stream->outputBufferSizeBytes) / stream->perfCounterTicksPerBuffer.QuadPart);

+        buffersWrapped = (bytesExpected - bytesPlayed) / stream->outputBufferSizeBytes;

+        if( buffersWrapped > 0 )

+        {

+            playCursor += (buffersWrapped * stream->outputBufferSizeBytes);

+            bytesPlayed += (buffersWrapped * stream->outputBufferSizeBytes);

+        }

+        /* Maintain frame output cursor. */

+        stream->framesPlayed += (bytesPlayed / stream->bytesPerOutputFrame);

+    }

+    numBytesEmpty = playCursor - stream->outputBufferWriteOffsetBytes;

+    if( numBytesEmpty < 0 ) numBytesEmpty += stream->outputBufferSizeBytes; // unwrap offset

+    /* Have we underflowed? */

+    if( numBytesEmpty > (stream->outputBufferSizeBytes - playWriteGap) )

+    {

+        if( stream->outputIsRunning )

+        {

+            stream->outputUnderflowCount += 1;

+        }

+        stream->outputBufferWriteOffsetBytes = writeCursor;

+        numBytesEmpty = stream->outputBufferSizeBytes - playWriteGap;

+    }

+    *bytesEmpty = numBytesEmpty;

+    return hr;

+}

+

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

+static PaError Pa_TimeSlice( PaWinDsStream *stream )

+{

+    PaError           result = 0;   /* FIXME: this should be declared int and this function should also return that type (same as stream callback return type)*/

+    long              numFrames = 0;

+    long              bytesEmpty = 0;

+    long              bytesFilled = 0;

+    long              bytesToXfer = 0;

+    long              framesToXfer = 0;

+    long              numInFramesReady = 0;

+    long              numOutFramesReady = 0;

+    long              bytesProcessed;

+    HRESULT           hresult;

+    double            outputLatency = 0;

+    PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /** @todo implement inputBufferAdcTime */

+    

+/* Input */

+    LPBYTE            lpInBuf1 = NULL;

+    LPBYTE            lpInBuf2 = NULL;

+    DWORD             dwInSize1 = 0;

+    DWORD             dwInSize2 = 0;

+/* Output */

+    LPBYTE            lpOutBuf1 = NULL;

+    LPBYTE            lpOutBuf2 = NULL;

+    DWORD             dwOutSize1 = 0;

+    DWORD             dwOutSize2 = 0;

+

+    /* How much input data is available? */

+    if( stream->bufferProcessor.inputChannelCount > 0 )

+    {

+        HRESULT hr;

+        DWORD capturePos;

+        DWORD readPos;

+        long  filled = 0;

+        // Query to see how much data is in buffer.

+        // We don't need the capture position but sometimes DirectSound doesn't handle NULLS correctly

+        // so let's pass a pointer just to be safe.

+        hr = IDirectSoundCaptureBuffer_GetCurrentPosition( stream->pDirectSoundInputBuffer, &capturePos, &readPos );

+        if( hr == DS_OK )

+        {

+            filled = readPos - stream->readOffset;

+            if( filled < 0 ) filled += stream->inputSize; // unwrap offset

+            bytesFilled = filled;

+        }

+            // FIXME: what happens if IDirectSoundCaptureBuffer_GetCurrentPosition fails?

+

+        framesToXfer = numInFramesReady = bytesFilled / stream->bytesPerInputFrame;

+        outputLatency = ((double)bytesFilled) * stream->secondsPerHostByte;

+

+        /** @todo Check for overflow */

+    }

+

+    /* How much output room is available? */

+    if( stream->bufferProcessor.outputChannelCount > 0 )

+    {

+        UINT previousUnderflowCount = stream->outputUnderflowCount;

+        QueryOutputSpace( stream, &bytesEmpty );

+        framesToXfer = numOutFramesReady = bytesEmpty / stream->bytesPerOutputFrame;

+

+        /* Check for underflow */

+        if( stream->outputUnderflowCount != previousUnderflowCount )

+            stream->callbackFlags |= paOutputUnderflow;

+    }

+

+    if( (numInFramesReady > 0) && (numOutFramesReady > 0) )

+    {

+        framesToXfer = (numOutFramesReady < numInFramesReady) ? numOutFramesReady : numInFramesReady;

+    }

+

+    if( framesToXfer > 0 )

+    {

+

+        PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );

+

+    /* The outputBufferDacTime parameter should indicates the time at which

+        the first sample of the output buffer is heard at the DACs. */

+        timeInfo.currentTime = PaUtil_GetTime();

+        timeInfo.outputBufferDacTime = timeInfo.currentTime + outputLatency;

+

+

+        PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, stream->callbackFlags );

+        stream->callbackFlags = 0;

+        

+    /* Input */

+        if( stream->bufferProcessor.inputChannelCount > 0 )

+        {

+            bytesToXfer = framesToXfer * stream->bytesPerInputFrame;

+            hresult = IDirectSoundCaptureBuffer_Lock ( stream->pDirectSoundInputBuffer,

+                stream->readOffset, bytesToXfer,

+                (void **) &lpInBuf1, &dwInSize1,

+                (void **) &lpInBuf2, &dwInSize2, 0);

+            if (hresult != DS_OK)

+            {

+                ERR_RPT(("DirectSound IDirectSoundCaptureBuffer_Lock failed, hresult = 0x%x\n",hresult));

+                result = paUnanticipatedHostError;

+                PA_DS_SET_LAST_DIRECTSOUND_ERROR( hresult );

+                goto error2;

+            }

+

+            numFrames = dwInSize1 / stream->bytesPerInputFrame;

+            PaUtil_SetInputFrameCount( &stream->bufferProcessor, numFrames );

+            PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, 0, lpInBuf1, 0 );

+        /* Is input split into two regions. */

+            if( dwInSize2 > 0 )

+            {

+                numFrames = dwInSize2 / stream->bytesPerInputFrame;

+                PaUtil_Set2ndInputFrameCount( &stream->bufferProcessor, numFrames );

+                PaUtil_Set2ndInterleavedInputChannels( &stream->bufferProcessor, 0, lpInBuf2, 0 );

+            }

+        }

+

+    /* Output */

+        if( stream->bufferProcessor.outputChannelCount > 0 )

+        {

+            bytesToXfer = framesToXfer * stream->bytesPerOutputFrame;

+            hresult = IDirectSoundBuffer_Lock ( stream->pDirectSoundOutputBuffer,

+                stream->outputBufferWriteOffsetBytes, bytesToXfer,

+                (void **) &lpOutBuf1, &dwOutSize1,

+                (void **) &lpOutBuf2, &dwOutSize2, 0);

+            if (hresult != DS_OK)

+            {

+                ERR_RPT(("DirectSound IDirectSoundBuffer_Lock failed, hresult = 0x%x\n",hresult));

+                result = paUnanticipatedHostError;

+                PA_DS_SET_LAST_DIRECTSOUND_ERROR( hresult );

+                goto error1;

+            }

+

+            numFrames = dwOutSize1 / stream->bytesPerOutputFrame;

+            PaUtil_SetOutputFrameCount( &stream->bufferProcessor, numFrames );

+            PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, 0, lpOutBuf1, 0 );

+

+        /* Is output split into two regions. */

+            if( dwOutSize2 > 0 )

+            {

+                numFrames = dwOutSize2 / stream->bytesPerOutputFrame;

+                PaUtil_Set2ndOutputFrameCount( &stream->bufferProcessor, numFrames );

+                PaUtil_Set2ndInterleavedOutputChannels( &stream->bufferProcessor, 0, lpOutBuf2, 0 );

+            }

+        }

+

+        result = paContinue;

+        numFrames = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &result );

+        stream->framesWritten += numFrames;

+        

+        if( stream->bufferProcessor.outputChannelCount > 0 )

+        {

+        /* FIXME: an underflow could happen here */

+

+        /* Update our buffer offset and unlock sound buffer */

+            bytesProcessed = numFrames * stream->bytesPerOutputFrame;

+            stream->outputBufferWriteOffsetBytes = (stream->outputBufferWriteOffsetBytes + bytesProcessed) % stream->outputBufferSizeBytes;

+            IDirectSoundBuffer_Unlock( stream->pDirectSoundOutputBuffer, lpOutBuf1, dwOutSize1, lpOutBuf2, dwOutSize2);

+            stream->dsw_framesWritten += numFrames;

+        }

+

+error1:

+        if( stream->bufferProcessor.inputChannelCount > 0 )

+        {

+        /* FIXME: an overflow could happen here */

+

+        /* Update our buffer offset and unlock sound buffer */

+            bytesProcessed = numFrames * stream->bytesPerInputFrame;

+            stream->readOffset = (stream->readOffset + bytesProcessed) % stream->inputSize;

+            IDirectSoundCaptureBuffer_Unlock( stream->pDirectSoundInputBuffer, lpInBuf1, dwInSize1, lpInBuf2, dwInSize2);

+        }

+error2:

+

+        PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, numFrames );

+

+    }

+    

+    return result;

+}

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

+

+static HRESULT ZeroAvailableOutputSpace( PaWinDsStream *stream )

+{

+    HRESULT hr;

+    LPBYTE lpbuf1 = NULL;

+    LPBYTE lpbuf2 = NULL;

+    DWORD dwsize1 = 0;

+    DWORD dwsize2 = 0;

+    long  bytesEmpty;

+    hr = QueryOutputSpace( stream, &bytesEmpty ); // updates framesPlayed

+    if (hr != DS_OK) return hr;

+    if( bytesEmpty == 0 ) return DS_OK;

+    // Lock free space in the DS

+    hr = IDirectSoundBuffer_Lock( stream->pDirectSoundOutputBuffer, stream->outputBufferWriteOffsetBytes,

+                                    bytesEmpty, (void **) &lpbuf1, &dwsize1,

+                                    (void **) &lpbuf2, &dwsize2, 0);

+    if (hr == DS_OK)

+    {

+        // Copy the buffer into the DS

+        ZeroMemory(lpbuf1, dwsize1);

+        if(lpbuf2 != NULL)

+        {

+            ZeroMemory(lpbuf2, dwsize2);

+        }

+        // Update our buffer offset and unlock sound buffer

+        stream->outputBufferWriteOffsetBytes = (stream->outputBufferWriteOffsetBytes + dwsize1 + dwsize2) % stream->outputBufferSizeBytes;

+        IDirectSoundBuffer_Unlock( stream->pDirectSoundOutputBuffer, lpbuf1, dwsize1, lpbuf2, dwsize2);

+        stream->dsw_framesWritten += bytesEmpty / stream->bytesPerOutputFrame;

+    }

+    return hr;

+}

+

+

+static void CALLBACK Pa_TimerCallback(UINT uID, UINT uMsg, DWORD_PTR dwUser, DWORD dw1, DWORD dw2)

+{

+    PaWinDsStream *stream;

+

+    /* suppress unused variable warnings */

+    (void) uID;

+    (void) uMsg;

+    (void) dw1;

+    (void) dw2;

+    

+    stream = (PaWinDsStream *) dwUser;

+    if( stream == NULL ) return;

+

+    if( stream->isActive )

+    {

+        if( stream->abortProcessing )

+        {

+            stream->isActive = 0;

+        }

+        else if( stream->stopProcessing )

+        {

+            if( stream->bufferProcessor.outputChannelCount > 0 )

+            {

+                ZeroAvailableOutputSpace( stream );

+                /* clear isActive when all sound played */

+                if( stream->framesPlayed >= stream->framesWritten )

+                {

+                    stream->isActive = 0;

+                }

+            }

+            else

+            {

+                stream->isActive = 0;

+            }

+        }

+        else

+        {

+            if( Pa_TimeSlice( stream ) != 0)  /* Call time slice independant of timing method. */

+            {

+                /* FIXME implement handling of paComplete and paAbort if possible */

+                stream->stopProcessing = 1;

+            }

+        }

+

+        if( !stream->isActive ){

+            if( stream->streamRepresentation.streamFinishedCallback != 0 )

+                stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );

+        }

+    }

+}

+

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

+    When CloseStream() is called, the multi-api layer ensures that

+    the stream has already been stopped or aborted.

+*/

+static PaError CloseStream( PaStream* s )

+{

+    PaError result = paNoError;

+    PaWinDsStream *stream = (PaWinDsStream*)s;

+

+    // Cleanup the sound buffers

+    if( stream->pDirectSoundOutputBuffer )

+    {

+        IDirectSoundBuffer_Stop( stream->pDirectSoundOutputBuffer );

+        IDirectSoundBuffer_Release( stream->pDirectSoundOutputBuffer );

+        stream->pDirectSoundOutputBuffer = NULL;

+    }

+

+    if( stream->pDirectSoundInputBuffer )

+    {

+        IDirectSoundCaptureBuffer_Stop( stream->pDirectSoundInputBuffer );

+        IDirectSoundCaptureBuffer_Release( stream->pDirectSoundInputBuffer );

+        stream->pDirectSoundInputBuffer = NULL;

+    }

+

+    if( stream->pDirectSoundCapture )

+    {

+        IDirectSoundCapture_Release( stream->pDirectSoundCapture );

+        stream->pDirectSoundCapture = NULL;

+    }

+

+    if( stream->pDirectSound )

+    {

+        IDirectSound_Release( stream->pDirectSound );

+        stream->pDirectSound = NULL;

+    }

+

+    PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );

+    PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );

+    PaUtil_FreeMemory( stream );

+

+    return result;

+}

+

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

+static PaError StartStream( PaStream *s )

+{

+    PaError          result = paNoError;

+    PaWinDsStream   *stream = (PaWinDsStream*)s;

+    HRESULT          hr;

+

+    PaUtil_ResetBufferProcessor( &stream->bufferProcessor );

+    

+    if( stream->bufferProcessor.inputChannelCount > 0 )

+    {

+        // Start the buffer playback

+        if( stream->pDirectSoundInputBuffer != NULL ) // FIXME: not sure this check is necessary

+        {

+            hr = IDirectSoundCaptureBuffer_Start( stream->pDirectSoundInputBuffer, DSCBSTART_LOOPING );

+        }

+

+        DBUG(("StartStream: DSW_StartInput returned = 0x%X.\n", hr));

+        if( hr != DS_OK )

+        {

+            result = paUnanticipatedHostError;

+            PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );

+            goto error;

+        }

+    }

+

+    stream->framesWritten = 0;

+    stream->callbackFlags = 0;

+

+    stream->abortProcessing = 0;

+    stream->stopProcessing = 0;

+    stream->isActive = 1;

+

+    if( stream->bufferProcessor.outputChannelCount > 0 )

+    {

+        /* Give user callback a chance to pre-fill buffer. REVIEW - i thought we weren't pre-filling, rb. */

+        result = Pa_TimeSlice( stream );

+        if( result != paNoError ) return result; // FIXME - what if finished?

+

+        QueryPerformanceCounter( &stream->previousPlayTime );

+        stream->previousPlayCursor = 0;

+        stream->framesPlayed = 0;

+        hr = IDirectSoundBuffer_SetCurrentPosition( stream->pDirectSoundOutputBuffer, 0 );

+        DBUG(("PaHost_StartOutput: IDirectSoundBuffer_SetCurrentPosition returned = 0x%X.\n", hr));

+        if( hr != DS_OK )

+        {

+            result = paUnanticipatedHostError;

+            PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );

+            goto error;

+        }

+

+        // Start the buffer playback in a loop.

+        if( stream->pDirectSoundOutputBuffer != NULL ) // FIXME: not sure this needs to be checked here

+        {

+            hr = IDirectSoundBuffer_Play( stream->pDirectSoundOutputBuffer, 0, 0, DSBPLAY_LOOPING );

+            DBUG(("PaHost_StartOutput: IDirectSoundBuffer_Play returned = 0x%X.\n", hr));

+            if( hr != DS_OK )

+            {

+                result = paUnanticipatedHostError;

+                PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );

+                goto error;

+            }

+            stream->outputIsRunning = TRUE;

+        }

+    }

+

+

+    /* Create timer that will wake us up so we can fill the DSound buffer. */

+    {

+        int resolution;

+        int framesPerWakeup = stream->framesPerDSBuffer / 4;

+        int msecPerWakeup = MSEC_PER_SECOND * framesPerWakeup / (int) stream->streamRepresentation.streamInfo.sampleRate;

+        if( msecPerWakeup < 10 ) msecPerWakeup = 10;

+        else if( msecPerWakeup > 100 ) msecPerWakeup = 100;

+        resolution = msecPerWakeup/4;

+        stream->timerID = timeSetEvent( msecPerWakeup, resolution, (LPTIMECALLBACK) Pa_TimerCallback,

+                                             (DWORD_PTR) stream, TIME_PERIODIC );

+    }

+    if( stream->timerID == 0 )

+    {

+        stream->isActive = 0;

+        result = paUnanticipatedHostError;

+        PA_DS_SET_LAST_DIRECTSOUND_ERROR( hr );

+        goto error;

+    }

+

+    stream->isStarted = TRUE;

+

+error:

+    return result;

+}

+

+

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

+static PaError StopStream( PaStream *s )

+{

+    PaError result = paNoError;

+    PaWinDsStream *stream = (PaWinDsStream*)s;

+    HRESULT          hr;

+    int timeoutMsec;

+

+    stream->stopProcessing = 1;

+    /* Set timeout at 20% beyond maximum time we might wait. */

+    timeoutMsec = (int) (1200.0 * stream->framesPerDSBuffer / stream->streamRepresentation.streamInfo.sampleRate);

+    while( stream->isActive && (timeoutMsec > 0)  )

+    {

+        Sleep(10);

+        timeoutMsec -= 10;

+    }

+    if( stream->timerID != 0 )

+    {

+        timeKillEvent(stream->timerID);  /* Stop callback timer. */

+        stream->timerID = 0;

+    }

+

+

+    if( stream->bufferProcessor.outputChannelCount > 0 )

+    {

+        // Stop the buffer playback

+        if( stream->pDirectSoundOutputBuffer != NULL )

+        {

+            stream->outputIsRunning = FALSE;

+            // FIXME: what happens if IDirectSoundBuffer_Stop returns an error?

+            hr = IDirectSoundBuffer_Stop( stream->pDirectSoundOutputBuffer );

+        }

+    }

+

+    if( stream->bufferProcessor.inputChannelCount > 0 )

+    {

+        // Stop the buffer capture

+        if( stream->pDirectSoundInputBuffer != NULL )

+        {

+            // FIXME: what happens if IDirectSoundCaptureBuffer_Stop returns an error?

+            hr = IDirectSoundCaptureBuffer_Stop( stream->pDirectSoundInputBuffer );

+        }

+    }

+

+    stream->isStarted = FALSE;

+

+    return result;

+}

+

+

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

+static PaError AbortStream( PaStream *s )

+{

+    PaWinDsStream *stream = (PaWinDsStream*)s;

+

+    stream->abortProcessing = 1;

+    return StopStream( s );

+}

+

+

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

+static PaError IsStreamStopped( PaStream *s )

+{

+    PaWinDsStream *stream = (PaWinDsStream*)s;

+

+    return !stream->isStarted;

+}

+

+

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

+static PaError IsStreamActive( PaStream *s )

+{

+    PaWinDsStream *stream = (PaWinDsStream*)s;

+

+    return stream->isActive;

+}

+

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

+static PaTime GetStreamTime( PaStream *s )

+{

+    /* suppress unused variable warnings */

+    (void) s;

+

+    return PaUtil_GetTime();

+}

+

+

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

+static double GetStreamCpuLoad( PaStream* s )

+{

+    PaWinDsStream *stream = (PaWinDsStream*)s;

+

+    return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );

+}

+

+

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

+    As separate stream interfaces are used for blocking and callback

+    streams, the following functions can be guaranteed to only be called

+    for blocking streams.

+*/

+

+static PaError ReadStream( PaStream* s,

+                           void *buffer,

+                           unsigned long frames )

+{

+    PaWinDsStream *stream = (PaWinDsStream*)s;

+

+    /* suppress unused variable warnings */

+    (void) buffer;

+    (void) frames;

+    (void) stream;

+

+    /* IMPLEMENT ME, see portaudio.h for required behavior*/

+

+    return paNoError;

+}

+

+

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

+static PaError WriteStream( PaStream* s,

+                            const void *buffer,

+                            unsigned long frames )

+{

+    PaWinDsStream *stream = (PaWinDsStream*)s;

+

+    /* suppress unused variable warnings */

+    (void) buffer;

+    (void) frames;

+    (void) stream;

+

+    /* IMPLEMENT ME, see portaudio.h for required behavior*/

+

+    return paNoError;

+}

+

+

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

+static signed long GetStreamReadAvailable( PaStream* s )

+{

+    PaWinDsStream *stream = (PaWinDsStream*)s;

+

+    /* suppress unused variable warnings */

+    (void) stream;

+

+    /* IMPLEMENT ME, see portaudio.h for required behavior*/

+

+    return 0;

+}

+

+

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

+static signed long GetStreamWriteAvailable( PaStream* s )

+{

+    PaWinDsStream *stream = (PaWinDsStream*)s;

+

+    /* suppress unused variable warnings */

+    (void) stream;

+    

+    /* IMPLEMENT ME, see portaudio.h for required behavior*/

+

+    return 0;

+}

+

+

+

diff --git a/src/engine/external/portaudio/pa_win_ds_dynlink.c b/src/engine/external/portaudio/pa_win_ds_dynlink.c
new file mode 100644
index 00000000..f890632a
--- /dev/null
+++ b/src/engine/external/portaudio/pa_win_ds_dynlink.c
@@ -0,0 +1,166 @@
+/*

+ * Interface for dynamically loading directsound and providing a dummy

+ * implementation if it isn't present.

+ *

+ * Author: Ross Bencina (some portions Phil Burk & Robert Marsanyi)

+ *

+ * For PortAudio Portable Real-Time Audio Library

+ * For more information see: http://www.portaudio.com

+ * Copyright (c) 1999-2006 Phil Burk, Robert Marsanyi and Ross Bencina

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/**

+ @file

+ @ingroup hostaip_src

+*/

+

+#include "pa_win_ds_dynlink.h"

+

+PaWinDsDSoundEntryPoints paWinDsDSoundEntryPoints = { 0, 0, 0, 0, 0, 0, 0 };

+

+

+static HRESULT WINAPI DummyDirectSoundCreate(LPGUID lpcGuidDevice, LPDIRECTSOUND *ppDS, LPUNKNOWN pUnkOuter)

+{

+    (void)lpcGuidDevice; /* unused parameter */

+    (void)ppDS; /* unused parameter */

+    (void)pUnkOuter; /* unused parameter */

+    return E_NOTIMPL;

+}

+

+static HRESULT WINAPI DummyDirectSoundEnumerateW(LPDSENUMCALLBACKW lpDSEnumCallback, LPVOID lpContext)

+{

+    (void)lpDSEnumCallback; /* unused parameter */

+    (void)lpContext; /* unused parameter */

+    return E_NOTIMPL;

+}

+

+static HRESULT WINAPI DummyDirectSoundEnumerateA(LPDSENUMCALLBACKA lpDSEnumCallback, LPVOID lpContext)

+{

+    (void)lpDSEnumCallback; /* unused parameter */

+    (void)lpContext; /* unused parameter */

+    return E_NOTIMPL;

+}

+

+static HRESULT WINAPI DummyDirectSoundCaptureCreate(LPGUID lpcGUID, LPDIRECTSOUNDCAPTURE *lplpDSC, LPUNKNOWN pUnkOuter)

+{

+    (void)lpcGUID; /* unused parameter */

+    (void)lplpDSC; /* unused parameter */

+    (void)pUnkOuter; /* unused parameter */

+    return E_NOTIMPL;

+}

+

+static HRESULT WINAPI DummyDirectSoundCaptureEnumerateW(LPDSENUMCALLBACKW lpDSCEnumCallback, LPVOID lpContext)

+{

+    (void)lpDSCEnumCallback; /* unused parameter */

+    (void)lpContext; /* unused parameter */

+    return E_NOTIMPL;

+}

+

+static HRESULT WINAPI DummyDirectSoundCaptureEnumerateA(LPDSENUMCALLBACKA lpDSCEnumCallback, LPVOID lpContext)

+{

+    (void)lpDSCEnumCallback; /* unused parameter */

+    (void)lpContext; /* unused parameter */

+    return E_NOTIMPL;

+}

+

+

+void PaWinDs_InitializeDSoundEntryPoints(void)

+{

+    paWinDsDSoundEntryPoints.hInstance_ = LoadLibrary("dsound.dll");

+    if( paWinDsDSoundEntryPoints.hInstance_ != NULL )

+    {

+        paWinDsDSoundEntryPoints.DirectSoundCreate =

+                (HRESULT (WINAPI *)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN))

+                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCreate" );

+        if( paWinDsDSoundEntryPoints.DirectSoundCreate == NULL )

+            paWinDsDSoundEntryPoints.DirectSoundCreate = DummyDirectSoundCreate;

+

+        paWinDsDSoundEntryPoints.DirectSoundEnumerateW =

+                (HRESULT (WINAPI *)(LPDSENUMCALLBACKW, LPVOID))

+                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundEnumerateW" );

+        if( paWinDsDSoundEntryPoints.DirectSoundEnumerateW == NULL )

+            paWinDsDSoundEntryPoints.DirectSoundEnumerateW = DummyDirectSoundEnumerateW;

+

+        paWinDsDSoundEntryPoints.DirectSoundEnumerateA =

+                (HRESULT (WINAPI *)(LPDSENUMCALLBACKA, LPVOID))

+                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundEnumerateA" );

+        if( paWinDsDSoundEntryPoints.DirectSoundEnumerateA == NULL )

+            paWinDsDSoundEntryPoints.DirectSoundEnumerateA = DummyDirectSoundEnumerateA;

+

+        paWinDsDSoundEntryPoints.DirectSoundCaptureCreate =

+                (HRESULT (WINAPI *)(LPGUID, LPDIRECTSOUNDCAPTURE *, LPUNKNOWN))

+                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCaptureCreate" );

+        if( paWinDsDSoundEntryPoints.DirectSoundCaptureCreate == NULL )

+            paWinDsDSoundEntryPoints.DirectSoundCaptureCreate = DummyDirectSoundCaptureCreate;

+

+        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW =

+                (HRESULT (WINAPI *)(LPDSENUMCALLBACKW, LPVOID))

+                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCaptureEnumerateW" );

+        if( paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW == NULL )

+            paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW = DummyDirectSoundCaptureEnumerateW;

+

+        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA =

+                (HRESULT (WINAPI *)(LPDSENUMCALLBACKA, LPVOID))

+                GetProcAddress( paWinDsDSoundEntryPoints.hInstance_, "DirectSoundCaptureEnumerateA" );

+        if( paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA == NULL )

+            paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA = DummyDirectSoundCaptureEnumerateA;

+    }

+    else

+    {

+        /* initialize with dummy entry points to make live easy when ds isn't present */

+        paWinDsDSoundEntryPoints.DirectSoundCreate = DummyDirectSoundCreate;

+        paWinDsDSoundEntryPoints.DirectSoundEnumerateW = DummyDirectSoundEnumerateW;

+        paWinDsDSoundEntryPoints.DirectSoundEnumerateA = DummyDirectSoundEnumerateA;

+        paWinDsDSoundEntryPoints.DirectSoundCaptureCreate = DummyDirectSoundCaptureCreate;

+        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW = DummyDirectSoundCaptureEnumerateW;

+        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA = DummyDirectSoundCaptureEnumerateA;

+    }

+}

+

+

+void PaWinDs_TerminateDSoundEntryPoints(void)

+{

+    if( paWinDsDSoundEntryPoints.hInstance_ != NULL )

+    {

+        /* ensure that we crash reliably if the entry points arent initialised */

+        paWinDsDSoundEntryPoints.DirectSoundCreate = 0;

+        paWinDsDSoundEntryPoints.DirectSoundEnumerateW = 0;

+        paWinDsDSoundEntryPoints.DirectSoundEnumerateA = 0;

+        paWinDsDSoundEntryPoints.DirectSoundCaptureCreate = 0;

+        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateW = 0;

+        paWinDsDSoundEntryPoints.DirectSoundCaptureEnumerateA = 0;

+

+        FreeLibrary( paWinDsDSoundEntryPoints.hInstance_ );

+        paWinDsDSoundEntryPoints.hInstance_ = NULL;

+    }

+}
\ No newline at end of file
diff --git a/src/engine/external/portaudio/pa_win_ds_dynlink.h b/src/engine/external/portaudio/pa_win_ds_dynlink.h
new file mode 100644
index 00000000..ee7a838d
--- /dev/null
+++ b/src/engine/external/portaudio/pa_win_ds_dynlink.h
@@ -0,0 +1,94 @@
+/*

+ * Interface for dynamically loading directsound and providing a dummy

+ * implementation if it isn't present.

+ *

+ * Author: Ross Bencina (some portions Phil Burk & Robert Marsanyi)

+ *

+ * For PortAudio Portable Real-Time Audio Library

+ * For more information see: http://www.portaudio.com

+ * Copyright (c) 1999-2006 Phil Burk, Robert Marsanyi and Ross Bencina

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/**

+ @file

+ @ingroup hostaip_src

+*/

+

+#ifndef INCLUDED_PA_DSOUND_DYNLINK_H

+#define INCLUDED_PA_DSOUND_DYNLINK_H

+

+/* on Borland compilers, WIN32 doesn't seem to be defined by default, which

+    breaks DSound.h. Adding the define here fixes the problem. - rossb. */

+#ifdef __BORLANDC__

+#if !defined(WIN32)

+#define WIN32

+#endif

+#endif

+

+/*

+  We are only using DX3 in here, no need to polute the namespace - davidv

+*/

+#define DIRECTSOUND_VERSION 0x0300

+

+#include <DSound.h>

+

+#ifdef __cplusplus

+extern "C"

+{

+#endif /* __cplusplus */

+

+

+typedef struct

+{

+    HINSTANCE hInstance_;

+    

+    HRESULT (WINAPI *DirectSoundCreate)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN);

+    HRESULT (WINAPI *DirectSoundEnumerateW)(LPDSENUMCALLBACKW, LPVOID);

+    HRESULT (WINAPI *DirectSoundEnumerateA)(LPDSENUMCALLBACKA, LPVOID);

+

+    HRESULT (WINAPI *DirectSoundCaptureCreate)(LPGUID, LPDIRECTSOUNDCAPTURE *, LPUNKNOWN);

+    HRESULT (WINAPI *DirectSoundCaptureEnumerateW)(LPDSENUMCALLBACKW, LPVOID);

+    HRESULT (WINAPI *DirectSoundCaptureEnumerateA)(LPDSENUMCALLBACKA, LPVOID);

+}PaWinDsDSoundEntryPoints;

+

+extern PaWinDsDSoundEntryPoints paWinDsDSoundEntryPoints;

+

+void PaWinDs_InitializeDSoundEntryPoints(void);

+void PaWinDs_TerminateDSoundEntryPoints(void);

+

+

+#ifdef __cplusplus

+}

+#endif /* __cplusplus */

+

+#endif /* INCLUDED_PA_DSOUND_DYNLINK_H */

diff --git a/src/engine/external/portaudio/pa_win_hostapis.c b/src/engine/external/portaudio/pa_win_hostapis.c
new file mode 100644
index 00000000..e874c206
--- /dev/null
+++ b/src/engine/external/portaudio/pa_win_hostapis.c
@@ -0,0 +1,100 @@
+/*

+ * $Id: pa_win_hostapis.c 1097 2006-08-26 08:27:53Z rossb $

+ * Portable Audio I/O Library Windows initialization table

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup win_src

+

+    Win32 host API initialization function table.

+

+    @todo Consider using PA_USE_WMME etc instead of PA_NO_WMME. This is what

+    the Unix version does, we should consider being consistent.

+*/

+

+

+#include "pa_hostapi.h"

+

+#ifdef __cplusplus

+extern "C"

+{

+#endif /* __cplusplus */

+

+PaError PaSkeleton_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );

+PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );

+PaError PaWinDs_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );

+PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );

+PaError PaWinWdm_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );

+PaError PaWinWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );

+

+#ifdef __cplusplus

+}

+#endif /* __cplusplus */

+

+

+PaUtilHostApiInitializer *paHostApiInitializers[] =

+    {

+

+#ifndef PA_NO_WMME

+        PaWinMme_Initialize,

+#endif

+

+#ifndef PA_NO_DS

+        PaWinDs_Initialize,

+#endif

+

+#ifndef PA_NO_ASIO

+        PaAsio_Initialize,

+#endif

+

+/*

+#ifndef PA_NO_WASAPI

+		PaWinWasapi_Initialize,

+#endif

+

+#ifndef PA_NO_WDMKS

+       PaWinWdm_Initialize,

+#endif

+*/

+

+        //PaSkeleton_Initialize, /* just for testing */

+

+        0   /* NULL terminated array */

+    };

+

+

+int paDefaultHostApiIndex = 0;

+

diff --git a/src/engine/external/portaudio/pa_win_util.c b/src/engine/external/portaudio/pa_win_util.c
new file mode 100644
index 00000000..d9911b42
--- /dev/null
+++ b/src/engine/external/portaudio/pa_win_util.c
@@ -0,0 +1,147 @@
+/*

+ * $Id: pa_win_util.c 1197 2007-05-04 13:07:10Z gordon_gidluck $

+ * Portable Audio I/O Library

+ * Win32 platform-specific support functions

+ *

+ * Based on the Open Source API proposed by Ross Bencina

+ * Copyright (c) 1999-2000 Ross Bencina

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @ingroup win_src

+

+ Win32 platform-specific support functions.

+

+    @todo Implement workaround for QueryPerformanceCounter() skipping forward

+    bug. (see msdn kb Q274323).

+*/

+ 

+#include <windows.h>

+#include <mmsystem.h> /* for timeGetTime() */

+

+#include "pa_util.h"

+

+

+/*

+   Track memory allocations to avoid leaks.

+ */

+

+#if PA_TRACK_MEMORY

+static int numAllocations_ = 0;

+#endif

+

+

+void *PaUtil_AllocateMemory( long size )

+{

+    void *result = GlobalAlloc( GPTR, size );

+

+#if PA_TRACK_MEMORY

+    if( result != NULL ) numAllocations_ += 1;

+#endif

+    return result;

+}

+

+

+void PaUtil_FreeMemory( void *block )

+{

+    if( block != NULL )

+    {

+        GlobalFree( block );

+#if PA_TRACK_MEMORY

+        numAllocations_ -= 1;

+#endif

+

+    }

+}

+

+

+int PaUtil_CountCurrentlyAllocatedBlocks( void )

+{

+#if PA_TRACK_MEMORY

+    return numAllocations_;

+#else

+    return 0;

+#endif

+}

+

+

+void Pa_Sleep( long msec )

+{

+    Sleep( msec );

+}

+

+static int usePerformanceCounter_;

+static double secondsPerTick_;

+

+void PaUtil_InitializeClock( void )

+{

+    LARGE_INTEGER ticksPerSecond;

+

+    if( QueryPerformanceFrequency( &ticksPerSecond ) != 0 )

+    {

+        usePerformanceCounter_ = 1;

+        secondsPerTick_ = 1.0 / (double)ticksPerSecond.QuadPart;

+    }

+    else

+    {

+        usePerformanceCounter_ = 0;

+    }

+}

+

+

+double PaUtil_GetTime( void )

+{

+    LARGE_INTEGER time;

+

+    if( usePerformanceCounter_ )

+    {

+        /* FIXME:

+            according to this knowledge-base article, QueryPerformanceCounter

+            can skip forward by seconds!

+            http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q274323&

+

+            it may be better to use the rtdsc instruction using inline asm,

+            however then a method is needed to calculate a ticks/seconds ratio.

+        */

+        QueryPerformanceCounter( &time );

+        return time.QuadPart * secondsPerTick_;

+    }

+    else

+    {

+#ifndef UNDER_CE    	

+        return timeGetTime() * .001;

+#else

+        return GetTickCount() * .001;

+#endif                

+    }

+}

diff --git a/src/engine/external/portaudio/pablio.c b/src/engine/external/portaudio/pablio.c
new file mode 100644
index 00000000..0685c8d8
--- /dev/null
+++ b/src/engine/external/portaudio/pablio.c
@@ -0,0 +1,314 @@
+/*

+ * $Id: pablio.c 1151 2006-11-29 02:11:16Z leland_lucius $

+ * pablio.c

+ * Portable Audio Blocking Input/Output utility.

+ *

+ * Author: Phil Burk, http://www.softsynth.com

+ *

+ * This program uses the PortAudio Portable Audio Library.

+ * For more information see: http://www.portaudio.com

+ * Copyright (c) 1999-2000 Ross Bencina and Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+#include <stdio.h>

+#include <stdlib.h>

+#include <math.h>

+#include "portaudio.h"

+#include "pa_ringbuffer.h"

+#include "pablio.h"

+#include <string.h>

+

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

+/******** Constants *****************************************************/

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

+

+#define FRAMES_PER_BUFFER    (256)

+

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

+/******** Prototypes ****************************************************/

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

+

+static int blockingIOCallback( void *inputBuffer, void *outputBuffer,

+                               unsigned long framesPerBuffer,

+                               PaTimestamp outTime, void *userData );

+static PaError PABLIO_InitFIFO( RingBuffer *rbuf, long numFrames, long bytesPerFrame );

+static PaError PABLIO_TermFIFO( RingBuffer *rbuf );

+

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

+/******** Functions *****************************************************/

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

+

+/* Called from PortAudio.

+ * Read and write data only if there is room in FIFOs.

+ */

+static int blockingIOCallback( void *inputBuffer, void *outputBuffer,

+                               unsigned long framesPerBuffer,

+                               PaTimestamp outTime, void *userData )

+{

+    PABLIO_Stream *data = (PABLIO_Stream*)userData;

+    long numBytes = data->bytesPerFrame * framesPerBuffer;

+    (void) outTime;

+

+    /* This may get called with NULL inputBuffer during initial setup. */

+    if( inputBuffer != NULL )

+    {

+        PaUtil_WriteRingBuffer( &data->inFIFO, inputBuffer, numBytes );

+    }

+    if( outputBuffer != NULL )

+    {

+        int i;

+        int numRead = PaUtil_ReadRingBuffer( &data->outFIFO, outputBuffer, numBytes );

+        /* Zero out remainder of buffer if we run out of data. */

+        for( i=numRead; i<numBytes; i++ )

+        {

+            ((char *)outputBuffer)[i] = 0;

+        }

+    }

+

+    return 0;

+}

+

+/* Allocate buffer. */

+static PaError PABLIO_InitFIFO( RingBuffer *rbuf, long numFrames, long bytesPerFrame )

+{

+    long numBytes = numFrames * bytesPerFrame;

+    char *buffer = (char *) malloc( numBytes );

+    if( buffer == NULL ) return paInsufficientMemory;

+    memset( buffer, 0, numBytes );

+    return (PaError) PaUtil_InitializeRingBuffer( rbuf, numBytes, buffer );

+}

+

+/* Free buffer. */

+static PaError PABLIO_TermFIFO( RingBuffer *rbuf )

+{

+    if( rbuf->buffer ) free( rbuf->buffer );

+    rbuf->buffer = NULL;

+    return paNoError;

+}

+

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

+ * Write data to ring buffer.

+ * Will not return until all the data has been written.

+ */

+long WriteAudioStream( PABLIO_Stream *aStream, void *data, long numFrames )

+{

+    long bytesWritten;

+    char *p = (char *) data;

+    long numBytes = aStream->bytesPerFrame * numFrames;

+    while( numBytes > 0)

+    {

+        bytesWritten = PaUtil_WriteRingBuffer( &aStream->outFIFO, p, numBytes );

+        numBytes -= bytesWritten;

+        p += bytesWritten;

+        if( numBytes > 0) Pa_Sleep(10);

+    }

+    return numFrames;

+}

+

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

+ * Read data from ring buffer.

+ * Will not return until all the data has been read.

+ */

+long ReadAudioStream( PABLIO_Stream *aStream, void *data, long numFrames )

+{

+    long bytesRead;

+    char *p = (char *) data;

+    long numBytes = aStream->bytesPerFrame * numFrames;

+    while( numBytes > 0)

+    {

+        bytesRead = PaUtil_ReadRingBuffer( &aStream->inFIFO, p, numBytes );

+        numBytes -= bytesRead;

+        p += bytesRead;

+        if( numBytes > 0) Pa_Sleep(10);

+    }

+    return numFrames;

+}

+

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

+ * Return the number of frames that could be written to the stream without

+ * having to wait.

+ */

+long GetAudioStreamWriteable( PABLIO_Stream *aStream )

+{

+    int bytesEmpty = PaUtil_GetRingBufferWriteAvailable( &aStream->outFIFO );

+    return bytesEmpty / aStream->bytesPerFrame;

+}

+

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

+ * Return the number of frames that are available to be read from the

+ * stream without having to wait.

+ */

+long GetAudioStreamReadable( PABLIO_Stream *aStream )

+{

+    int bytesFull = PaUtil_GetRingBufferReadAvailable( &aStream->inFIFO );

+    return bytesFull / aStream->bytesPerFrame;

+}

+

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

+static unsigned long RoundUpToNextPowerOf2( unsigned long n )

+{

+    long numBits = 0;

+    if( ((n-1) & n) == 0) return n; /* Already Power of two. */

+    while( n > 0 )

+    {

+        n= n>>1;

+        numBits++;

+    }

+    return (1<<numBits);

+}

+

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

+ * Opens a PortAudio stream with default characteristics.

+ * Allocates PABLIO_Stream structure.

+ *

+ * flags parameter can be an ORed combination of:

+ *    PABLIO_READ, PABLIO_WRITE, or PABLIO_READ_WRITE,

+ *    and either PABLIO_MONO or PABLIO_STEREO

+ */

+PaError OpenAudioStream( PABLIO_Stream **rwblPtr, double sampleRate,

+                         PaSampleFormat format, long flags )

+{

+    long   bytesPerSample;

+    long   doRead = 0;

+    long   doWrite = 0;

+    PaError err;

+    PABLIO_Stream *aStream;

+    long   minNumBuffers;

+    long   numFrames;

+

+    /* Allocate PABLIO_Stream structure for caller. */

+    aStream = (PABLIO_Stream *) malloc( sizeof(PABLIO_Stream) );

+    if( aStream == NULL ) return paInsufficientMemory;

+    memset( aStream, 0, sizeof(PABLIO_Stream) );

+

+    /* Determine size of a sample. */

+    bytesPerSample = Pa_GetSampleSize( format );

+    if( bytesPerSample < 0 )

+    {

+        err = (PaError) bytesPerSample;

+        goto error;

+    }

+    aStream->samplesPerFrame = ((flags&PABLIO_MONO) != 0) ? 1 : 2;

+    aStream->bytesPerFrame = bytesPerSample * aStream->samplesPerFrame;

+

+    /* Initialize PortAudio  */

+    err = Pa_Initialize();

+    if( err != paNoError ) goto error;

+

+    /* Warning: numFrames must be larger than amount of data processed per interrupt

+     *    inside PA to prevent glitches. Just to be safe, adjust size upwards.

+     */

+    minNumBuffers = 2 * Pa_GetMinNumBuffers( FRAMES_PER_BUFFER, sampleRate );

+    numFrames = minNumBuffers * FRAMES_PER_BUFFER;

+    numFrames = RoundUpToNextPowerOf2( numFrames );

+

+    /* Initialize Ring Buffers */

+    doRead = ((flags & PABLIO_READ) != 0);

+    doWrite = ((flags & PABLIO_WRITE) != 0);

+    if(doRead)

+    {

+        err = PABLIO_InitFIFO( &aStream->inFIFO, numFrames, aStream->bytesPerFrame );

+        if( err != paNoError ) goto error;

+    }

+    if(doWrite)

+    {

+        long numBytes;

+        err = PABLIO_InitFIFO( &aStream->outFIFO, numFrames, aStream->bytesPerFrame );

+        if( err != paNoError ) goto error;

+        /* Make Write FIFO appear full initially. */

+        numBytes = PaUtil_GetRingBufferWriteAvailable( &aStream->outFIFO );

+        PaUtil_AdvanceRingBufferWriteIndex( &aStream->outFIFO, numBytes );

+    }

+

+    /* Open a PortAudio stream that we will use to communicate with the underlying

+     * audio drivers. */

+    err = Pa_OpenStream(

+              &aStream->stream,

+              (doRead ? Pa_GetDefaultInputDeviceID() : paNoDevice),

+              (doRead ? aStream->samplesPerFrame : 0 ),

+              format,

+              NULL,

+              (doWrite ? Pa_GetDefaultOutputDeviceID() : paNoDevice),

+              (doWrite ? aStream->samplesPerFrame : 0 ),

+              format,

+              NULL,

+              sampleRate,

+              FRAMES_PER_BUFFER,

+              minNumBuffers,

+              paClipOff,       /* we won't output out of range samples so don't bother clipping them */

+              blockingIOCallback,

+              aStream );

+    if( err != paNoError ) goto error;

+

+    err = Pa_StartStream( aStream->stream );

+    if( err != paNoError ) goto error;

+

+    *rwblPtr = aStream;

+    return paNoError;

+

+error:

+    CloseAudioStream( aStream );

+    *rwblPtr = NULL;

+    return err;

+}

+

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

+PaError CloseAudioStream( PABLIO_Stream *aStream )

+{

+    PaError err;

+    int bytesEmpty;

+    int byteSize = aStream->outFIFO.bufferSize;

+

+    /* If we are writing data, make sure we play everything written. */

+    if( byteSize > 0 )

+    {

+        bytesEmpty = PaUtil_GetRingBufferWriteAvailable( &aStream->outFIFO );

+        while( bytesEmpty < byteSize )

+        {

+            Pa_Sleep( 10 );

+            bytesEmpty = PaUtil_GetRingBufferWriteAvailable( &aStream->outFIFO );

+        }

+    }

+

+    err = Pa_StopStream( aStream->stream );

+    if( err != paNoError ) goto error;

+    err = Pa_CloseStream( aStream->stream );

+    if( err != paNoError ) goto error;

+    Pa_Terminate();

+

+error:

+    PABLIO_TermFIFO( &aStream->inFIFO );

+    PABLIO_TermFIFO( &aStream->outFIFO );

+    free( aStream );

+    return err;

+}

diff --git a/src/engine/external/portaudio/pablio.h b/src/engine/external/portaudio/pablio.h
new file mode 100644
index 00000000..81a63886
--- /dev/null
+++ b/src/engine/external/portaudio/pablio.h
@@ -0,0 +1,116 @@
+#ifndef _PABLIO_H

+#define _PABLIO_H

+

+#ifdef __cplusplus

+extern "C"

+{

+#endif /* __cplusplus */

+

+/*

+ * $Id: pablio.h 1083 2006-08-23 07:30:49Z rossb $

+ * PABLIO.h

+ * Portable Audio Blocking read/write utility.

+ *

+ * Author: Phil Burk, http://www.softsynth.com/portaudio/

+ *

+ * Include file for PABLIO, the Portable Audio Blocking I/O Library.

+ * PABLIO is built on top of PortAudio, the Portable Audio Library.

+ * For more information see: http://www.portaudio.com

+ * Copyright (c) 1999-2000 Ross Bencina and Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+#include <stdio.h>

+#include <stdlib.h>

+#include <math.h>

+#include "portaudio.h"

+#include "ringbuffer.h"

+#include <string.h>

+

+typedef struct

+{

+    RingBuffer   inFIFO;

+    RingBuffer   outFIFO;

+    PortAudioStream *stream;

+    int          bytesPerFrame;

+    int          samplesPerFrame;

+}

+PABLIO_Stream;

+

+/* Values for flags for OpenAudioStream(). */

+#define PABLIO_READ     (1<<0)

+#define PABLIO_WRITE    (1<<1)

+#define PABLIO_READ_WRITE    (PABLIO_READ|PABLIO_WRITE)

+#define PABLIO_MONO     (1<<2)

+#define PABLIO_STEREO   (1<<3)

+

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

+ * Write data to ring buffer.

+ * Will not return until all the data has been written.

+ */

+long WriteAudioStream( PABLIO_Stream *aStream, void *data, long numFrames );

+

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

+ * Read data from ring buffer.

+ * Will not return until all the data has been read.

+ */

+long ReadAudioStream( PABLIO_Stream *aStream, void *data, long numFrames );

+

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

+ * Return the number of frames that could be written to the stream without

+ * having to wait.

+ */

+long GetAudioStreamWriteable( PABLIO_Stream *aStream );

+

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

+ * Return the number of frames that are available to be read from the

+ * stream without having to wait.

+ */

+long GetAudioStreamReadable( PABLIO_Stream *aStream );

+

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

+ * Opens a PortAudio stream with default characteristics.

+ * Allocates PABLIO_Stream structure.

+ *

+ * flags parameter can be an ORed combination of:

+ *    PABLIO_READ, PABLIO_WRITE, or PABLIO_READ_WRITE,

+ *    and either PABLIO_MONO or PABLIO_STEREO

+ */

+PaError OpenAudioStream( PABLIO_Stream **aStreamPtr, double sampleRate,

+                         PaSampleFormat format, long flags );

+

+PaError CloseAudioStream( PABLIO_Stream *aStream );

+

+#ifdef __cplusplus

+}

+#endif /* __cplusplus */

+#endif /* _PABLIO_H */

diff --git a/src/engine/external/portaudio/portaudio.h b/src/engine/external/portaudio/portaudio.h
new file mode 100644
index 00000000..71f0e3d6
--- /dev/null
+++ b/src/engine/external/portaudio/portaudio.h
@@ -0,0 +1,1134 @@
+

+#ifndef PORTAUDIO_H

+#define PORTAUDIO_H

+/*

+ * $Id: portaudio.h 1195 2007-04-22 17:34:45Z aknudsen $

+ * PortAudio Portable Real-Time Audio Library

+ * PortAudio API Header File

+ * Latest version available at: http://www.portaudio.com/

+ *

+ * Copyright (c) 1999-2002 Ross Bencina and Phil Burk

+ *

+ * Permission is hereby granted, free of charge, to any person obtaining

+ * a copy of this software and associated documentation files

+ * (the "Software"), to deal in the Software without restriction,

+ * including without limitation the rights to use, copy, modify, merge,

+ * publish, distribute, sublicense, and/or sell copies of the Software,

+ * and to permit persons to whom the Software is furnished to do so,

+ * subject to the following conditions:

+ *

+ * The above copyright notice and this permission notice shall be

+ * included in all copies or substantial portions of the Software.

+ *

+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,

+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF

+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.

+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR

+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF

+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ */

+

+/*

+ * The text above constitutes the entire PortAudio license; however, 

+ * the PortAudio community also makes the following non-binding requests:

+ *

+ * Any person wishing to distribute modifications to the Software is

+ * requested to send the modifications to the original developer so that

+ * they can be incorporated into the canonical version. It is also 

+ * requested that these non-binding requests be included along with the 

+ * license above.

+ */

+

+/** @file

+ @brief The PortAudio API.

+*/

+

+

+#ifdef __cplusplus

+extern "C"

+{

+#endif /* __cplusplus */

+

+ 

+/** Retrieve the release number of the currently running PortAudio build,

+ eg 1900.

+*/

+int Pa_GetVersion( void );

+

+

+/** Retrieve a textual description of the current PortAudio build,

+ eg "PortAudio V19-devel 13 October 2002".

+*/

+const char* Pa_GetVersionText( void );

+

+

+/** Error codes returned by PortAudio functions.

+ Note that with the exception of paNoError, all PaErrorCodes are negative.

+*/

+

+typedef int PaError;

+typedef enum PaErrorCode

+{

+    paNoError = 0,

+

+    paNotInitialized = -10000,

+    paUnanticipatedHostError,

+    paInvalidChannelCount,

+    paInvalidSampleRate,

+    paInvalidDevice,

+    paInvalidFlag,

+    paSampleFormatNotSupported,

+    paBadIODeviceCombination,

+    paInsufficientMemory,

+    paBufferTooBig,

+    paBufferTooSmall,

+    paNullCallback,

+    paBadStreamPtr,

+    paTimedOut,

+    paInternalError,

+    paDeviceUnavailable,

+    paIncompatibleHostApiSpecificStreamInfo,

+    paStreamIsStopped,

+    paStreamIsNotStopped,

+    paInputOverflowed,

+    paOutputUnderflowed,

+    paHostApiNotFound,

+    paInvalidHostApi,

+    paCanNotReadFromACallbackStream,      /**< @todo review error code name */

+    paCanNotWriteToACallbackStream,       /**< @todo review error code name */

+    paCanNotReadFromAnOutputOnlyStream,   /**< @todo review error code name */

+    paCanNotWriteToAnInputOnlyStream,     /**< @todo review error code name */

+    paIncompatibleStreamHostApi,

+    paBadBufferPtr

+} PaErrorCode;

+

+

+/** Translate the supplied PortAudio error code into a human readable

+ message.

+*/

+const char *Pa_GetErrorText( PaError errorCode );

+

+

+/** Library initialization function - call this before using PortAudio.

+ This function initialises internal data structures and prepares underlying

+ host APIs for use.  With the exception of Pa_GetVersion(), Pa_GetVersionText(),

+ and Pa_GetErrorText(), this function MUST be called before using any other

+ PortAudio API functions.

+

+ If Pa_Initialize() is called multiple times, each successful 

+ call must be matched with a corresponding call to Pa_Terminate(). 

+ Pairs of calls to Pa_Initialize()/Pa_Terminate() may overlap, and are not 

+ required to be fully nested.

+

+ Note that if Pa_Initialize() returns an error code, Pa_Terminate() should

+ NOT be called.

+

+ @return paNoError if successful, otherwise an error code indicating the cause

+ of failure.

+

+ @see Pa_Terminate

+*/

+PaError Pa_Initialize( void );

+

+

+/** Library termination function - call this when finished using PortAudio.

+ This function deallocates all resources allocated by PortAudio since it was

+ initializied by a call to Pa_Initialize(). In cases where Pa_Initialise() has

+ been called multiple times, each call must be matched with a corresponding call

+ to Pa_Terminate(). The final matching call to Pa_Terminate() will automatically

+ close any PortAudio streams that are still open.

+

+ Pa_Terminate() MUST be called before exiting a program which uses PortAudio.

+ Failure to do so may result in serious resource leaks, such as audio devices

+ not being available until the next reboot.

+

+ @return paNoError if successful, otherwise an error code indicating the cause

+ of failure.

+ 

+ @see Pa_Initialize

+*/

+PaError Pa_Terminate( void );

+

+

+

+/** The type used to refer to audio devices. Values of this type usually

+ range from 0 to (Pa_GetDeviceCount()-1), and may also take on the PaNoDevice

+ and paUseHostApiSpecificDeviceSpecification values.

+

+ @see Pa_GetDeviceCount, paNoDevice, paUseHostApiSpecificDeviceSpecification

+*/

+typedef int PaDeviceIndex;

+

+

+/** A special PaDeviceIndex value indicating that no device is available,

+ or should be used.

+

+ @see PaDeviceIndex

+*/

+#define paNoDevice ((PaDeviceIndex)-1)

+

+

+/** A special PaDeviceIndex value indicating that the device(s) to be used

+ are specified in the host api specific stream info structure.

+

+ @see PaDeviceIndex

+*/

+#define paUseHostApiSpecificDeviceSpecification ((PaDeviceIndex)-2)

+

+

+/* Host API enumeration mechanism */

+

+/** The type used to enumerate to host APIs at runtime. Values of this type

+ range from 0 to (Pa_GetHostApiCount()-1).

+

+ @see Pa_GetHostApiCount

+*/

+typedef int PaHostApiIndex;

+

+

+/** Retrieve the number of available host APIs. Even if a host API is

+ available it may have no devices available.

+

+ @return A non-negative value indicating the number of available host APIs

+ or, a PaErrorCode (which are always negative) if PortAudio is not initialized

+ or an error is encountered.

+

+ @see PaHostApiIndex

+*/

+PaHostApiIndex Pa_GetHostApiCount( void );

+

+

+/** Retrieve the index of the default host API. The default host API will be

+ the lowest common denominator host API on the current platform and is

+ unlikely to provide the best performance.

+

+ @return A non-negative value ranging from 0 to (Pa_GetHostApiCount()-1)

+ indicating the default host API index or, a PaErrorCode (which are always

+ negative) if PortAudio is not initialized or an error is encountered.

+*/

+PaHostApiIndex Pa_GetDefaultHostApi( void );

+

+

+/** Unchanging unique identifiers for each supported host API. This type

+ is used in the PaHostApiInfo structure. The values are guaranteed to be

+ unique and to never change, thus allowing code to be written that

+ conditionally uses host API specific extensions.

+

+ New type ids will be allocated when support for a host API reaches

+ "public alpha" status, prior to that developers should use the

+ paInDevelopment type id.

+

+ @see PaHostApiInfo

+*/

+typedef enum PaHostApiTypeId

+{

+    paInDevelopment=0, /* use while developing support for a new host API */

+    paDirectSound=1,

+    paMME=2,

+    paASIO=3,

+    paSoundManager=4,

+    paCoreAudio=5,

+    paOSS=7,

+    paALSA=8,

+    paAL=9,

+    paBeOS=10,

+    paWDMKS=11,

+    paJACK=12,

+    paWASAPI=13,

+    paAudioScienceHPI=14

+} PaHostApiTypeId;

+

+

+/** A structure containing information about a particular host API. */

+

+typedef struct PaHostApiInfo

+{

+    /** this is struct version 1 */

+    int structVersion;

+    /** The well known unique identifier of this host API @see PaHostApiTypeId */

+    PaHostApiTypeId type;

+    /** A textual description of the host API for display on user interfaces. */

+    const char *name;

+

+    /**  The number of devices belonging to this host API. This field may be

+     used in conjunction with Pa_HostApiDeviceIndexToDeviceIndex() to enumerate

+     all devices for this host API.

+     @see Pa_HostApiDeviceIndexToDeviceIndex

+    */

+    int deviceCount;

+

+    /** The default input device for this host API. The value will be a

+     device index ranging from 0 to (Pa_GetDeviceCount()-1), or paNoDevice

+     if no default input device is available.

+    */

+    PaDeviceIndex defaultInputDevice;

+

+    /** The default output device for this host API. The value will be a

+     device index ranging from 0 to (Pa_GetDeviceCount()-1), or paNoDevice

+     if no default output device is available.

+    */

+    PaDeviceIndex defaultOutputDevice;

+    

+} PaHostApiInfo;

+

+

+/** Retrieve a pointer to a structure containing information about a specific

+ host Api.

+

+ @param hostApi A valid host API index ranging from 0 to (Pa_GetHostApiCount()-1)

+

+ @return A pointer to an immutable PaHostApiInfo structure describing

+ a specific host API. If the hostApi parameter is out of range or an error

+ is encountered, the function returns NULL.

+

+ The returned structure is owned by the PortAudio implementation and must not

+ be manipulated or freed. The pointer is only guaranteed to be valid between

+ calls to Pa_Initialize() and Pa_Terminate().

+*/

+const PaHostApiInfo * Pa_GetHostApiInfo( PaHostApiIndex hostApi );

+

+

+/** Convert a static host API unique identifier, into a runtime

+ host API index.

+

+ @param type A unique host API identifier belonging to the PaHostApiTypeId

+ enumeration.

+

+ @return A valid PaHostApiIndex ranging from 0 to (Pa_GetHostApiCount()-1) or,

+ a PaErrorCode (which are always negative) if PortAudio is not initialized

+ or an error is encountered.

+ 

+ The paHostApiNotFound error code indicates that the host API specified by the

+ type parameter is not available.

+

+ @see PaHostApiTypeId

+*/

+PaHostApiIndex Pa_HostApiTypeIdToHostApiIndex( PaHostApiTypeId type );

+

+

+/** Convert a host-API-specific device index to standard PortAudio device index.

+ This function may be used in conjunction with the deviceCount field of

+ PaHostApiInfo to enumerate all devices for the specified host API.

+

+ @param hostApi A valid host API index ranging from 0 to (Pa_GetHostApiCount()-1)

+

+ @param hostApiDeviceIndex A valid per-host device index in the range

+ 0 to (Pa_GetHostApiInfo(hostApi)->deviceCount-1)

+

+ @return A non-negative PaDeviceIndex ranging from 0 to (Pa_GetDeviceCount()-1)

+ or, a PaErrorCode (which are always negative) if PortAudio is not initialized

+ or an error is encountered.

+

+ A paInvalidHostApi error code indicates that the host API index specified by

+ the hostApi parameter is out of range.

+

+ A paInvalidDevice error code indicates that the hostApiDeviceIndex parameter

+ is out of range.

+ 

+ @see PaHostApiInfo

+*/

+PaDeviceIndex Pa_HostApiDeviceIndexToDeviceIndex( PaHostApiIndex hostApi,

+        int hostApiDeviceIndex );

+

+

+

+/** Structure used to return information about a host error condition.

+*/

+typedef struct PaHostErrorInfo{

+    PaHostApiTypeId hostApiType;    /**< the host API which returned the error code */

+    long errorCode;                 /**< the error code returned */

+    const char *errorText;          /**< a textual description of the error if available, otherwise a zero-length string */

+}PaHostErrorInfo;

+

+

+/** Return information about the last host error encountered. The error

+ information returned by Pa_GetLastHostErrorInfo() will never be modified

+ asyncronously by errors occurring in other PortAudio owned threads

+ (such as the thread that manages the stream callback.)

+

+ This function is provided as a last resort, primarily to enhance debugging

+ by providing clients with access to all available error information.

+

+ @return A pointer to an immutable structure constaining information about

+ the host error. The values in this structure will only be valid if a

+ PortAudio function has previously returned the paUnanticipatedHostError

+ error code.

+*/

+const PaHostErrorInfo* Pa_GetLastHostErrorInfo( void );

+

+

+

+/* Device enumeration and capabilities */

+

+/** Retrieve the number of available devices. The number of available devices

+ may be zero.

+

+ @return A non-negative value indicating the number of available devices or,

+ a PaErrorCode (which are always negative) if PortAudio is not initialized

+ or an error is encountered.

+*/

+PaDeviceIndex Pa_GetDeviceCount( void );

+

+

+/** Retrieve the index of the default input device. The result can be

+ used in the inputDevice parameter to Pa_OpenStream().

+

+ @return The default input device index for the default host API, or paNoDevice

+ if no default input device is available or an error was encountered.

+*/

+PaDeviceIndex Pa_GetDefaultInputDevice( void );

+

+

+/** Retrieve the index of the default output device. The result can be

+ used in the outputDevice parameter to Pa_OpenStream().

+

+ @return The default output device index for the defualt host API, or paNoDevice

+ if no default output device is available or an error was encountered.

+

+ @note

+ On the PC, the user can specify a default device by

+ setting an environment variable. For example, to use device #1.

+<pre>

+ set PA_RECOMMENDED_OUTPUT_DEVICE=1

+</pre>

+ The user should first determine the available device ids by using

+ the supplied application "pa_devs".

+*/

+PaDeviceIndex Pa_GetDefaultOutputDevice( void );

+

+

+/** The type used to represent monotonic time in seconds that can be used

+ for syncronisation. The type is used for the outTime argument to the

+ PaStreamCallback and as the result of Pa_GetStreamTime().

+     

+ @see PaStreamCallback, Pa_GetStreamTime

+*/

+typedef double PaTime;

+

+

+/** A type used to specify one or more sample formats. Each value indicates

+ a possible format for sound data passed to and from the stream callback,

+ Pa_ReadStream and Pa_WriteStream.

+

+ The standard formats paFloat32, paInt16, paInt32, paInt24, paInt8

+ and aUInt8 are usually implemented by all implementations.

+

+ The floating point representation (paFloat32) uses +1.0 and -1.0 as the

+ maximum and minimum respectively.

+

+ paUInt8 is an unsigned 8 bit format where 128 is considered "ground"

+

+ The paNonInterleaved flag indicates that a multichannel buffer is passed

+ as a set of non-interleaved pointers.

+

+ @see Pa_OpenStream, Pa_OpenDefaultStream, PaDeviceInfo

+ @see paFloat32, paInt16, paInt32, paInt24, paInt8

+ @see paUInt8, paCustomFormat, paNonInterleaved

+*/

+typedef unsigned long PaSampleFormat;

+

+

+#define paFloat32        ((PaSampleFormat) 0x00000001) /**< @see PaSampleFormat */

+#define paInt32          ((PaSampleFormat) 0x00000002) /**< @see PaSampleFormat */

+#define paInt24          ((PaSampleFormat) 0x00000004) /**< Packed 24 bit format. @see PaSampleFormat */

+#define paInt16          ((PaSampleFormat) 0x00000008) /**< @see PaSampleFormat */

+#define paInt8           ((PaSampleFormat) 0x00000010) /**< @see PaSampleFormat */

+#define paUInt8          ((PaSampleFormat) 0x00000020) /**< @see PaSampleFormat */

+#define paCustomFormat   ((PaSampleFormat) 0x00010000)/**< @see PaSampleFormat */

+

+#define paNonInterleaved ((PaSampleFormat) 0x80000000)

+

+/** A structure providing information and capabilities of PortAudio devices.

+ Devices may support input, output or both input and output.

+*/

+typedef struct PaDeviceInfo

+{

+    int structVersion;  /* this is struct version 2 */

+    const char *name;

+    PaHostApiIndex hostApi; /* note this is a host API index, not a type id*/

+    

+    int maxInputChannels;

+    int maxOutputChannels;

+

+    /* Default latency values for interactive performance. */

+    PaTime defaultLowInputLatency;

+    PaTime defaultLowOutputLatency;

+    /* Default latency values for robust non-interactive applications (eg. playing sound files). */

+    PaTime defaultHighInputLatency;

+    PaTime defaultHighOutputLatency;

+

+    double defaultSampleRate;

+} PaDeviceInfo;

+

+

+/** Retrieve a pointer to a PaDeviceInfo structure containing information

+ about the specified device.

+ @return A pointer to an immutable PaDeviceInfo structure. If the device

+ parameter is out of range the function returns NULL.

+

+ @param device A valid device index in the range 0 to (Pa_GetDeviceCount()-1)

+

+ @note PortAudio manages the memory referenced by the returned pointer,

+ the client must not manipulate or free the memory. The pointer is only

+ guaranteed to be valid between calls to Pa_Initialize() and Pa_Terminate().

+

+ @see PaDeviceInfo, PaDeviceIndex

+*/

+const PaDeviceInfo* Pa_GetDeviceInfo( PaDeviceIndex device );

+

+

+/** Parameters for one direction (input or output) of a stream.

+*/

+typedef struct PaStreamParameters

+{

+    /** A valid device index in the range 0 to (Pa_GetDeviceCount()-1)

+     specifying the device to be used or the special constant

+     paUseHostApiSpecificDeviceSpecification which indicates that the actual

+     device(s) to use are specified in hostApiSpecificStreamInfo.

+     This field must not be set to paNoDevice.

+    */

+    PaDeviceIndex device;

+    

+    /** The number of channels of sound to be delivered to the

+     stream callback or accessed by Pa_ReadStream() or Pa_WriteStream().

+     It can range from 1 to the value of maxInputChannels in the

+     PaDeviceInfo record for the device specified by the device parameter.

+    */

+    int channelCount;

+

+    /** The sample format of the buffer provided to the stream callback,

+     a_ReadStream() or Pa_WriteStream(). It may be any of the formats described

+     by the PaSampleFormat enumeration.

+    */

+    PaSampleFormat sampleFormat;

+

+    /** The desired latency in seconds. Where practical, implementations should

+     configure their latency based on these parameters, otherwise they may

+     choose the closest viable latency instead. Unless the suggested latency

+     is greater than the absolute upper limit for the device implementations

+     should round the suggestedLatency up to the next practial value - ie to

+     provide an equal or higher latency than suggestedLatency wherever possibe.

+     Actual latency values for an open stream may be retrieved using the

+     inputLatency and outputLatency fields of the PaStreamInfo structure

+     returned by Pa_GetStreamInfo().

+     @see default*Latency in PaDeviceInfo, *Latency in PaStreamInfo

+    */

+    PaTime suggestedLatency;

+

+    /** An optional pointer to a host api specific data structure

+     containing additional information for device setup and/or stream processing.

+     hostApiSpecificStreamInfo is never required for correct operation,

+     if not used it should be set to NULL.

+    */

+    void *hostApiSpecificStreamInfo;

+

+} PaStreamParameters;

+

+

+/** Return code for Pa_IsFormatSupported indicating success. */

+#define paFormatIsSupported (0)

+

+/** Determine whether it would be possible to open a stream with the specified

+ parameters.

+

+ @param inputParameters A structure that describes the input parameters used to

+ open a stream. The suggestedLatency field is ignored. See PaStreamParameters

+ for a description of these parameters. inputParameters must be NULL for

+ output-only streams.

+

+ @param outputParameters A structure that describes the output parameters used

+ to open a stream. The suggestedLatency field is ignored. See PaStreamParameters

+ for a description of these parameters. outputParameters must be NULL for

+ input-only streams.

+

+ @param sampleRate The required sampleRate. For full-duplex streams it is the

+ sample rate for both input and output

+

+ @return Returns 0 if the format is supported, and an error code indicating why

+ the format is not supported otherwise. The constant paFormatIsSupported is

+ provided to compare with the return value for success.

+

+ @see paFormatIsSupported, PaStreamParameters

+*/

+PaError Pa_IsFormatSupported( const PaStreamParameters *inputParameters,

+                              const PaStreamParameters *outputParameters,

+                              double sampleRate );

+

+

+

+/* Streaming types and functions */

+

+

+/**

+ A single PaStream can provide multiple channels of real-time

+ streaming audio input and output to a client application. A stream

+ provides access to audio hardware represented by one or more

+ PaDevices. Depending on the underlying Host API, it may be possible 

+ to open multiple streams using the same device, however this behavior 

+ is implementation defined. Portable applications should assume that 

+ a PaDevice may be simultaneously used by at most one PaStream.

+

+ Pointers to PaStream objects are passed between PortAudio functions that

+ operate on streams.

+

+ @see Pa_OpenStream, Pa_OpenDefaultStream, Pa_OpenDefaultStream, Pa_CloseStream,

+ Pa_StartStream, Pa_StopStream, Pa_AbortStream, Pa_IsStreamActive,

+ Pa_GetStreamTime, Pa_GetStreamCpuLoad

+

+*/

+typedef void PaStream;

+

+

+/** Can be passed as the framesPerBuffer parameter to Pa_OpenStream()

+ or Pa_OpenDefaultStream() to indicate that the stream callback will

+ accept buffers of any size.

+*/

+#define paFramesPerBufferUnspecified  (0)

+

+

+/** Flags used to control the behavior of a stream. They are passed as

+ parameters to Pa_OpenStream or Pa_OpenDefaultStream. Multiple flags may be

+ ORed together.

+

+ @see Pa_OpenStream, Pa_OpenDefaultStream

+ @see paNoFlag, paClipOff, paDitherOff, paNeverDropInput,

+  paPrimeOutputBuffersUsingStreamCallback, paPlatformSpecificFlags

+*/

+typedef unsigned long PaStreamFlags;

+

+/** @see PaStreamFlags */

+#define   paNoFlag          ((PaStreamFlags) 0)

+

+/** Disable default clipping of out of range samples.

+ @see PaStreamFlags

+*/

+#define   paClipOff         ((PaStreamFlags) 0x00000001)

+

+/** Disable default dithering.

+ @see PaStreamFlags

+*/

+#define   paDitherOff       ((PaStreamFlags) 0x00000002)

+

+/** Flag requests that where possible a full duplex stream will not discard

+ overflowed input samples without calling the stream callback. This flag is

+ only valid for full duplex callback streams and only when used in combination

+ with the paFramesPerBufferUnspecified (0) framesPerBuffer parameter. Using

+ this flag incorrectly results in a paInvalidFlag error being returned from

+ Pa_OpenStream and Pa_OpenDefaultStream.

+

+ @see PaStreamFlags, paFramesPerBufferUnspecified

+*/

+#define   paNeverDropInput  ((PaStreamFlags) 0x00000004)

+

+/** Call the stream callback to fill initial output buffers, rather than the

+ default behavior of priming the buffers with zeros (silence). This flag has

+ no effect for input-only and blocking read/write streams.

+ 

+ @see PaStreamFlags

+*/

+#define   paPrimeOutputBuffersUsingStreamCallback ((PaStreamFlags) 0x00000008)

+

+/** A mask specifying the platform specific bits.

+ @see PaStreamFlags

+*/

+#define   paPlatformSpecificFlags ((PaStreamFlags)0xFFFF0000)

+

+/**

+ Timing information for the buffers passed to the stream callback.

+*/

+typedef struct PaStreamCallbackTimeInfo{

+    PaTime inputBufferAdcTime;

+    PaTime currentTime;

+    PaTime outputBufferDacTime;

+} PaStreamCallbackTimeInfo;

+

+

+/**

+ Flag bit constants for the statusFlags to PaStreamCallback.

+

+ @see paInputUnderflow, paInputOverflow, paOutputUnderflow, paOutputOverflow,

+ paPrimingOutput

+*/

+typedef unsigned long PaStreamCallbackFlags;

+

+/** In a stream opened with paFramesPerBufferUnspecified, indicates that

+ input data is all silence (zeros) because no real data is available. In a

+ stream opened without paFramesPerBufferUnspecified, it indicates that one or

+ more zero samples have been inserted into the input buffer to compensate

+ for an input underflow.

+ @see PaStreamCallbackFlags

+*/

+#define paInputUnderflow   ((PaStreamCallbackFlags) 0x00000001)

+

+/** In a stream opened with paFramesPerBufferUnspecified, indicates that data

+ prior to the first sample of the input buffer was discarded due to an

+ overflow, possibly because the stream callback is using too much CPU time.

+ Otherwise indicates that data prior to one or more samples in the

+ input buffer was discarded.

+ @see PaStreamCallbackFlags

+*/

+#define paInputOverflow    ((PaStreamCallbackFlags) 0x00000002)

+

+/** Indicates that output data (or a gap) was inserted, possibly because the

+ stream callback is using too much CPU time.

+ @see PaStreamCallbackFlags

+*/

+#define paOutputUnderflow  ((PaStreamCallbackFlags) 0x00000004)

+

+/** Indicates that output data will be discarded because no room is available.

+ @see PaStreamCallbackFlags

+*/

+#define paOutputOverflow   ((PaStreamCallbackFlags) 0x00000008)

+

+/** Some of all of the output data will be used to prime the stream, input

+ data may be zero.

+ @see PaStreamCallbackFlags

+*/

+#define paPrimingOutput    ((PaStreamCallbackFlags) 0x00000010)

+

+/**

+ Allowable return values for the PaStreamCallback.

+ @see PaStreamCallback

+*/

+typedef enum PaStreamCallbackResult

+{

+    paContinue=0,

+    paComplete=1,

+    paAbort=2

+} PaStreamCallbackResult;

+

+

+/**

+ Functions of type PaStreamCallback are implemented by PortAudio clients.

+ They consume, process or generate audio in response to requests from an

+ active PortAudio stream.

+     

+ @param input and @param output are arrays of interleaved samples,

+ the format, packing and number of channels used by the buffers are

+ determined by parameters to Pa_OpenStream().

+     

+ @param frameCount The number of sample frames to be processed by

+ the stream callback.

+

+ @param timeInfo The time in seconds when the first sample of the input

+ buffer was received at the audio input, the time in seconds when the first

+ sample of the output buffer will begin being played at the audio output, and

+ the time in seconds when the stream callback was called.

+ See also Pa_GetStreamTime()

+

+ @param statusFlags Flags indicating whether input and/or output buffers

+ have been inserted or will be dropped to overcome underflow or overflow

+ conditions.

+

+ @param userData The value of a user supplied pointer passed to

+ Pa_OpenStream() intended for storing synthesis data etc.

+

+ @return

+ The stream callback should return one of the values in the

+ PaStreamCallbackResult enumeration. To ensure that the callback continues

+ to be called, it should return paContinue (0). Either paComplete or paAbort

+ can be returned to finish stream processing, after either of these values is

+ returned the callback will not be called again. If paAbort is returned the

+ stream will finish as soon as possible. If paComplete is returned, the stream

+ will continue until all buffers generated by the callback have been played.

+ This may be useful in applications such as soundfile players where a specific

+ duration of output is required. However, it is not necessary to utilise this

+ mechanism as Pa_StopStream(), Pa_AbortStream() or Pa_CloseStream() can also

+ be used to stop the stream. The callback must always fill the entire output

+ buffer irrespective of its return value.

+

+ @see Pa_OpenStream, Pa_OpenDefaultStream

+

+ @note With the exception of Pa_GetStreamCpuLoad() it is not permissable to call

+ PortAudio API functions from within the stream callback.

+*/

+typedef int PaStreamCallback(

+    const void *input, void *output,

+    unsigned long frameCount,

+    const PaStreamCallbackTimeInfo* timeInfo,

+    PaStreamCallbackFlags statusFlags,

+    void *userData );

+

+

+/** Opens a stream for either input, output or both.

+     

+ @param stream The address of a PaStream pointer which will receive

+ a pointer to the newly opened stream.

+     

+ @param inputParameters A structure that describes the input parameters used by

+ the opened stream. See PaStreamParameters for a description of these parameters.

+ inputParameters must be NULL for output-only streams.

+

+ @param outputParameters A structure that describes the output parameters used by

+ the opened stream. See PaStreamParameters for a description of these parameters.

+ outputParameters must be NULL for input-only streams.

+ 

+ @param sampleRate The desired sampleRate. For full-duplex streams it is the

+ sample rate for both input and output

+     

+ @param framesPerBuffer The number of frames passed to the stream callback

+ function, or the preferred block granularity for a blocking read/write stream.

+ The special value paFramesPerBufferUnspecified (0) may be used to request that

+ the stream callback will recieve an optimal (and possibly varying) number of

+ frames based on host requirements and the requested latency settings.

+ Note: With some host APIs, the use of non-zero framesPerBuffer for a callback

+ stream may introduce an additional layer of buffering which could introduce

+ additional latency. PortAudio guarantees that the additional latency

+ will be kept to the theoretical minimum however, it is strongly recommended

+ that a non-zero framesPerBuffer value only be used when your algorithm

+ requires a fixed number of frames per stream callback.

+ 

+ @param streamFlags Flags which modify the behaviour of the streaming process.

+ This parameter may contain a combination of flags ORed together. Some flags may

+ only be relevant to certain buffer formats.

+     

+ @param streamCallback A pointer to a client supplied function that is responsible

+ for processing and filling input and output buffers. If this parameter is NULL

+ the stream will be opened in 'blocking read/write' mode. In blocking mode,

+ the client can receive sample data using Pa_ReadStream and write sample data

+ using Pa_WriteStream, the number of samples that may be read or written

+ without blocking is returned by Pa_GetStreamReadAvailable and

+ Pa_GetStreamWriteAvailable respectively.

+

+ @param userData A client supplied pointer which is passed to the stream callback

+ function. It could for example, contain a pointer to instance data necessary

+ for processing the audio buffers. This parameter is ignored if streamCallback

+ is NULL.

+     

+ @return

+ Upon success Pa_OpenStream() returns paNoError and places a pointer to a

+ valid PaStream in the stream argument. The stream is inactive (stopped).

+ If a call to Pa_OpenStream() fails, a non-zero error code is returned (see

+ PaError for possible error codes) and the value of stream is invalid.

+

+ @see PaStreamParameters, PaStreamCallback, Pa_ReadStream, Pa_WriteStream,

+ Pa_GetStreamReadAvailable, Pa_GetStreamWriteAvailable

+*/

+PaError Pa_OpenStream( PaStream** stream,

+                       const PaStreamParameters *inputParameters,

+                       const PaStreamParameters *outputParameters,

+                       double sampleRate,

+                       unsigned long framesPerBuffer,

+                       PaStreamFlags streamFlags,

+                       PaStreamCallback *streamCallback,

+                       void *userData );

+

+

+/** A simplified version of Pa_OpenStream() that opens the default input

+ and/or output devices.

+

+ @param stream The address of a PaStream pointer which will receive

+ a pointer to the newly opened stream.

+ 

+ @param numInputChannels  The number of channels of sound that will be supplied

+ to the stream callback or returned by Pa_ReadStream. It can range from 1 to

+ the value of maxInputChannels in the PaDeviceInfo record for the default input

+ device. If 0 the stream is opened as an output-only stream.

+

+ @param numOutputChannels The number of channels of sound to be delivered to the

+ stream callback or passed to Pa_WriteStream. It can range from 1 to the value

+ of maxOutputChannels in the PaDeviceInfo record for the default output dvice.

+ If 0 the stream is opened as an output-only stream.

+

+ @param sampleFormat The sample format of both the input and output buffers

+ provided to the callback or passed to and from Pa_ReadStream and Pa_WriteStream.

+ sampleFormat may be any of the formats described by the PaSampleFormat

+ enumeration.

+ 

+ @param sampleRate Same as Pa_OpenStream parameter of the same name.

+ @param framesPerBuffer Same as Pa_OpenStream parameter of the same name.

+ @param streamCallback Same as Pa_OpenStream parameter of the same name.

+ @param userData Same as Pa_OpenStream parameter of the same name.

+

+ @return As for Pa_OpenStream

+

+ @see Pa_OpenStream, PaStreamCallback

+*/

+PaError Pa_OpenDefaultStream( PaStream** stream,

+                              int numInputChannels,

+                              int numOutputChannels,

+                              PaSampleFormat sampleFormat,

+                              double sampleRate,

+                              unsigned long framesPerBuffer,

+                              PaStreamCallback *streamCallback,

+                              void *userData );

+

+

+/** Closes an audio stream. If the audio stream is active it

+ discards any pending buffers as if Pa_AbortStream() had been called.

+*/

+PaError Pa_CloseStream( PaStream *stream );

+

+

+/** Functions of type PaStreamFinishedCallback are implemented by PortAudio 

+ clients. They can be registered with a stream using the Pa_SetStreamFinishedCallback

+ function. Once registered they are called when the stream becomes inactive

+ (ie once a call to Pa_StopStream() will not block).

+ A stream will become inactive after the stream callback returns non-zero,

+ or when Pa_StopStream or Pa_AbortStream is called. For a stream providing audio

+ output, if the stream callback returns paComplete, or Pa_StopStream is called,

+ the stream finished callback will not be called until all generated sample data

+ has been played.

+ 

+ @param userData The userData parameter supplied to Pa_OpenStream()

+

+ @see Pa_SetStreamFinishedCallback

+*/

+typedef void PaStreamFinishedCallback( void *userData );

+

+

+/** Register a stream finished callback function which will be called when the 

+ stream becomes inactive. See the description of PaStreamFinishedCallback for 

+ further details about when the callback will be called.

+

+ @param stream a pointer to a PaStream that is in the stopped state - if the

+ stream is not stopped, the stream's finished callback will remain unchanged 

+ and an error code will be returned.

+

+ @param streamFinishedCallback a pointer to a function with the same signature

+ as PaStreamFinishedCallback, that will be called when the stream becomes

+ inactive. Passing NULL for this parameter will un-register a previously

+ registered stream finished callback function.

+

+ @return on success returns paNoError, otherwise an error code indicating the cause

+ of the error.

+

+ @see PaStreamFinishedCallback

+*/

+PaError Pa_SetStreamFinishedCallback( PaStream *stream, PaStreamFinishedCallback* streamFinishedCallback ); 

+

+

+/** Commences audio processing.

+*/

+PaError Pa_StartStream( PaStream *stream );

+

+

+/** Terminates audio processing. It waits until all pending

+ audio buffers have been played before it returns.

+*/

+PaError Pa_StopStream( PaStream *stream );

+

+

+/** Terminates audio processing immediately without waiting for pending

+ buffers to complete.

+*/

+PaError Pa_AbortStream( PaStream *stream );

+

+

+/** Determine whether the stream is stopped.

+ A stream is considered to be stopped prior to a successful call to

+ Pa_StartStream and after a successful call to Pa_StopStream or Pa_AbortStream.

+ If a stream callback returns a value other than paContinue the stream is NOT

+ considered to be stopped.

+

+ @return Returns one (1) when the stream is stopped, zero (0) when

+ the stream is running or, a PaErrorCode (which are always negative) if

+ PortAudio is not initialized or an error is encountered.

+

+ @see Pa_StopStream, Pa_AbortStream, Pa_IsStreamActive

+*/

+PaError Pa_IsStreamStopped( PaStream *stream );

+

+

+/** Determine whether the stream is active.

+ A stream is active after a successful call to Pa_StartStream(), until it

+ becomes inactive either as a result of a call to Pa_StopStream() or

+ Pa_AbortStream(), or as a result of a return value other than paContinue from

+ the stream callback. In the latter case, the stream is considered inactive

+ after the last buffer has finished playing.

+

+ @return Returns one (1) when the stream is active (ie playing or recording

+ audio), zero (0) when not playing or, a PaErrorCode (which are always negative)

+ if PortAudio is not initialized or an error is encountered.

+

+ @see Pa_StopStream, Pa_AbortStream, Pa_IsStreamStopped

+*/

+PaError Pa_IsStreamActive( PaStream *stream );

+

+

+

+/** A structure containing unchanging information about an open stream.

+ @see Pa_GetStreamInfo

+*/

+

+typedef struct PaStreamInfo

+{

+    /** this is struct version 1 */

+    int structVersion;

+

+    /** The input latency of the stream in seconds. This value provides the most

+     accurate estimate of input latency available to the implementation. It may

+     differ significantly from the suggestedLatency value passed to Pa_OpenStream().

+     The value of this field will be zero (0.) for output-only streams.

+     @see PaTime

+    */

+    PaTime inputLatency;

+

+    /** The output latency of the stream in seconds. This value provides the most

+     accurate estimate of output latency available to the implementation. It may

+     differ significantly from the suggestedLatency value passed to Pa_OpenStream().

+     The value of this field will be zero (0.) for input-only streams.

+     @see PaTime

+    */

+    PaTime outputLatency;

+

+    /** The sample rate of the stream in Hertz (samples per second). In cases

+     where the hardware sample rate is inaccurate and PortAudio is aware of it,

+     the value of this field may be different from the sampleRate parameter

+     passed to Pa_OpenStream(). If information about the actual hardware sample

+     rate is not available, this field will have the same value as the sampleRate

+     parameter passed to Pa_OpenStream().

+    */

+    double sampleRate;

+    

+} PaStreamInfo;

+

+

+/** Retrieve a pointer to a PaStreamInfo structure containing information

+ about the specified stream.

+ @return A pointer to an immutable PaStreamInfo structure. If the stream

+ parameter invalid, or an error is encountered, the function returns NULL.

+

+ @param stream A pointer to an open stream previously created with Pa_OpenStream.

+

+ @note PortAudio manages the memory referenced by the returned pointer,

+ the client must not manipulate or free the memory. The pointer is only

+ guaranteed to be valid until the specified stream is closed.

+

+ @see PaStreamInfo

+*/

+const PaStreamInfo* Pa_GetStreamInfo( PaStream *stream );

+

+

+/** Determine the current time for the stream according to the same clock used

+ to generate buffer timestamps. This time may be used for syncronising other

+ events to the audio stream, for example synchronizing audio to MIDI.

+                                        

+ @return The stream's current time in seconds, or 0 if an error occurred.

+

+ @see PaTime, PaStreamCallback

+*/

+PaTime Pa_GetStreamTime( PaStream *stream );

+

+

+/** Retrieve CPU usage information for the specified stream.

+ The "CPU Load" is a fraction of total CPU time consumed by a callback stream's

+ audio processing routines including, but not limited to the client supplied

+ stream callback. This function does not work with blocking read/write streams.

+

+ This function may be called from the stream callback function or the

+ application.

+     

+ @return

+ A floating point value, typically between 0.0 and 1.0, where 1.0 indicates

+ that the stream callback is consuming the maximum number of CPU cycles possible

+ to maintain real-time operation. A value of 0.5 would imply that PortAudio and

+ the stream callback was consuming roughly 50% of the available CPU time. The

+ return value may exceed 1.0. A value of 0.0 will always be returned for a

+ blocking read/write stream, or if an error occurrs.

+*/

+double Pa_GetStreamCpuLoad( PaStream* stream );

+

+

+/** Read samples from an input stream. The function doesn't return until

+ the entire buffer has been filled - this may involve waiting for the operating

+ system to supply the data.

+

+ @param stream A pointer to an open stream previously created with Pa_OpenStream.

+ 

+ @param buffer A pointer to a buffer of sample frames. The buffer contains

+ samples in the format specified by the inputParameters->sampleFormat field

+ used to open the stream, and the number of channels specified by

+ inputParameters->numChannels. If non-interleaved samples were requested,

+ buffer is a pointer to the first element of an array of non-interleaved

+ buffer pointers, one for each channel.

+

+ @param frames The number of frames to be read into buffer. This parameter

+ is not constrained to a specific range, however high performance applications

+ will want to match this parameter to the framesPerBuffer parameter used

+ when opening the stream.

+

+ @return On success PaNoError will be returned, or PaInputOverflowed if input

+ data was discarded by PortAudio after the previous call and before this call.

+*/

+PaError Pa_ReadStream( PaStream* stream,

+                       void *buffer,

+                       unsigned long frames );

+

+

+/** Write samples to an output stream. This function doesn't return until the

+ entire buffer has been consumed - this may involve waiting for the operating

+ system to consume the data.

+

+ @param stream A pointer to an open stream previously created with Pa_OpenStream.

+

+ @param buffer A pointer to a buffer of sample frames. The buffer contains

+ samples in the format specified by the outputParameters->sampleFormat field

+ used to open the stream, and the number of channels specified by

+ outputParameters->numChannels. If non-interleaved samples were requested,

+ buffer is a pointer to the first element of an array of non-interleaved

+ buffer pointers, one for each channel.

+

+ @param frames The number of frames to be written from buffer. This parameter

+ is not constrained to a specific range, however high performance applications

+ will want to match this parameter to the framesPerBuffer parameter used

+ when opening the stream.

+

+ @return On success PaNoError will be returned, or paOutputUnderflowed if

+ additional output data was inserted after the previous call and before this

+ call.

+*/

+PaError Pa_WriteStream( PaStream* stream,

+                        const void *buffer,

+                        unsigned long frames );

+

+

+/** Retrieve the number of frames that can be read from the stream without

+ waiting.

+

+ @return Returns a non-negative value representing the maximum number of frames

+ that can be read from the stream without blocking or busy waiting or, a

+ PaErrorCode (which are always negative) if PortAudio is not initialized or an

+ error is encountered.

+*/

+signed long Pa_GetStreamReadAvailable( PaStream* stream );

+

+

+/** Retrieve the number of frames that can be written to the stream without

+ waiting.

+

+ @return Returns a non-negative value representing the maximum number of frames

+ that can be written to the stream without blocking or busy waiting or, a

+ PaErrorCode (which are always negative) if PortAudio is not initialized or an

+ error is encountered.

+*/

+signed long Pa_GetStreamWriteAvailable( PaStream* stream );

+

+

+/* Miscellaneous utilities */

+

+

+/** Retrieve the size of a given sample format in bytes.

+

+ @return The size in bytes of a single sample in the specified format,

+ or paSampleFormatNotSupported if the format is not supported.

+*/

+PaError Pa_GetSampleSize( PaSampleFormat format );

+

+

+/** Put the caller to sleep for at least 'msec' milliseconds. This function is

+ provided only as a convenience for authors of portable code (such as the tests

+ and examples in the PortAudio distribution.)

+

+ The function may sleep longer than requested so don't rely on this for accurate

+ musical timing.

+*/

+void Pa_Sleep( long msec );

+

+

+

+#ifdef __cplusplus

+}

+#endif /* __cplusplus */

+#endif /* PORTAUDIO_H */

diff --git a/src/engine/external/wavpack/arm.S b/src/engine/external/wavpack/arm.S
new file mode 100644
index 00000000..ab882181
--- /dev/null
+++ b/src/engine/external/wavpack/arm.S
@@ -0,0 +1,461 @@
+////////////////////////////////////////////////////////////////////////////

+//                           **** WAVPACK ****                            //

+//                  Hybrid Lossless Wavefile Compressor                   //

+//              Copyright (c) 1998 - 2006 Conifer Software.               //

+//                          All Rights Reserved.                          //

+//      Distributed under the BSD Software License (see license.txt)      //

+////////////////////////////////////////////////////////////////////////////

+

+/* This is an assembly optimized version of the following WavPack function:

+ *

+ * void decorr_stereo_pass_cont (struct decorr_pass *dpp,

+ *                               long *buffer, long sample_count);

+ *

+ * It performs a single pass of stereo decorrelation on the provided buffer.

+ * Note that this version of the function requires that the 8 previous stereo

+ * samples are visible and correct. In other words, it ignores the "samples_*"

+ * fields in the decorr_pass structure and gets the history data directly

+ * from the buffer. It does, however, return the appropriate history samples

+ * to the decorr_pass structure before returning.

+ *

+ * This is written to work on a ARM7TDMI processor. This version only uses the

+ * 32-bit multiply-accumulate instruction and so will overflow with 24-bit

+ * WavPack files.

+ */

+        .text

+        .align

+        .global         decorr_stereo_pass_cont_arm

+

+/*

+ * on entry:

+ *

+ * r0 = struct decorr_pass *dpp

+ * r1 = long *buffer

+ * r2 = long sample_count

+ */

+

+decorr_stereo_pass_cont_arm:

+

+        stmfd   sp!, {r4 - r8, r10, r11, lr}

+        mov     r5, r0                  @ r5 = dpp

+        mov     r11, #512               @ r11 = 512 for rounding

+        ldrsh   r6, [r0, #2]            @ r6 = dpp->delta

+        ldrsh   r4, [r0, #4]            @ r4 = dpp->weight_A

+        ldrsh   r0, [r0, #6]            @ r0 = dpp->weight_B

+        cmp     r2, #0                  @ exit if no samples to process

+        beq     common_exit

+

+        add     r7, r1, r2, asl #3      @ r7 = buffer ending position

+        ldrsh   r2, [r5, #0]            @ r2 = dpp->term

+        cmp     r2, #0

+        bmi     minus_term

+

+        ldr     lr, [r1, #-16]          @ load 2 sample history from buffer

+        ldr     r10, [r1, #-12]         @  for terms 2, 17, and 18

+        ldr     r8, [r1, #-8]

+        ldr     r3, [r1, #-4]

+        cmp     r2, #17

+        beq     term_17_loop

+        cmp     r2, #18

+        beq     term_18_loop

+        cmp     r2, #2

+        beq     term_2_loop

+        b       term_default_loop       @ else handle default (1-8, except 2)

+

+minus_term:

+        mov     r10, #1024              @ r10 = -1024 for weight clipping

+        rsb     r10, r10, #0            @  (only used for negative terms)

+        cmn     r2, #1

+        beq     term_minus_1

+        cmn     r2, #2

+        beq     term_minus_2

+        cmn     r2, #3

+        beq     term_minus_3

+        b       common_exit

+

+/*

+ ******************************************************************************

+ * Loop to handle term = 17 condition

+ *

+ * r0 = dpp->weight_B           r8 = previous left sample

+ * r1 = bptr                    r9 = 

+ * r2 = current sample          r10 = second previous left sample

+ * r3 = previous right sample   r11 = 512 (for rounding)

+ * r4 = dpp->weight_A           ip = current decorrelation value

+ * r5 = dpp                     sp =

+ * r6 = dpp->delta              lr = second previous right sample

+ * r7 = eptr                    pc =

+ *******************************************************************************

+ */

+

+term_17_loop:

+        rsbs    ip, lr, r8, asl #1      @ decorr value = (2 * prev) - 2nd prev

+        mov     lr, r8                  @ previous becomes 2nd previous

+        ldr     r2, [r1], #4            @ get sample & update pointer

+        mla     r8, ip, r4, r11         @ mult decorr value by weight, round,

+        add     r8, r2, r8, asr #10     @  shift, and add to new sample

+        strne   r8, [r1, #-4]           @ if change possible, store sample back

+        cmpne   r2, #0

+        beq     .L325

+        teq     ip, r2                  @ update weight based on signs

+        submi   r4, r4, r6

+        addpl   r4, r4, r6

+

+.L325:  rsbs    ip, r10, r3, asl #1     @ do same thing for right channel

+        mov     r10, r3

+        ldr     r2, [r1], #4

+        mla     r3, ip, r0, r11

+        add     r3, r2, r3, asr #10

+        strne   r3, [r1, #-4]

+        cmpne   r2, #0

+        beq     .L329

+        teq     ip, r2

+        submi   r0, r0, r6

+        addpl   r0, r0, r6

+

+.L329:  cmp     r7, r1                  @ loop back if more samples to do

+        bhi     term_17_loop

+        b       store_1718              @ common exit for terms 17 & 18

+

+/*

+ ******************************************************************************

+ * Loop to handle term = 18 condition

+ *

+ * r0 = dpp->weight_B           r8 = previous left sample

+ * r1 = bptr                    r9 = 

+ * r2 = current sample          r10 = second previous left sample

+ * r3 = previous right sample   r11 = 512 (for rounding)

+ * r4 = dpp->weight_A           ip = decorrelation value

+ * r5 = dpp                     sp =

+ * r6 = dpp->delta              lr = second previous right sample

+ * r7 = eptr                    pc =

+ *******************************************************************************

+ */

+

+term_18_loop:

+        sub     ip, r8, lr              @ decorr value =

+        mov     lr, r8                  @  ((3 * prev) - 2nd prev) >> 1

+        adds    ip, r8, ip, asr #1

+        ldr     r2, [r1], #4            @ get sample & update pointer

+        mla     r8, ip, r4, r11         @ mult decorr value by weight, round,

+        add     r8, r2, r8, asr #10     @  shift, and add to new sample

+        strne   r8, [r1, #-4]           @ if change possible, store sample back

+        cmpne   r2, #0

+        beq     .L337

+        teq     ip, r2                  @ update weight based on signs

+        submi   r4, r4, r6

+        addpl   r4, r4, r6

+

+.L337:  sub     ip, r3, r10             @ do same thing for right channel

+        mov     r10, r3

+        adds    ip, r3, ip, asr #1

+        ldr     r2, [r1], #4

+        mla     r3, ip, r0, r11

+        add     r3, r2, r3, asr #10

+        strne   r3, [r1, #-4]

+        cmpne   r2, #0

+        beq     .L341

+        teq     ip, r2

+        submi   r0, r0, r6

+        addpl   r0, r0, r6

+

+.L341:  cmp     r7, r1                  @ loop back if more samples to do

+        bhi     term_18_loop

+

+/* common exit for terms 17 & 18 */

+

+store_1718:

+        str     r3, [r5, #40]           @ store sample history into struct

+        str     r8, [r5, #8]

+        str     r10, [r5, #44]

+        str     lr, [r5, #12]

+        b       common_exit             @ and return

+

+/*

+ ******************************************************************************

+ * Loop to handle term = 2 condition

+ * (note that this case can be handled by the default term handler (1-8), but

+ * this special case is faster because it doesn't have to read memory twice)

+ *

+ * r0 = dpp->weight_B           r8 = previous left sample

+ * r1 = bptr                    r9 = 

+ * r2 = current sample          r10 = second previous left sample

+ * r3 = previous right sample   r11 = 512 (for rounding)

+ * r4 = dpp->weight_A           ip = decorrelation value

+ * r5 = dpp                     sp =

+ * r6 = dpp->delta              lr = second previous right sample

+ * r7 = eptr                    pc =

+ *******************************************************************************

+ */

+

+term_2_loop:

+        movs    ip, lr                  @ get decorrelation value & test

+        mov     lr, r8                  @ previous becomes 2nd previous

+        ldr     r2, [r1], #4            @ get sample & update pointer

+        mla     r8, ip, r4, r11         @ mult decorr value by weight, round,

+        add     r8, r2, r8, asr #10     @  shift, and add to new sample

+        strne   r8, [r1, #-4]           @ if change possible, store sample back

+        cmpne   r2, #0

+        beq     .L225

+        teq     ip, r2                  @ update weight based on signs

+        submi   r4, r4, r6

+        addpl   r4, r4, r6

+

+.L225:  movs    ip, r10                 @ do same thing for right channel

+        mov     r10, r3

+        ldr     r2, [r1], #4

+        mla     r3, ip, r0, r11

+        add     r3, r2, r3, asr #10

+        strne   r3, [r1, #-4]

+        cmpne   r2, #0

+        beq     .L229

+        teq     ip, r2

+        submi   r0, r0, r6

+        addpl   r0, r0, r6

+

+.L229:  cmp     r7, r1                  @ loop back if more samples to do

+        bhi     term_2_loop

+        b       default_term_exit       @ this exit updates all dpp->samples

+

+/*

+ ******************************************************************************

+ * Loop to handle default term condition

+ *

+ * r0 = dpp->weight_B           r8 = result accumulator

+ * r1 = bptr                    r9 = 

+ * r2 = dpp->term               r10 =

+ * r3 = decorrelation value     r11 = 512 (for rounding)

+ * r4 = dpp->weight_A           ip = current sample

+ * r5 = dpp                     sp =

+ * r6 = dpp->delta              lr =

+ * r7 = eptr                    pc =

+ *******************************************************************************

+ */

+

+term_default_loop:

+        ldr     ip, [r1]                @ get original sample

+        ldr     r3, [r1, -r2, asl #3]   @ get decorrelation value based on term

+        mla     r8, r3, r4, r11         @ mult decorr value by weight, round,

+        add     r8, ip, r8, asr #10     @  shift and add to new sample

+        str     r8, [r1], #4            @ store update sample

+        cmp     r3, #0

+        cmpne   ip, #0

+        beq     .L350

+        teq     ip, r3                  @ update weight based on signs

+        submi   r4, r4, r6

+        addpl   r4, r4, r6

+

+.L350:  ldr     ip, [r1]                @ do the same thing for right channel

+        ldr     r3, [r1, -r2, asl #3]

+        mla     r8, r3, r0, r11

+        add     r8, ip, r8, asr #10

+        str     r8, [r1], #4

+        cmp     r3, #0

+        cmpne   ip, #0

+        beq     .L354

+        teq     ip, r3

+        submi   r0, r0, r6

+        addpl   r0, r0, r6

+

+.L354:  cmp     r7, r1                  @ loop back if more samples to do

+        bhi     term_default_loop

+

+/*

+ * This exit is used by terms 1-8 to store the previous 8 samples into the decorr

+ * structure (even if they are not all used for the given term)

+ */

+

+default_term_exit:

+        ldrsh   r3, [r5, #0]

+        sub     ip, r3, #1

+        mov     lr, #7

+

+.L358:  and     r3, ip, #7

+        add     r3, r5, r3, asl #2

+        ldr     r2, [r1, #-4]

+        str     r2, [r3, #40]

+        ldr     r2, [r1, #-8]!

+        str     r2, [r3, #8]

+        sub     ip, ip, #1

+        sub     lr, lr, #1

+        cmn     lr, #1

+        bne     .L358

+        b       common_exit

+

+/*

+ ******************************************************************************

+ * Loop to handle term = -1 condition

+ *

+ * r0 = dpp->weight_B           r8 =

+ * r1 = bptr                    r9 = 

+ * r2 = intermediate result     r10 = -1024 (for clipping)

+ * r3 = previous right sample   r11 = 512 (for rounding)

+ * r4 = dpp->weight_A           ip = current sample

+ * r5 = dpp                     sp =

+ * r6 = dpp->delta              lr = updated left sample

+ * r7 = eptr                    pc =

+ *******************************************************************************

+ */

+

+term_minus_1:

+        ldr     r3, [r1, #-4]

+

+term_minus_1_loop:

+        ldr     ip, [r1]                @ for left channel the decorrelation value

+        mla     r2, r3, r4, r11         @  is the previous right sample (in r3)

+        add     lr, ip, r2, asr #10

+        str     lr, [r1], #8

+        cmp     r3, #0

+        cmpne   ip, #0

+        beq     .L361

+        teq     ip, r3                  @ update weight based on signs

+        submi   r4, r4, r6

+        addpl   r4, r4, r6

+        cmp     r4, #1024

+        movgt   r4, #1024

+        cmp     r4, r10

+        movlt   r4, r10

+

+.L361:  ldr     r2, [r1, #-4]           @ for right channel the decorrelation value

+        mla     r3, lr, r0, r11         @  is the just updated right sample (in lr)

+        add     r3, r2, r3, asr #10

+        str     r3, [r1, #-4]

+        cmp     lr, #0

+        cmpne   r2, #0

+        beq     .L369

+        teq     r2, lr

+        submi   r0, r0, r6

+        addpl   r0, r0, r6

+        cmp     r0, #1024               @ then clip weight to +/-1024

+        movgt   r0, #1024

+        cmp     r0, r10

+        movlt   r0, r10

+

+.L369:  cmp     r7, r1                  @ loop back if more samples to do

+        bhi     term_minus_1_loop

+

+        str     r3, [r5, #8]            @ else store right sample and exit

+        b       common_exit

+

+/*

+ ******************************************************************************

+ * Loop to handle term = -2 condition

+ * (note that the channels are processed in the reverse order here)

+ *

+ * r0 = dpp->weight_B           r8 =

+ * r1 = bptr                    r9 = 

+ * r2 = intermediate result     r10 = -1024 (for clipping)

+ * r3 = previous left sample    r11 = 512 (for rounding)

+ * r4 = dpp->weight_A           ip = current sample

+ * r5 = dpp                     sp =

+ * r6 = dpp->delta              lr = updated right sample

+ * r7 = eptr                    pc =

+ *******************************************************************************

+ */

+

+term_minus_2:

+        ldr     r3, [r1, #-8]

+

+term_minus_2_loop:

+        ldr     ip, [r1, #4]            @ for right channel the decorrelation value

+        mla     r2, r3, r0, r11         @  is the previous left sample (in r3)

+        add     lr, ip, r2, asr #10

+        str     lr, [r1, #4]

+        cmp     r3, #0

+        cmpne   ip, #0

+        beq     .L380

+        teq     ip, r3                  @ update weight based on signs

+        submi   r0, r0, r6

+        addpl   r0, r0, r6

+        cmp     r0, #1024               @ then clip weight to +/-1024

+        movgt   r0, #1024

+        cmp     r0, r10

+        movlt   r0, r10

+

+.L380:  ldr     r2, [r1, #0]            @ for left channel the decorrelation value

+        mla     r3, lr, r4, r11         @  is the just updated left sample (in lr)

+        add     r3, r2, r3, asr #10

+        str     r3, [r1], #8

+        cmp     lr, #0

+        cmpne   r2, #0

+        beq     .L388

+        teq     r2, lr

+        submi   r4, r4, r6

+        addpl   r4, r4, r6

+        cmp     r4, #1024

+        movgt   r4, #1024

+        cmp     r4, r10

+        movlt   r4, r10

+

+.L388:  cmp     r7, r1                  @ loop back if more samples to do

+        bhi     term_minus_2_loop

+

+        str     r3, [r5, #40]           @ else store left channel and exit

+        b       common_exit

+

+/*

+ ******************************************************************************

+ * Loop to handle term = -3 condition

+ *

+ * r0 = dpp->weight_B           r8 = previous left sample

+ * r1 = bptr                    r9 = 

+ * r2 = current left sample     r10 = -1024 (for clipping)

+ * r3 = previous right sample   r11 = 512 (for rounding)

+ * r4 = dpp->weight_A           ip = intermediate result

+ * r5 = dpp                     sp =

+ * r6 = dpp->delta              lr =

+ * r7 = eptr                    pc =

+ *******************************************************************************

+ */

+

+term_minus_3:

+        ldr     r3, [r1, #-4]           @ load previous samples

+        ldr     r8, [r1, #-8]

+

+term_minus_3_loop:

+        ldr     ip, [r1]

+        mla     r2, r3, r4, r11

+        add     r2, ip, r2, asr #10

+        str     r2, [r1], #4

+        cmp     r3, #0

+        cmpne   ip, #0

+        beq     .L399

+        teq     ip, r3                  @ update weight based on signs

+        submi   r4, r4, r6

+        addpl   r4, r4, r6

+        cmp     r4, #1024               @ then clip weight to +/-1024

+        movgt   r4, #1024

+        cmp     r4, r10

+        movlt   r4, r10

+

+.L399:  movs    ip, r8                  @ ip = previous left we use now

+        mov     r8, r2                  @ r8 = current left we use next time

+        ldr     r2, [r1], #4

+        mla     r3, ip, r0, r11

+        add     r3, r2, r3, asr #10

+        strne   r3, [r1, #-4]

+        cmpne   r2, #0

+        beq     .L407

+        teq     ip, r2

+        submi   r0, r0, r6

+        addpl   r0, r0, r6

+        cmp     r0, #1024

+        movgt   r0, #1024

+        cmp     r0, r10

+        movlt   r0, r10

+

+.L407:  cmp     r7, r1                  @ loop back if more samples to do

+        bhi     term_minus_3_loop

+

+        str     r3, [r5, #8]            @ else store previous samples & exit

+        str     r8, [r5, #40]

+

+/*

+ * Before finally exiting we must store weights back for next time

+ */

+

+common_exit:

+        strh    r4, [r5, #4]

+        strh    r0, [r5, #6]

+        ldmfd   sp!, {r4 - r8, r10, r11, pc}

+

diff --git a/src/engine/external/wavpack/arml.S b/src/engine/external/wavpack/arml.S
new file mode 100644
index 00000000..39de5383
--- /dev/null
+++ b/src/engine/external/wavpack/arml.S
@@ -0,0 +1,491 @@
+////////////////////////////////////////////////////////////////////////////

+//                           **** WAVPACK ****                            //

+//                  Hybrid Lossless Wavefile Compressor                   //

+//              Copyright (c) 1998 - 2006 Conifer Software.               //

+//                          All Rights Reserved.                          //

+//      Distributed under the BSD Software License (see license.txt)      //

+////////////////////////////////////////////////////////////////////////////

+

+/* This is an assembly optimized version of the following WavPack function:

+ *

+ * void decorr_stereo_pass_cont (struct decorr_pass *dpp,

+ *                               long *buffer, long sample_count);

+ *

+ * It performs a single pass of stereo decorrelation on the provided buffer.

+ * Note that this version of the function requires that the 8 previous stereo

+ * samples are visible and correct. In other words, it ignores the "samples_*"

+ * fields in the decorr_pass structure and gets the history data directly

+ * from the buffer. It does, however, return the appropriate history samples

+ * to the decorr_pass structure before returning.

+ *

+ * This is written to work on a ARM7TDMI processor. This version uses the

+ * 64-bit multiply-accumulate instruction and so can be used with all

+ * WavPack files. However, for optimum performance with 16-bit WavPack

+ * files, there is a faster version that only uses the 32-bit MLA

+ * instruction.

+ */

+

+        .text

+        .align

+        .global         decorr_stereo_pass_cont_arml

+

+/*

+ * on entry:

+ *

+ * r0 = struct decorr_pass *dpp

+ * r1 = long *buffer

+ * r2 = long sample_count

+ */

+

+decorr_stereo_pass_cont_arml:

+

+        stmfd   sp!, {r4 - r8, r10, r11, lr}

+        mov     r5, r0                  @ r5 = dpp

+        mov     r11, #512               @ r11 = 512 for rounding

+        ldrsh   r6, [r0, #2]            @ r6 = dpp->delta

+        ldrsh   r4, [r0, #4]            @ r4 = dpp->weight_A

+        ldrsh   r0, [r0, #6]            @ r0 = dpp->weight_B

+        cmp     r2, #0                  @ exit if no samples to process

+        beq     common_exit

+

+        mov     r0, r0, asl #18         @ for 64-bit math we use weights << 18

+        mov     r4, r4, asl #18

+        mov     r6, r6, asl #18

+        add     r7, r1, r2, asl #3      @ r7 = buffer ending position

+        ldrsh   r2, [r5, #0]            @ r2 = dpp->term

+        cmp     r2, #0

+        blt     minus_term

+

+        ldr     lr, [r1, #-16]          @ load 2 sample history from buffer

+        ldr     r10, [r1, #-12]         @  for terms 2, 17, and 18

+        ldr     r8, [r1, #-8]

+        ldr     r3, [r1, #-4]

+

+        cmp     r2, #18

+        beq     term_18_loop

+        mov     lr, lr, asl #4

+        mov     r10, r10, asl #4

+        cmp     r2, #2

+        beq     term_2_loop

+        cmp     r2, #17

+        beq     term_17_loop

+        b       term_default_loop

+

+minus_term:

+        mov     r10, #(1024 << 18)      @ r10 = -1024 << 18 for weight clipping

+        rsb     r10, r10, #0            @  (only used for negative terms)

+        cmn     r2, #1

+        beq     term_minus_1

+        cmn     r2, #2

+        beq     term_minus_2

+        cmn     r2, #3

+        beq     term_minus_3

+        b       common_exit

+

+/*

+ ******************************************************************************

+ * Loop to handle term = 17 condition

+ *

+ * r0 = dpp->weight_B           r8 = previous left sample

+ * r1 = bptr                    r9 = 

+ * r2 = current sample          r10 = second previous left sample << 4

+ * r3 = previous right sample   r11 = lo accumulator (for rounding)

+ * r4 = dpp->weight_A           ip = current decorrelation value

+ * r5 = dpp                     sp =

+ * r6 = dpp->delta              lr = second previous right sample << 4

+ * r7 = eptr                    pc =

+ *******************************************************************************

+ */

+

+term_17_loop:

+        rsbs    ip, lr, r8, asl #5      @ decorr value = (2 * prev) - 2nd prev

+        mov     lr, r8, asl #4          @ previous becomes 2nd previous

+        ldr     r2, [r1], #4            @ get sample & update pointer

+        mov     r11, #0x80000000

+        mov     r8, r2

+        smlalne r11, r8, r4, ip

+        strne   r8, [r1, #-4]           @ if change possible, store sample back

+        cmpne   r2, #0

+        beq     .L325

+        teq     ip, r2                  @ update weight based on signs

+        submi   r4, r4, r6

+        addpl   r4, r4, r6

+

+.L325:  rsbs    ip, r10, r3, asl #5     @ do same thing for right channel

+        mov     r10, r3, asl #4

+        ldr     r2, [r1], #4

+        mov     r11, #0x80000000

+        mov     r3, r2

+        smlalne r11, r3, r0, ip

+        strne   r3, [r1, #-4]

+        cmpne   r2, #0

+        beq     .L329

+        teq     ip, r2

+        submi   r0, r0, r6

+        addpl   r0, r0, r6

+

+.L329:  cmp     r7, r1                  @ loop back if more samples to do

+        bhi     term_17_loop

+        mov     lr, lr, asr #4

+        mov     r10, r10, asr #4

+        b       store_1718              @ common exit for terms 17 & 18

+

+/*

+ ******************************************************************************

+ * Loop to handle term = 18 condition

+ *

+ * r0 = dpp->weight_B           r8 = previous left sample

+ * r1 = bptr                    r9 = 

+ * r2 = current sample          r10 = second previous left sample

+ * r3 = previous right sample   r11 = lo accumulator (for rounding)

+ * r4 = dpp->weight_A           ip = decorrelation value

+ * r5 = dpp                     sp =

+ * r6 = dpp->delta              lr = second previous right sample

+ * r7 = eptr                    pc =

+ *******************************************************************************

+ */

+

+term_18_loop:

+        rsb     ip, lr, r8              @ decorr value =

+        mov     lr, r8                  @  ((3 * prev) - 2nd prev) >> 1

+        add     ip, lr, ip, asr #1

+        movs    ip, ip, asl #4

+        ldr     r2, [r1], #4            @ get sample & update pointer

+        mov     r11, #0x80000000

+        mov     r8, r2

+        smlalne r11, r8, r4, ip

+        strne   r8, [r1, #-4]           @ if change possible, store sample back

+        cmpne   r2, #0

+        beq     .L337

+        teq     ip, r2                  @ update weight based on signs

+        submi   r4, r4, r6

+        addpl   r4, r4, r6

+

+.L337:  rsb     ip, r10, r3             @ do same thing for right channel

+        mov     r10, r3

+        add     ip, r10, ip, asr #1

+        movs    ip, ip, asl #4

+        ldr     r2, [r1], #4

+        mov     r11, #0x80000000

+        mov     r3, r2

+        smlalne r11, r3, r0, ip

+        strne   r3, [r1, #-4]

+        cmpne   r2, #0

+        beq     .L341

+        teq     ip, r2

+        submi   r0, r0, r6

+        addpl   r0, r0, r6

+

+.L341:  cmp     r7, r1                  @ loop back if more samples to do

+        bhi     term_18_loop

+

+/* common exit for terms 17 & 18 */

+

+store_1718:

+        str     r3, [r5, #40]           @ store sample history into struct

+        str     r8, [r5, #8]

+        str     r10, [r5, #44]

+        str     lr, [r5, #12]

+        b       common_exit             @ and return

+

+/*

+ ******************************************************************************

+ * Loop to handle term = 2 condition

+ * (note that this case can be handled by the default term handler (1-8), but

+ * this special case is faster because it doesn't have to read memory twice)

+ *

+ * r0 = dpp->weight_B           r8 = previous left sample

+ * r1 = bptr                    r9 = 

+ * r2 = current sample          r10 = second previous left sample << 4

+ * r3 = previous right sample   r11 = lo accumulator (for rounding)

+ * r4 = dpp->weight_A           ip = decorrelation value

+ * r5 = dpp                     sp =

+ * r6 = dpp->delta              lr = second previous right sample << 4

+ * r7 = eptr                    pc =

+ *******************************************************************************

+ */

+

+term_2_loop:

+        movs    ip, lr                  @ get decorrelation value & test

+        ldr     r2, [r1], #4            @ get sample & update pointer

+        mov     lr, r8, asl #4          @ previous becomes 2nd previous

+        mov     r11, #0x80000000

+        mov     r8, r2

+        smlalne r11, r8, r4, ip

+        strne   r8, [r1, #-4]           @ if change possible, store sample back

+        cmpne   r2, #0

+        beq     .L225

+        teq     ip, r2                  @ update weight based on signs

+        submi   r4, r4, r6

+        addpl   r4, r4, r6

+

+.L225:  movs    ip, r10                 @ do same thing for right channel

+        ldr     r2, [r1], #4

+        mov     r10, r3, asl #4

+        mov     r11, #0x80000000

+        mov     r3, r2

+        smlalne r11, r3, r0, ip

+        strne   r3, [r1, #-4]

+        cmpne   r2, #0

+        beq     .L229

+        teq     ip, r2

+        submi   r0, r0, r6

+        addpl   r0, r0, r6

+

+.L229:  cmp     r7, r1                  @ loop back if more samples to do

+        bhi     term_2_loop

+

+        b       default_term_exit       @ this exit updates all dpp->samples

+

+/*

+ ******************************************************************************

+ * Loop to handle default term condition

+ *

+ * r0 = dpp->weight_B           r8 = result accumulator

+ * r1 = bptr                    r9 = 

+ * r2 = dpp->term               r10 =

+ * r3 = decorrelation value     r11 = lo accumulator (for rounding)

+ * r4 = dpp->weight_A           ip = current sample

+ * r5 = dpp                     sp =

+ * r6 = dpp->delta              lr =

+ * r7 = eptr                    pc =

+ *******************************************************************************

+ */

+

+term_default_loop:

+        ldr     r3, [r1, -r2, asl #3]   @ get decorrelation value based on term

+        ldr     ip, [r1], #4            @ get original sample and bump ptr

+        movs    r3, r3, asl #4

+        mov     r11, #0x80000000

+        mov     r8, ip

+        smlalne r11, r8, r4, r3

+        strne   r8, [r1, #-4]           @ if possibly changed, store updated sample

+        cmpne   ip, #0

+        beq     .L350

+        teq     ip, r3                  @ update weight based on signs

+        submi   r4, r4, r6

+        addpl   r4, r4, r6

+

+.L350:  ldr     r3, [r1, -r2, asl #3]   @ do the same thing for right channel

+        ldr     ip, [r1], #4

+        movs    r3, r3, asl #4

+        mov     r11, #0x80000000

+        mov     r8, ip

+        smlalne r11, r8, r0, r3

+        strne   r8, [r1, #-4]

+        cmpne   ip, #0

+        beq     .L354

+        teq     ip, r3

+        submi   r0, r0, r6

+        addpl   r0, r0, r6

+

+.L354:  cmp     r7, r1                  @ loop back if more samples to do

+        bhi     term_default_loop

+

+/*

+ * This exit is used by terms 1-8 to store the previous 8 samples into the decorr

+ * structure (even if they are not all used for the given term)

+ */

+

+default_term_exit:

+        ldrsh   r3, [r5, #0]

+        sub     ip, r3, #1

+        mov     lr, #7

+

+.L358:  and     r3, ip, #7

+        add     r3, r5, r3, asl #2

+        ldr     r2, [r1, #-4]

+        str     r2, [r3, #40]

+        ldr     r2, [r1, #-8]!

+        str     r2, [r3, #8]

+        sub     ip, ip, #1

+        sub     lr, lr, #1

+        cmn     lr, #1

+        bne     .L358

+        b       common_exit

+

+/*

+ ******************************************************************************

+ * Loop to handle term = -1 condition

+ *

+ * r0 = dpp->weight_B           r8 =

+ * r1 = bptr                    r9 = 

+ * r2 = intermediate result     r10 = -1024 (for clipping)

+ * r3 = previous right sample   r11 = lo accumulator (for rounding)

+ * r4 = dpp->weight_A           ip = current sample

+ * r5 = dpp                     sp =

+ * r6 = dpp->delta              lr = updated left sample

+ * r7 = eptr                    pc =

+ *******************************************************************************

+ */

+

+term_minus_1:

+        ldr     r3, [r1, #-4]

+

+term_minus_1_loop:

+        ldr     ip, [r1], #8            @ for left channel the decorrelation value

+        movs    r3, r3, asl #4          @  is the previous right sample (in r3)

+        mov     r11, #0x80000000

+        mov     lr, ip

+        smlalne r11, lr, r4, r3

+        strne   lr, [r1, #-8]

+        cmpne   ip, #0

+        beq     .L361

+        teq     ip, r3                  @ update weight based on signs

+        submi   r4, r4, r6

+        addpl   r4, r4, r6

+        cmp     r4, #(1024 << 18)

+        movgt   r4, #(1024 << 18)

+        cmp     r4, r10

+        movlt   r4, r10

+

+.L361:  ldr     r2, [r1, #-4]           @ for right channel the decorrelation value

+        movs    lr, lr, asl #4

+        mov     r11, #0x80000000

+        mov     r3, r2

+        smlalne r11, r3, r0, lr

+        strne   r3, [r1, #-4]

+        cmpne   r2, #0

+        beq     .L369

+        teq     r2, lr

+        submi   r0, r0, r6

+        addpl   r0, r0, r6

+        cmp     r0, #(1024 << 18)               @ then clip weight to +/-1024

+        movgt   r0, #(1024 << 18)

+        cmp     r0, r10

+        movlt   r0, r10

+

+.L369:  cmp     r7, r1                  @ loop back if more samples to do

+        bhi     term_minus_1_loop

+

+        str     r3, [r5, #8]            @ else store right sample and exit

+        b       common_exit

+

+/*

+ ******************************************************************************

+ * Loop to handle term = -2 condition

+ * (note that the channels are processed in the reverse order here)

+ *

+ * r0 = dpp->weight_B           r8 =

+ * r1 = bptr                    r9 = 

+ * r2 = intermediate result     r10 = -1024 (for clipping)

+ * r3 = previous left sample    r11 = lo accumulator (for rounding)

+ * r4 = dpp->weight_A           ip = current sample

+ * r5 = dpp                     sp =

+ * r6 = dpp->delta              lr = updated right sample

+ * r7 = eptr                    pc =

+ *******************************************************************************

+ */

+

+term_minus_2:

+        ldr     r3, [r1, #-8]

+

+term_minus_2_loop:

+        ldr     ip, [r1, #4]            @ for right channel the decorrelation value

+        movs    r3, r3, asl #4          @  is the previous left sample (in r3)

+        mov     r11, #0x80000000

+        mov     lr, ip

+        smlalne r11, lr, r0, r3

+        strne   lr, [r1, #4]

+        cmpne   ip, #0

+        beq     .L380

+        teq     ip, r3                  @ update weight based on signs

+        submi   r0, r0, r6

+        addpl   r0, r0, r6

+        cmp     r0, #(1024 << 18)               @ then clip weight to +/-1024

+        movgt   r0, #(1024 << 18)

+        cmp     r0, r10

+        movlt   r0, r10

+

+.L380:  ldr     r2, [r1], #8            @ for left channel the decorrelation value

+        movs    lr, lr, asl #4

+        mov     r11, #0x80000000

+        mov     r3, r2

+        smlalne r11, r3, r4, lr

+        strne   r3, [r1, #-8]

+        cmpne   r2, #0

+        beq     .L388

+        teq     r2, lr

+        submi   r4, r4, r6

+        addpl   r4, r4, r6

+        cmp     r4, #(1024 << 18)

+        movgt   r4, #(1024 << 18)

+        cmp     r4, r10

+        movlt   r4, r10

+

+.L388:  cmp     r7, r1                  @ loop back if more samples to do

+        bhi     term_minus_2_loop

+

+        str     r3, [r5, #40]           @ else store left channel and exit

+        b       common_exit

+

+/*

+ ******************************************************************************

+ * Loop to handle term = -3 condition

+ *

+ * r0 = dpp->weight_B           r8 = previous left sample

+ * r1 = bptr                    r9 = 

+ * r2 = current left sample     r10 = -1024 (for clipping)

+ * r3 = previous right sample   r11 = lo accumulator (for rounding)

+ * r4 = dpp->weight_A           ip = intermediate result

+ * r5 = dpp                     sp =

+ * r6 = dpp->delta              lr =

+ * r7 = eptr                    pc =

+ *******************************************************************************

+ */

+

+term_minus_3:

+        ldr     r3, [r1, #-4]           @ load previous samples

+        ldr     r8, [r1, #-8]

+

+term_minus_3_loop:

+        ldr     ip, [r1], #4

+        movs    r3, r3, asl #4

+        mov     r11, #0x80000000

+        mov     r2, ip

+        smlalne r11, r2, r4, r3

+        strne   r2, [r1, #-4]

+        cmpne   ip, #0

+        beq     .L399

+        teq     ip, r3                  @ update weight based on signs

+        submi   r4, r4, r6

+        addpl   r4, r4, r6

+        cmp     r4, #(1024 << 18)       @ then clip weight to +/-1024

+        movgt   r4, #(1024 << 18)

+        cmp     r4, r10

+        movlt   r4, r10

+

+.L399:  movs    ip, r8, asl #4          @ ip = previous left we use now

+        mov     r8, r2                  @ r8 = current left we use next time

+        ldr     r2, [r1], #4

+        mov     r11, #0x80000000

+        mov     r3, r2

+        smlalne r11, r3, r0, ip

+        strne   r3, [r1, #-4]

+        cmpne   r2, #0

+        beq     .L407

+        teq     ip, r2

+        submi   r0, r0, r6

+        addpl   r0, r0, r6

+        cmp     r0, #(1024 << 18)

+        movgt   r0, #(1024 << 18)

+        cmp     r0, r10

+        movlt   r0, r10

+

+.L407:  cmp     r7, r1                  @ loop back if more samples to do

+        bhi     term_minus_3_loop

+

+        str     r3, [r5, #8]            @ else store previous samples & exit

+        str     r8, [r5, #40]

+

+/*

+ * Before finally exiting we must store weights back for next time

+ */

+

+common_exit:

+        mov     r0, r0, asr #18         @ restore weights to real magnitude

+        mov     r4, r4, asr #18

+        strh    r4, [r5, #4]

+        strh    r0, [r5, #6]

+        ldmfd   sp!, {r4 - r8, r10, r11, pc}

+

diff --git a/src/engine/external/wavpack/bits.c b/src/engine/external/wavpack/bits.c
new file mode 100644
index 00000000..dbfa0cae
--- /dev/null
+++ b/src/engine/external/wavpack/bits.c
@@ -0,0 +1,140 @@
+////////////////////////////////////////////////////////////////////////////

+//                           **** WAVPACK ****                            //

+//                  Hybrid Lossless Wavefile Compressor                   //

+//              Copyright (c) 1998 - 2006 Conifer Software.               //

+//                          All Rights Reserved.                          //

+//      Distributed under the BSD Software License (see license.txt)      //

+////////////////////////////////////////////////////////////////////////////

+

+// bits.c

+

+// This module provides utilities to support the BitStream structure which is

+// used to read and write all WavPack audio data streams. It also contains a

+// wrapper for the stream I/O functions and a set of functions dealing with

+// endian-ness, both for enhancing portability. Finally, a debug wrapper for

+// the malloc() system is provided.

+

+#include "wavpack.h"

+

+#include <string.h>

+#include <ctype.h>

+

+////////////////////////// Bitstream functions ////////////////////////////////

+

+// Open the specified BitStream and associate with the specified buffer.

+

+static void bs_read (Bitstream *bs);

+

+void bs_open_read (Bitstream *bs, uchar *buffer_start, uchar *buffer_end, read_stream file, uint32_t file_bytes)

+{

+    CLEAR (*bs);

+    bs->buf = buffer_start;

+    bs->end = buffer_end;

+

+    if (file) {

+        bs->ptr = bs->end - 1;

+        bs->file_bytes = file_bytes;

+        bs->file = file;

+    }

+    else

+        bs->ptr = bs->buf - 1;

+

+    bs->wrap = bs_read;

+}

+

+// This function is only called from the getbit() and getbits() macros when

+// the BitStream has been exhausted and more data is required. Sinve these

+// bistreams no longer access files, this function simple sets an error and

+// resets the buffer.

+

+static void bs_read (Bitstream *bs)

+{

+    if (bs->file && bs->file_bytes) {

+        uint32_t bytes_read, bytes_to_read = bs->end - bs->buf;

+

+        if (bytes_to_read > bs->file_bytes)

+            bytes_to_read = bs->file_bytes;

+

+        bytes_read = bs->file (bs->buf, bytes_to_read);

+

+        if (bytes_read) {

+            bs->end = bs->buf + bytes_read;

+            bs->file_bytes -= bytes_read;

+        }

+        else {

+            memset (bs->buf, -1, bs->end - bs->buf);

+            bs->error = 1;

+        }

+    }

+    else

+        bs->error = 1;

+

+    if (bs->error)

+        memset (bs->buf, -1, bs->end - bs->buf);

+

+    bs->ptr = bs->buf;

+}

+

+/////////////////////// Endian Correction Routines ////////////////////////////

+

+void little_endian_to_native (void *data, char *format)

+{

+    uchar *cp = (uchar *) data;

+    int32_t temp;

+

+    while (*format) {

+        switch (*format) {

+            case 'L':

+                temp = cp [0] + ((int32_t) cp [1] << 8) + ((int32_t) cp [2] << 16) + ((int32_t) cp [3] << 24);

+                * (int32_t *) cp = temp;

+                cp += 4;

+                break;

+

+            case 'S':

+                temp = cp [0] + (cp [1] << 8);

+                * (short *) cp = (short) temp;

+                cp += 2;

+                break;

+

+            default:

+                if (isdigit (*format))

+                    cp += *format - '0';

+

+                break;

+        }

+

+        format++;

+    }

+}

+

+void native_to_little_endian (void *data, char *format)

+{

+    uchar *cp = (uchar *) data;

+    int32_t temp;

+

+    while (*format) {

+        switch (*format) {

+            case 'L':

+                temp = * (int32_t *) cp;

+                *cp++ = (uchar) temp;

+                *cp++ = (uchar) (temp >> 8);

+                *cp++ = (uchar) (temp >> 16);

+                *cp++ = (uchar) (temp >> 24);

+                break;

+

+            case 'S':

+                temp = * (short *) cp;

+                *cp++ = (uchar) temp;

+                *cp++ = (uchar) (temp >> 8);

+                break;

+

+            default:

+                if (isdigit (*format))

+                    cp += *format - '0';

+

+                break;

+        }

+

+        format++;

+    }

+}

diff --git a/src/engine/external/wavpack/coldfire.S b/src/engine/external/wavpack/coldfire.S
new file mode 100644
index 00000000..93df9d82
--- /dev/null
+++ b/src/engine/external/wavpack/coldfire.S
@@ -0,0 +1,525 @@
+////////////////////////////////////////////////////////////////////////////

+//                           **** WAVPACK ****                            //

+//                  Hybrid Lossless Wavefile Compressor                   //

+//              Copyright (c) 1998 - 2006 Conifer Software.               //

+//                          All Rights Reserved.                          //

+//      Distributed under the BSD Software License (see license.txt)      //

+////////////////////////////////////////////////////////////////////////////

+

+/* This is an assembly optimized version of the following WavPack function:

+ *

+ * void decorr_stereo_pass_cont (struct decorr_pass *dpp,

+ *                               long *buffer, long sample_count);

+ *

+ * It performs a single pass of stereo decorrelation on the provided buffer.

+ * Note that this version of the function requires that the 8 previous stereo

+ * samples are visible and correct. In other words, it ignores the "samples_*"

+ * fields in the decorr_pass structure and gets the history data directly

+ * from the buffer. It does, however, return the appropriate history samples

+ * to the decorr_pass structure before returning.

+ *

+ * This is written to work on a MCF5249 processor, or any processor based on

+ * the ColdFire V2 core with an EMAC unit. The EMAC is perfectly suited for

+ * the "apply_weight" function of WavPack decorrelation because it provides

+ * the requires 40-bit product. The fractional rounding mode of the EMAC is not

+ * configurable and uses "round to even" while WavPack uses "round to larger",

+ * so the rounding has to be done manually.

+ */

+

+        .text

+        .align  2

+        .global decorr_stereo_pass_cont_mcf5249

+

+decorr_stereo_pass_cont_mcf5249:

+

+        lea     (-44, %sp), %sp

+        movem.l %d2-%d7/%a2-%a6, (%sp)

+        move.l  44+4(%sp), %a2          | a2 = dpp->

+        move.l  44+8(%sp), %a1          | a1 = bptr

+        move.w  2(%a2), %a3             | a3 = dpp->delta

+        move.w  4(%a2), %d3             | d3 = dpp->weight_A (sign extended)

+        ext.l   %d3

+        move.w  6(%a2), %d4             | d4 = dpp->weight_B (sign extended)

+        ext.l   %d4

+        move.l 44+12(%sp), %d0          | d0 = sample_count

+        jbeq    return_only             | if zero, nothing to do

+

+        lsl.l   #3, %d0                 | d5 = bptr + (sample_count * 8)

+        move.l  %d0, %d5

+        add.l   %a1, %d5

+

+        moveq.l #17, %d0                | left shift weights & delta 17 places

+        asl.l   %d0, %d3

+        asl.l   %d0, %d4

+        move.l  %a3, %d1

+        asl.l   %d0, %d1

+        move.l  %d1, %a3

+

+        moveq.l #0x20, %d6

+        move.l  %d6, %macsr             | set fractional mode for MAC

+        move.l  #0, %acc1               | acc1 = 0x00 0000 80 (for rounding)

+        move.l  #0x800000, %accext01

+        

+        move.l  #1024<<17, %d6          | d6 & d7 are weight clipping limits

+        move.l  #-1024<<17, %d7         | (only used by negative terms)

+

+        move.w  (%a2), %d0              | d0 = term

+        ext.l   %d0

+        cmp.l   #17, %d0

+        jbeq    term_17                 | term = 17

+        cmp.l   #18, %d0

+        jbeq    term_18                 | term = 18

+        addq.l  #1, %d0

+        jbeq    term_minus_1            | term = -1

+        addq.l  #1, %d0

+        jbeq    term_minus_2            | term = -2

+        addq.l  #1, %d0

+        jbeq    term_minus_3            | term = -3

+        jbra    term_default            | default term = 1 - 8

+

+|------------------------------------------------------------------------------

+| Loop to handle term = 17 condition

+|

+| a0 =                          d0 = (2 * bptr [-1]) - bptr [-2]

+| a1 = bptr                     d1 = initial bptr [0]

+| a2 = dpp->                    d2 = updated bptr [0]

+| a3 = dpp->delta << 17         d3 = dpp->weight_A << 17

+| a4 =                          d4 = dpp->weight_B << 17

+| a5 =                          d5 = eptr

+| macsr = 0x20                  acc1 = 0x00 0000 80

+|------------------------------------------------------------------------------

+

+term_17:

+        move.l  -8(%a1), %d0            | d0 = 2 * bptr [-1] - bptr [-2]

+        add.l   %d0, %d0

+        sub.l   -16(%a1), %d0

+        beq     .L251                   | if zero, skip calculation

+        move.l  %acc1, %acc0

+        asl.l   #4, %d0                 | acc0 = acc1 + (d0 << 4) * weight_A

+        mac.l   %d0, %d3, %acc0

+        move.l  (%a1), %d1

+        beq     .L255

+        eor.l   %d1, %d0                | else compare signs

+        bge     .L256                   | if same, add delta to weight

+        sub.l   %a3, %d3                | else subtract delta from weight

+        sub.l   %a3, %d3                | subtract again instead of branch

+.L256:  add.l   %a3, %d3                | add delta to weight

+

+.L255:  move.l  %acc0, %d2              | d2 = rounded product

+        add.l   %d1, %d2                | update bptr [0] and store

+        move.l  %d2, (%a1)+

+

+.L253:  move.l  -8(%a1), %d0            | d0 = 2 * bptr [-1] - bptr [-2]

+        add.l   %d0, %d0

+        sub.l   -16(%a1), %d0

+        beq     .L257                   | if zero, skip calculations

+        move.l  %acc1, %acc0

+        asl.l   #4, %d0                 | acc0 = acc1 + (d0 << 4) * weight_B

+        mac.l   %d0, %d4, %acc0

+        move.l  (%a1), %d1

+        beq     .L254

+        eor.l   %d1, %d0                | else compare signs

+        bge     .L259                   | if same, add delta to weight

+        sub.l   %a3, %d4                | else subtract delta from weight

+        sub.l   %a3, %d4                | subtract again instead of branch

+.L259:  add.l   %a3, %d4                | add delta to weight

+

+.L254:  move.l  %acc0, %d2              | d2 = rounded product

+        add.l   %d1, %d2                | update bptr [0] and store

+        move.l  %d2, (%a1)+

+

+.L252:  cmp.l   %a1, %d5                | loop if bptr < eptr

+        jbhi    term_17

+        bra     term_17_18_finish       | exit through common path

+

+.L251:  addq.l  #4, %a1                 | update point and jump back into loop

+        bra     .L253

+

+.L257:  addq.l  #4, %a1                 | update point and jump back into loop

+        bra     .L252

+

+|------------------------------------------------------------------------------

+| Loop to handle term = 18 condition

+|

+| a0 =                          d0 = ((3 * bptr [-1]) - bptr [-2]) >> 1

+| a1 = bptr                     d1 = initial bptr [0]

+| a2 = dpp->                    d2 = updated bptr [0]

+| a3 = dpp->delta << 17         d3 = dpp->weight_A << 17

+| a4 =                          d4 = dpp->weight_B << 17

+| a5 =                          d5 = eptr

+| macsr = 0x20                  acc1 = 0x00 0000 80

+|------------------------------------------------------------------------------

+

+term_18:

+        move.l  -8(%a1), %a0            | d0 = (3 * bptr [-1] - bptr [-2]) >> 1

+        lea     (%a0,%a0.l*2), %a0

+        move.l  %a0, %d0

+        sub.l   -16(%a1), %d0

+        asr.l   #1, %d0

+        beq     .L260

+        move.l  %acc1, %acc0

+        asl.l   #4, %d0                 | acc0 = acc1 + (d0 << 4) * weight_A

+        mac.l   %d0, %d3, %acc0

+        move.l  (%a1), %d1

+        beq     .L266

+        eor.l   %d1, %d0                | else compare signs

+        bge     .L267                   | if same, add delta to weight

+        sub.l   %a3, %d3                | else subtract delta from weight

+        sub.l   %a3, %d3                | subtract again instead of branch

+.L267:  add.l   %a3, %d3                | add delta to weight

+

+.L266:  move.l  %acc0, %d2              | d2 = rounded product

+        add.l   %d1, %d2                | add applied weight to bptr [0], store

+        move.l  %d2, (%a1)+

+

+.L268:  move.l  -8(%a1), %a0            | d0 = (3 * bptr [-1] - bptr [-2]) >> 1

+        lea     (%a0,%a0.l*2), %a0

+        move.l  %a0, %d0

+        sub.l   -16(%a1), %d0

+        asr.l   #1, %d0

+        beq     .L261

+        move.l  %acc1, %acc0

+        asl.l   #4, %d0                 | acc0 = acc1 + (d0 << 4) * weight_B

+        mac.l   %d0, %d4, %acc0

+        move.l  (%a1), %d1

+        beq     .L265

+        eor.l   %d1, %d0                | else compare signs

+        bge     .L270                   | if same, add delta to weight

+        sub.l   %a3, %d4                | else subtract delta from weight

+        sub.l   %a3, %d4                | subtract again instead of branch

+.L270:  add.l   %a3, %d4                | add delta to weight

+

+.L265:  move.l  %acc0, %d2              | d2 = rounded product

+        add.l   %d1, %d2                | add applied weight to bptr [0], store

+        move.l  %d2, (%a1)+

+

+.L269:  cmp.l   %a1, %d5                | loop if bptr < eptr

+        jbhi    term_18

+        bra     term_17_18_finish       | exit through common path

+

+.L260:  addq.l  #4, %a1                 | bump pointer and jump back into loop

+        bra     .L268

+

+.L261:  addq.l  #4, %a1                 | bump pointer and jump back into loop

+        bra     .L269

+

+term_17_18_finish:

+        move.l  -4(%a1), 40(%a2)        | restore dpp->samples_A [0-1], B [0-1]

+        move.l  -8(%a1), 8(%a2)

+        move.l  -12(%a1), 44(%a2)

+        move.l  -16(%a1), 12(%a2)

+        jbra    finish_up

+

+|------------------------------------------------------------------------------

+| Loop to handle default terms (i.e. 1 - 8)

+|

+| a0 = tptr                     d0 = tptr [0]

+| a1 = bptr                     d1 = initial bptr [0]

+| a2 = dpp->                    d2 = updated bptr [0]

+| a3 = dpp->delta << 17         d3 = dpp->weight_A << 17

+| a4 =                          d4 = dpp->weight_B << 17

+| a5 =                          d5 = eptr

+| macsr = 0x20                  acc1 = 0x00 0000 80

+|------------------------------------------------------------------------------

+

+term_default:

+        move.w  (%a2), %d0              | a0 = a1 - (dpp->term * 8)

+        ext.l   %d0

+        lsl.l   #3, %d0

+        move.l  %a1, %a0

+        sub.l   %d0, %a0

+

+term_default_loop:

+        move.l  (%a0)+, %d0             | d0 = tptr [0], skip ahead if zero

+        beq     .L271

+        move.l  %acc1, %acc0

+        asl.l   #4, %d0                 | acc0 = acc1 + (d0 << 4) * weight_A

+        mac.l   %d0, %d3, %acc0

+        move.l  (%a1), %d1

+        beq     .L277

+        eor.l   %d1, %d0                | else compare signs

+        bge     .L278                   | if same, add delta to weight

+        sub.l   %a3, %d3                | else subtract delta from weight

+        sub.l   %a3, %d3                | subtract again instead of branch

+.L278:  add.l   %a3, %d3                | add delta to weight

+

+.L277:  move.l  %acc0, %d2              | d2 = rounded product

+        add.l   %d1, %d2                | add applied weight to bptr [0], store

+        move.l  %d2, (%a1)+

+

+.L275:  move.l  (%a0)+, %d0             | d0 = tptr [0], skip ahead if zero

+        beq     .L272

+        move.l  %acc1, %acc0

+        asl.l   #4, %d0                 | acc0 = acc1 + (d0 << 4) * weight_B

+        mac.l   %d0, %d4, %acc0

+        move.l  (%a1), %d1

+        beq     .L276

+        eor.l   %d1, %d0                | else compare signs

+        bge     .L281                   | if same, add delta to weight

+        sub.l   %a3, %d4                | else subtract delta from weight

+        sub.l   %a3, %d4                | subtract again instead of branch

+.L281:  add.l   %a3, %d4                | add delta to weight

+

+.L276:  move.l  %acc0, %d2              | d2 = rounded product

+        add.l   %d1, %d2                | add applied weight to bptr [0], store

+        move.l  %d2, (%a1)+

+

+.L274:  cmp.l   %a1, %d5                | loop back if bptr < eptr

+        jbhi    term_default_loop

+        move.w  (%a2), %d0              | d0 = term - 1

+        moveq.l #8, %d1                 | d1 = loop counter

+

+.L323:  subq.l  #1, %d0                 | back up & mask index

+        and.l   #7, %d0

+        move.l  -(%a1), 40(%a2,%d0.l*4) | store dpp->samples_B [d0]

+        move.l  -(%a1), 8(%a2,%d0.l*4)  | store dpp->samples_A [d0]

+        subq.l  #1, %d1                 | loop on count

+        jbne    .L323

+        jbra    finish_up

+

+.L271:  addq.l  #4, %a1                 | bump pointer and jump back into loop

+        bra     .L275

+

+.L272:  addq.l  #4, %a1                 | bump pointer and jump back into loop

+        bra     .L274

+

+

+|------------------------------------------------------------------------------

+| Loop to handle term = -1 condition

+|

+| a0 =                          d0 = decorrelation sample

+| a1 = bptr                     d1 = initial bptr [0]

+| a2 = dpp->                    d2 = updated bptr [0]

+| a3 = dpp->delta << 17         d3 = dpp->weight_A << 17

+| a4 =                          d4 = dpp->weight_B << 17

+| a5 =                          d5 = eptr

+| a6 =                          d6 = 1024 << 17

+| a7 =                          d7 = -1024 << 17

+| macsr = 0x20                  acc1 = 0x00 0000 80

+|------------------------------------------------------------------------------

+

+term_minus_1:

+        move.l  -4(%a1), %d0            | d0 = bptr [-1]

+        beq     .L402

+        move.l  %acc1, %acc0

+        asl.l   #4, %d0                 | acc0 = acc1 + ((d0 << 4) * weight_A)

+        mac.l   %d0, %d3, %acc0

+        move.l  (%a1), %d1

+        beq     .L405

+        eor.l   %d1, %d0                | else compare signs

+        bge     .L404                   | if same, add delta to weight

+        sub.l   %a3, %d3                | else subtract delta from weight

+        cmp.l   %d7, %d3                | check for negative clip limit

+        bge     .L405

+        move.l  %d7, %d3

+        bra     .L405

+

+.L404:  add.l   %a3, %d3                | add delta to weight

+        cmp.l   %d6, %d3                | check for positive clip limit

+        ble     .L405

+        move.l  %d6, %d3

+

+.L405:  move.l  %acc0, %d0              | d2 = rounded product

+        add.l   %d1, %d0                | add applied weight to bptr [0], store

+        move.l  %d0, (%a1)+

+        beq     .L401

+

+.L410:  move.l  %acc1, %acc0

+        asl.l   #4, %d0                 | acc0 = acc1 + ((d0 << 4) * weight_B)

+        mac.l   %d0, %d4, %acc0

+        move.l  (%a1), %d1

+        beq     .L403

+        eor.l   %d1, %d0                | else compare signs

+        bge     .L407                   | if same, add delta to weight

+        sub.l   %a3, %d4                | else subtract delta from weight

+        cmp.l   %d7, %d4                | check for negative clip limit

+        bge     .L403

+        move.l  %d7, %d4

+        bra     .L403

+

+.L407:  add.l   %a3, %d4                | add delta to weight

+        cmp.l   %d6, %d4                | check for positive clip limit

+        ble     .L403

+        move.l  %d6, %d4

+

+.L403:  move.l  %acc0, %d2              | d2 = rounded product

+        add.l   %d1, %d2                | add applied weight to bptr [1], store

+        move.l  %d2, (%a1)+

+

+.L411:  cmp.l   %a1, %d5                | loop back if bptr < eptr

+        jbhi    term_minus_1

+        move.l  -4(%a1), 8(%a2)         | dpp->samples_A [0] = bptr [-1]

+        jbra    finish_up

+

+.L402:  move.l  (%a1)+, %d0

+        bne     .L410

+

+.L401:  addq.l  #4, %a1

+        bra     .L411

+

+

+|------------------------------------------------------------------------------

+| Loop to handle term = -2 condition

+|

+| a0 =                          d0 = decorrelation sample

+| a1 = bptr                     d1 = initial bptr [0]

+| a2 = dpp->                    d2 = updated bptr [0]

+| a3 = dpp->delta << 17         d3 = dpp->weight_A << 17

+| a4 =                          d4 = dpp->weight_B << 17

+| a5 =                          d5 = eptr

+| a6 =                          d6 = 1024 << 17

+| a7 =                          d7 = -1024 << 17

+| macsr = 0x20                  acc1 = 0x00 0000 80

+|------------------------------------------------------------------------------

+

+term_minus_2:

+        move.l  -8(%a1), %d0            | d0 = bptr [-2]

+        beq     .L511

+        move.l  %acc1, %acc0

+        asl.l   #4, %d0                 | acc0 = acc1 + ((d0 << 4) * weight_B)

+        mac.l   %d0, %d4, %acc0

+        move.l  4(%a1), %d1

+        beq     .L505

+        eor.l   %d1, %d0                | else compare signs

+        bge     .L504                   | if same, add delta to weight

+        sub.l   %a3, %d4                | else subtract delta from weight

+        cmp.l   %d7, %d4                | ckeck for negative clip limit

+        bge     .L505

+        move.l  %d7, %d4

+        bra     .L505

+

+.L504:  add.l   %a3, %d4                | add delta to weight

+        cmp.l   %d6, %d4                | check for positive clip limit

+        ble     .L505

+        move.l  %d6, %d4

+

+.L505:  move.l  %acc0, %d0              | d2 = rounded product

+        add.l   %d1, %d0                | add applied weight to bptr [0], store

+        move.l  %d0, 4(%a1)

+        beq     .L512

+

+.L510:  move.l  %acc1, %acc0

+        asl.l   #4, %d0                 | acc0 = acc1 + ((d0 << 4) * weight_A)

+        mac.l   %d0, %d3, %acc0

+        move.l  (%a1), %d1

+        beq     .L503

+        eor.l   %d1, %d0                | else compare signs

+        bge     .L507                   | if same, add delta to weight

+        sub.l   %a3, %d3                | else subtract delta from weight

+        cmp.l   %d7, %d3                | check for negative clip limit

+        bge     .L503

+        move.l  %d7, %d3

+        bra     .L503

+

+.L507:  add.l   %a3, %d3                | add delta to weight

+        cmp.l   %d6, %d3                | check for negative clip limit

+        ble     .L503

+        move.l  %d6, %d3

+

+.L503:  move.l  %acc0, %d2              | d2 = rounded product

+        add.l   %d1, %d2                | add applied weight to bptr [1], store

+        move.l  %d2, (%a1)

+

+.L512:  addq.l  #8, %a1

+        cmp.l   %a1, %d5                | loop if bptr < eptr

+        jbhi    term_minus_2

+        move.l  -8(%a1), 40(%a2)        | dpp->samples_B [0] = bptr [-4]

+        jbra    finish_up

+

+.L511:  move.l  4(%a1), %d0

+        beq     .L512

+        bra     .L510

+

+

+|------------------------------------------------------------------------------

+| Loop to handle term = -3 condition

+|

+| a0 =                          d0 = decorrelation sample

+| a1 = bptr                     d1 = initial bptr [0]

+| a2 = dpp->                    d2 = updated bptr [0]

+| a3 = dpp->delta << 17         d3 = dpp->weight_A << 17

+| a4 =                          d4 = dpp->weight_B << 17

+| a5 =                          d5 = eptr

+| a6 =                          d6 = 1024 << 17

+| a7 =                          d7 = -1024 << 17

+| macsr = 0x20                  acc1 = 0x00 0000 80

+|------------------------------------------------------------------------------

+

+term_minus_3:

+        move.l  -4(%a1), %d0            | d0 = bptr [-1]

+        beq     .L301

+        move.l  %acc1, %acc0

+        asl.l   #4, %d0                 | acc0 = acc1 + ((d0 << 4) * weight_A)

+        mac.l   %d0, %d3, %acc0

+        move.l  (%a1), %d1

+        beq     .L320

+        eor.l   %d1, %d0                | else compare signs

+        bge     .L319                   | if same, add delta to weight

+        sub.l   %a3, %d3                | else subtract delta from weight

+        cmp.l   %d7, %d3                | check for negative clip limit

+        bge     .L320

+        move.l  %d7, %d3

+        bra     .L320

+

+.L319:  add.l   %a3, %d3                | add delta to weight

+        cmp.l   %d6, %d3                | check for positive clip limit

+        ble     .L320

+        move.l  %d6, %d3

+

+.L320:  move.l  %acc0, %d2              | d2 = rounded product

+        add.l   %d1, %d2                | add applied weight to bptr [0], store

+        move.l  %d2, (%a1)+

+

+.L330:  move.l  -12(%a1), %d0           | d0 = bptr [-2]

+        beq     .L302

+        move.l  %acc1, %acc0

+        asl.l   #4, %d0                 | acc0 = acc1 + ((d0 << 4) * weight_B)

+        mac.l   %d0, %d4, %acc0

+        move.l  (%a1), %d1

+        beq     .L318

+        eor.l   %d1, %d0                | else compare signs

+        bge     .L322                   | if same, add delta to weight

+        sub.l   %a3, %d4                | else subtract delta from weight

+        cmp.l   %d7, %d4                | check for negative clip limit

+        bge     .L318

+        move.l  %d7, %d4

+        bra     .L318

+

+.L322:  add.l   %a3, %d4                | add delta to weight

+        cmp.l   %d6, %d4                | check for positive clip limit

+        ble     .L318

+        move.l  %d6, %d4

+

+.L318:  move.l  %acc0, %d2              | d2 = rounded product

+        add.l   %d1, %d2                | add applied weight to bptr [1], store

+        move.l  %d2, (%a1)+

+

+.L331:  cmp.l   %a1, %d5                | bptr, eptr

+        jbhi    term_minus_3

+        move.l  -4(%a1), 8(%a2)         | dpp->samples_A [0] = bptr [-1]

+        move.l  -8(%a1), 40(%a2)        | dpp->samples_B [0] = bptr [-2]

+        jbra    finish_up

+

+.L301:  addq.l  #4, %a1

+        bra     .L330

+

+.L302:  addq.l  #4, %a1

+        bra     .L331

+

+| finish and return

+

+finish_up:

+        moveq.l #17, %d0

+        asr.l   %d0, %d3

+        asr.l   %d0, %d4

+        move.w  %d3, 4(%a2)     | weight_A, dpp->weight_A

+        move.w  %d4, 6(%a2)     | weight_B, dpp->weight_B

+

+        clr.l   %d0             | clear up EMAC

+        move.l  %d0, %acc0

+        move.l  %d0, %acc1

+

+return_only:

+        movem.l (%sp), %d2-%d7/%a2-%a6

+        lea     (44,%sp), %sp

+        rts

diff --git a/src/engine/external/wavpack/float.c b/src/engine/external/wavpack/float.c
new file mode 100644
index 00000000..4b9b44ee
--- /dev/null
+++ b/src/engine/external/wavpack/float.c
@@ -0,0 +1,50 @@
+////////////////////////////////////////////////////////////////////////////

+//                           **** WAVPACK ****                            //

+//                  Hybrid Lossless Wavefile Compressor                   //

+//              Copyright (c) 1998 - 2006 Conifer Software.               //

+//                          All Rights Reserved.                          //

+//      Distributed under the BSD Software License (see license.txt)      //

+////////////////////////////////////////////////////////////////////////////

+

+// float.c

+

+#include "wavpack.h"

+

+int read_float_info (WavpackStream *wps, WavpackMetadata *wpmd)

+{

+    int bytecnt = wpmd->byte_length;

+    char *byteptr = wpmd->data;

+

+    if (bytecnt != 4)

+        return FALSE;

+

+    wps->float_flags = *byteptr++;

+    wps->float_shift = *byteptr++;

+    wps->float_max_exp = *byteptr++;

+    wps->float_norm_exp = *byteptr;

+    return TRUE;

+}

+

+void float_values (WavpackStream *wps, int32_t *values, int32_t num_values)

+{

+    int shift = wps->float_max_exp - wps->float_norm_exp + wps->float_shift;

+

+    if (shift > 32)

+        shift = 32;

+    else if (shift < -32)

+        shift = -32;

+

+    while (num_values--) {

+        if (shift > 0)

+            *values <<= shift;

+        else if (shift < 0)

+            *values >>= -shift;

+

+        if (*values > 8388607L)

+            *values = 8388607L;

+        else if (*values < -8388608L)

+            *values = -8388608L;

+

+        values++;

+    }

+}

diff --git a/src/engine/external/wavpack/license.txt b/src/engine/external/wavpack/license.txt
new file mode 100644
index 00000000..98f6e6b1
--- /dev/null
+++ b/src/engine/external/wavpack/license.txt
@@ -0,0 +1,25 @@
+               Copyright (c) 1998 - 2006 Conifer Software

+                          All rights reserved.

+

+Redistribution and use in source and binary forms, with or without

+modification, are permitted provided that the following conditions are met:

+

+    * Redistributions of source code must retain the above copyright notice,

+      this list of conditions and the following disclaimer.

+    * Redistributions in binary form must reproduce the above copyright notice,

+      this list of conditions and the following disclaimer in the

+      documentation and/or other materials provided with the distribution.

+    * Neither the name of Conifer Software nor the names of its contributors

+      may be used to endorse or promote products derived from this software

+      without specific prior written permission.

+

+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"

+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE

+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE

+ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR

+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL

+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR

+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER

+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,

+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE

+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

diff --git a/src/engine/external/wavpack/metadata.c b/src/engine/external/wavpack/metadata.c
new file mode 100644
index 00000000..578b17f9
--- /dev/null
+++ b/src/engine/external/wavpack/metadata.c
@@ -0,0 +1,105 @@
+////////////////////////////////////////////////////////////////////////////

+//                           **** WAVPACK ****                            //

+//                  Hybrid Lossless Wavefile Compressor                   //

+//              Copyright (c) 1998 - 2006 Conifer Software.               //

+//                          All Rights Reserved.                          //

+//      Distributed under the BSD Software License (see license.txt)      //

+////////////////////////////////////////////////////////////////////////////

+

+// metadata.c

+

+// This module handles the metadata structure introduced in WavPack 4.0

+

+#include "wavpack.h"

+

+int read_metadata_buff (WavpackContext *wpc, WavpackMetadata *wpmd)

+{

+    uchar tchar;

+

+    if (!wpc->infile (&wpmd->id, 1) || !wpc->infile (&tchar, 1))

+        return FALSE;

+

+    wpmd->byte_length = tchar << 1;

+

+    if (wpmd->id & ID_LARGE) {

+        wpmd->id &= ~ID_LARGE;

+

+        if (!wpc->infile (&tchar, 1))

+            return FALSE;

+

+        wpmd->byte_length += (int32_t) tchar << 9; 

+

+        if (!wpc->infile (&tchar, 1))

+            return FALSE;

+

+        wpmd->byte_length += (int32_t) tchar << 17;

+    }

+

+    if (wpmd->id & ID_ODD_SIZE) {

+        wpmd->id &= ~ID_ODD_SIZE;

+        wpmd->byte_length--;

+    }

+

+    if (wpmd->byte_length && wpmd->byte_length <= sizeof (wpc->read_buffer)) {

+        uint32_t bytes_to_read = wpmd->byte_length + (wpmd->byte_length & 1);

+

+        if (wpc->infile (wpc->read_buffer, bytes_to_read) != (int32_t) bytes_to_read) {

+            wpmd->data = NULL;

+            return FALSE;

+        }

+

+        wpmd->data = wpc->read_buffer;

+    }

+    else

+        wpmd->data = NULL;

+

+    return TRUE;

+}

+

+int process_metadata (WavpackContext *wpc, WavpackMetadata *wpmd)

+{

+    WavpackStream *wps = &wpc->stream;

+

+    switch (wpmd->id) {

+        case ID_DUMMY:

+            return TRUE;

+

+        case ID_DECORR_TERMS:

+            return read_decorr_terms (wps, wpmd);

+

+        case ID_DECORR_WEIGHTS:

+            return read_decorr_weights (wps, wpmd);

+

+        case ID_DECORR_SAMPLES:

+            return read_decorr_samples (wps, wpmd);

+

+        case ID_ENTROPY_VARS:

+            return read_entropy_vars (wps, wpmd);

+

+        case ID_HYBRID_PROFILE:

+            return read_hybrid_profile (wps, wpmd);

+

+        case ID_FLOAT_INFO:

+            return read_float_info (wps, wpmd);

+

+        case ID_INT32_INFO:

+            return read_int32_info (wps, wpmd);

+

+        case ID_CHANNEL_INFO:

+            return read_channel_info (wpc, wpmd);

+

+        case ID_CONFIG_BLOCK:

+            return read_config_info (wpc, wpmd);

+

+        case ID_WV_BITSTREAM:

+            return init_wv_bitstream (wpc, wpmd);

+

+        case ID_SHAPING_WEIGHTS:

+        case ID_WVC_BITSTREAM:

+        case ID_WVX_BITSTREAM:

+            return TRUE;

+

+        default:

+            return (wpmd->id & ID_OPTIONAL_DATA) ? TRUE : FALSE;

+    }

+}

diff --git a/src/engine/external/wavpack/readme.txt b/src/engine/external/wavpack/readme.txt
new file mode 100644
index 00000000..4ccbdf42
--- /dev/null
+++ b/src/engine/external/wavpack/readme.txt
@@ -0,0 +1,68 @@
+////////////////////////////////////////////////////////////////////////////

+//                           **** WAVPACK ****                            //

+//                  Hybrid Lossless Wavefile Compressor                   //

+//              Copyright (c) 1998 - 2006 Conifer Software.               //

+//                          All Rights Reserved.                          //

+//      Distributed under the BSD Software License (see license.txt)      //

+////////////////////////////////////////////////////////////////////////////

+

+This package contains a tiny version of the WavPack 4.40 decoder that might

+be used in a "resource limited" CPU environment or form the basis for a

+hardware decoding implementation. It is packaged with a demo command-line

+program that accepts a WavPack audio file on stdin and outputs a RIFF wav

+file to stdout. The program is standard C, and a win32 executable is

+included which was compiled under MS Visual C++ 6.0 using this command:

+

+cl /O1 /DWIN32 wvfilter.c wputils.c unpack.c float.c metadata.c words.c bits.c

+

+WavPack data is read with a stream reading callback. No direct seeking is

+provided for, but it is possible to start decoding anywhere in a WavPack

+stream. In this case, WavPack will be able to provide the sample-accurate

+position when it synchs with the data and begins decoding. The WIN32 macro

+is used for Windows to force the stdin and stdout streams to be binary mode.

+

+Compared to the previous version, this library has been optimized somewhat

+for improved performance in exchange for slightly larger code size. The

+library also now includes hand-optimized assembly language versions of the

+decorrelation functions for both the ColdFire (w/EMAC) and ARM processors.

+

+For demonstration purposes this uses a single static copy of the

+WavpackContext structure, so obviously it cannot be used for more than one

+file at a time. Also, this decoder will not handle "correction" files, plays

+only the first two channels of multi-channel files, and is limited in

+resolution in some large integer or floating point files (but always

+provides at least 24 bits of resolution). It also will not accept WavPack

+files from before version 4.0.

+

+The previous version of this library would handle float files by returning

+32-bit floating-point data (even though no floating point math was used).

+Because this library would normally be used for simply playing WavPack

+files where lossless performance (beyond 24-bits) is not relevant, I have

+changed this behavior. Now, these files will generate clipped 24-bit data.

+The MODE_FLOAT flag will still be returned by WavpackGetMode(), but the

+BitsPerSample and BytesPerSample queries will be 24 and 3, respectfully.

+What this means is that an application that can handle 24-bit data will

+now be able to handle floating point data (assuming that the MODE_FLOAT

+flag is ignored).

+

+To make this code viable on the greatest number of hardware platforms, the

+following are true:

+

+   speed is about 5x realtime on an AMD K6 300 MHz

+      ("high" mode 16/44 stereo; normal mode is about twice that fast)

+

+   no floating-point math required; just 32b * 32b = 32b int multiply

+

+   large data areas are static and less than 4K total

+   executable code and tables are less than 40K

+   no malloc / free usage

+

+To maintain compatibility on various platforms, the following conventions

+are used:

+

+   a "char" must be exactly 8-bits

+   a "short" must be exactly 16-bits

+   an "int" must be at least 16-bits, but may be larger

+   the "long" type is not used to avoid problems with 64-bit compilers

+

+Questions or comments should be directed to david@wavpack.com

diff --git a/src/engine/external/wavpack/unpack.c b/src/engine/external/wavpack/unpack.c
new file mode 100644
index 00000000..2bed5a0c
--- /dev/null
+++ b/src/engine/external/wavpack/unpack.c
@@ -0,0 +1,785 @@
+////////////////////////////////////////////////////////////////////////////

+//                           **** WAVPACK ****                            //

+//                  Hybrid Lossless Wavefile Compressor                   //

+//              Copyright (c) 1998 - 2006 Conifer Software.               //

+//                          All Rights Reserved.                          //

+//      Distributed under the BSD Software License (see license.txt)      //

+////////////////////////////////////////////////////////////////////////////

+

+// unpack.c

+

+// This module actually handles the decompression of the audio data, except

+// for the entropy decoding which is handled by the words.c module. For

+// maximum efficiency, the conversion is isolated to tight loops that handle

+// an entire buffer.

+

+#include "wavpack.h"

+

+#include <stdlib.h>

+#include <string.h>

+

+#define LOSSY_MUTE

+

+///////////////////////////// executable code ////////////////////////////////

+

+// This function initializes everything required to unpack a WavPack block

+// and must be called before unpack_samples() is called to obtain audio data.

+// It is assumed that the WavpackHeader has been read into the wps->wphdr

+// (in the current WavpackStream). This is where all the metadata blocks are

+// scanned up to the one containing the audio bitstream.

+

+int unpack_init (WavpackContext *wpc)

+{

+    WavpackStream *wps = &wpc->stream;

+    WavpackMetadata wpmd;

+

+    if (wps->wphdr.block_samples && wps->wphdr.block_index != (uint32_t) -1)

+        wps->sample_index = wps->wphdr.block_index;

+

+    wps->mute_error = FALSE;

+    wps->crc = 0xffffffff;

+    CLEAR (wps->wvbits);

+    CLEAR (wps->decorr_passes);

+    CLEAR (wps->w);

+

+    while (read_metadata_buff (wpc, &wpmd)) {

+        if (!process_metadata (wpc, &wpmd)) {

+            strcpy (wpc->error_message, "invalid metadata!");

+            return FALSE;

+        }

+

+        if (wpmd.id == ID_WV_BITSTREAM)

+            break;

+    }

+

+    if (wps->wphdr.block_samples && !bs_is_open (&wps->wvbits)) {

+        strcpy (wpc->error_message, "invalid WavPack file!");

+        return FALSE;

+    }

+

+    if (wps->wphdr.block_samples) {

+        if ((wps->wphdr.flags & INT32_DATA) && wps->int32_sent_bits)

+            wpc->lossy_blocks = TRUE;

+

+        if ((wps->wphdr.flags & FLOAT_DATA) &&

+            wps->float_flags & (FLOAT_EXCEPTIONS | FLOAT_ZEROS_SENT | FLOAT_SHIFT_SENT | FLOAT_SHIFT_SAME))

+                wpc->lossy_blocks = TRUE;

+    }

+

+    return TRUE;

+}

+

+// This function initialzes the main bitstream for audio samples, which must

+// be in the "wv" file.

+

+int init_wv_bitstream (WavpackContext *wpc, WavpackMetadata *wpmd)

+{

+    WavpackStream *wps = &wpc->stream;

+

+    if (wpmd->data)

+        bs_open_read (&wps->wvbits, wpmd->data, (unsigned char *) wpmd->data + wpmd->byte_length, NULL, 0);

+    else if (wpmd->byte_length)

+        bs_open_read (&wps->wvbits, wpc->read_buffer, wpc->read_buffer + sizeof (wpc->read_buffer),

+            wpc->infile, wpmd->byte_length + (wpmd->byte_length & 1));

+

+    return TRUE;

+}

+

+// Read decorrelation terms from specified metadata block into the

+// decorr_passes array. The terms range from -3 to 8, plus 17 & 18;

+// other values are reserved and generate errors for now. The delta

+// ranges from 0 to 7 with all values valid. Note that the terms are

+// stored in the opposite order in the decorr_passes array compared

+// to packing.

+

+int read_decorr_terms (WavpackStream *wps, WavpackMetadata *wpmd)

+{

+    int termcnt = wpmd->byte_length;

+    uchar *byteptr = wpmd->data;

+    struct decorr_pass *dpp;

+

+    if (termcnt > MAX_NTERMS)

+        return FALSE;

+

+    wps->num_terms = termcnt;

+

+    for (dpp = wps->decorr_passes + termcnt - 1; termcnt--; dpp--) {

+        dpp->term = (int)(*byteptr & 0x1f) - 5;

+        dpp->delta = (*byteptr++ >> 5) & 0x7;

+

+        if (!dpp->term || dpp->term < -3 || (dpp->term > MAX_TERM && dpp->term < 17) || dpp->term > 18)

+            return FALSE;

+    }

+

+    return TRUE;

+}

+

+// Read decorrelation weights from specified metadata block into the

+// decorr_passes array. The weights range +/-1024, but are rounded and

+// truncated to fit in signed chars for metadata storage. Weights are

+// separate for the two channels and are specified from the "last" term

+// (first during encode). Unspecified weights are set to zero.

+

+int read_decorr_weights (WavpackStream *wps, WavpackMetadata *wpmd)

+{

+    int termcnt = wpmd->byte_length, tcount;

+    signed char *byteptr = wpmd->data;

+    struct decorr_pass *dpp;

+

+    if (!(wps->wphdr.flags & MONO_DATA))

+        termcnt /= 2;

+

+    if (termcnt > wps->num_terms)

+        return FALSE;

+

+    for (tcount = wps->num_terms, dpp = wps->decorr_passes; tcount--; dpp++)

+        dpp->weight_A = dpp->weight_B = 0;

+

+    while (--dpp >= wps->decorr_passes && termcnt--) {

+        dpp->weight_A = restore_weight (*byteptr++);

+

+        if (!(wps->wphdr.flags & MONO_DATA))

+            dpp->weight_B = restore_weight (*byteptr++);

+    }

+

+    return TRUE;

+}

+

+// Read decorrelation samples from specified metadata block into the

+// decorr_passes array. The samples are signed 32-bit values, but are

+// converted to signed log2 values for storage in metadata. Values are

+// stored for both channels and are specified from the "last" term

+// (first during encode) with unspecified samples set to zero. The

+// number of samples stored varies with the actual term value, so

+// those must obviously come first in the metadata.

+

+int read_decorr_samples (WavpackStream *wps, WavpackMetadata *wpmd)

+{

+    uchar *byteptr = wpmd->data;

+    uchar *endptr = byteptr + wpmd->byte_length;

+    struct decorr_pass *dpp;

+    int tcount;

+

+    for (tcount = wps->num_terms, dpp = wps->decorr_passes; tcount--; dpp++) {

+        CLEAR (dpp->samples_A);

+        CLEAR (dpp->samples_B);

+    }

+

+    if (wps->wphdr.version == 0x402 && (wps->wphdr.flags & HYBRID_FLAG)) {

+        byteptr += 2;

+

+        if (!(wps->wphdr.flags & MONO_DATA))

+            byteptr += 2;

+    }

+

+    while (dpp-- > wps->decorr_passes && byteptr < endptr)

+        if (dpp->term > MAX_TERM) {

+            dpp->samples_A [0] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8)));

+            dpp->samples_A [1] = exp2s ((short)(byteptr [2] + (byteptr [3] << 8)));

+            byteptr += 4;

+

+            if (!(wps->wphdr.flags & MONO_DATA)) {

+                dpp->samples_B [0] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8)));

+                dpp->samples_B [1] = exp2s ((short)(byteptr [2] + (byteptr [3] << 8)));

+                byteptr += 4;

+            }

+        }

+        else if (dpp->term < 0) {

+            dpp->samples_A [0] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8)));

+            dpp->samples_B [0] = exp2s ((short)(byteptr [2] + (byteptr [3] << 8)));

+            byteptr += 4;

+        }

+        else {

+            int m = 0, cnt = dpp->term;

+

+            while (cnt--) {

+                dpp->samples_A [m] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8)));

+                byteptr += 2;

+

+                if (!(wps->wphdr.flags & MONO_DATA)) {

+                    dpp->samples_B [m] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8)));

+                    byteptr += 2;

+                }

+

+                m++;

+            }

+        }

+

+    return byteptr == endptr;

+}

+

+// Read the int32 data from the specified metadata into the specified stream.

+// This data is used for integer data that has more than 24 bits of magnitude

+// or, in some cases, used to eliminate redundant bits from any audio stream.

+

+int read_int32_info (WavpackStream *wps, WavpackMetadata *wpmd)

+{

+    int bytecnt = wpmd->byte_length;

+    char *byteptr = wpmd->data;

+

+    if (bytecnt != 4)

+        return FALSE;

+

+    wps->int32_sent_bits = *byteptr++;

+    wps->int32_zeros = *byteptr++;

+    wps->int32_ones = *byteptr++;

+    wps->int32_dups = *byteptr;

+    return TRUE;

+}

+

+// Read multichannel information from metadata. The first byte is the total

+// number of channels and the following bytes represent the channel_mask

+// as described for Microsoft WAVEFORMATEX.

+

+int read_channel_info (WavpackContext *wpc, WavpackMetadata *wpmd)

+{

+    int bytecnt = wpmd->byte_length, shift = 0;

+    char *byteptr = wpmd->data;

+    uint32_t mask = 0;

+

+    if (!bytecnt || bytecnt > 5)

+        return FALSE;

+

+    wpc->config.num_channels = *byteptr++;

+

+    while (--bytecnt) {

+        mask |= (uint32_t) *byteptr++ << shift;

+        shift += 8;

+    }

+

+    wpc->config.channel_mask = mask;

+    return TRUE;

+}

+

+// Read configuration information from metadata.

+

+int read_config_info (WavpackContext *wpc, WavpackMetadata *wpmd)

+{

+    int bytecnt = wpmd->byte_length;

+    uchar *byteptr = wpmd->data;

+

+    if (bytecnt >= 3) {

+        wpc->config.flags &= 0xff;

+        wpc->config.flags |= (int32_t) *byteptr++ << 8;

+        wpc->config.flags |= (int32_t) *byteptr++ << 16;

+        wpc->config.flags |= (int32_t) *byteptr << 24;

+    }

+

+    return TRUE;

+}

+

+// This monster actually unpacks the WavPack bitstream(s) into the specified

+// buffer as 32-bit integers or floats (depending on orignal data). Lossy

+// samples will be clipped to their original limits (i.e. 8-bit samples are

+// clipped to -128/+127) but are still returned in int32_ts. It is up to the

+// caller to potentially reformat this for the final output including any

+// multichannel distribution, block alignment or endian compensation. The

+// function unpack_init() must have been called and the entire WavPack block

+// must still be visible (although wps->blockbuff will not be accessed again).

+// For maximum clarity, the function is broken up into segments that handle

+// various modes. This makes for a few extra infrequent flag checks, but

+// makes the code easier to follow because the nesting does not become so

+// deep. For maximum efficiency, the conversion is isolated to tight loops

+// that handle an entire buffer. The function returns the total number of

+// samples unpacked, which can be less than the number requested if an error

+// occurs or the end of the block is reached.

+

+#if defined(CPU_COLDFIRE) && !defined(SIMULATOR)

+extern void decorr_stereo_pass_cont_mcf5249 (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count);

+#elif defined(CPU_ARM) && !defined(SIMULATOR)

+extern void decorr_stereo_pass_cont_arm (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count);

+extern void decorr_stereo_pass_cont_arml (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count);

+#else

+static void decorr_stereo_pass_cont (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count);

+#endif

+

+static void decorr_mono_pass (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count);

+static void decorr_stereo_pass (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count);

+static void fixup_samples (WavpackStream *wps, int32_t *buffer, uint32_t sample_count);

+

+int32_t unpack_samples (WavpackContext *wpc, int32_t *buffer, uint32_t sample_count)

+{

+    WavpackStream *wps = &wpc->stream;

+    uint32_t flags = wps->wphdr.flags, crc = wps->crc, i;

+    int32_t mute_limit = (1L << ((flags & MAG_MASK) >> MAG_LSB)) + 2;

+    struct decorr_pass *dpp;

+    int32_t *bptr, *eptr;

+    int tcount;

+

+    if (wps->sample_index + sample_count > wps->wphdr.block_index + wps->wphdr.block_samples)

+        sample_count = wps->wphdr.block_index + wps->wphdr.block_samples - wps->sample_index;

+

+    if (wps->mute_error) {

+        memset (buffer, 0, sample_count * (flags & MONO_FLAG ? 4 : 8));

+        wps->sample_index += sample_count;

+        return sample_count;

+    }

+

+    if (flags & HYBRID_FLAG)

+        mute_limit *= 2;

+

+    ///////////////////// handle version 4 mono data /////////////////////////

+

+    if (flags & MONO_DATA) {

+        eptr = buffer + sample_count;

+        i = get_words (buffer, sample_count, flags, &wps->w, &wps->wvbits);

+

+        for (tcount = wps->num_terms, dpp = wps->decorr_passes; tcount--; dpp++)

+            decorr_mono_pass (dpp, buffer, sample_count);

+

+        for (bptr = buffer; bptr < eptr; ++bptr) {

+            if (labs (bptr [0]) > mute_limit) {

+                i = bptr - buffer;

+                break;

+            }

+

+            crc = crc * 3 + bptr [0];

+        }

+    }

+

+    //////////////////// handle version 4 stereo data ////////////////////////

+

+    else {

+        eptr = buffer + (sample_count * 2);

+        i = get_words (buffer, sample_count, flags, &wps->w, &wps->wvbits);

+

+        if (sample_count < 16)

+            for (tcount = wps->num_terms, dpp = wps->decorr_passes; tcount--; dpp++)

+                decorr_stereo_pass (dpp, buffer, sample_count);

+        else

+            for (tcount = wps->num_terms, dpp = wps->decorr_passes; tcount--; dpp++) {

+                decorr_stereo_pass (dpp, buffer, 8);

+#if defined(CPU_COLDFIRE) && !defined(SIMULATOR)

+                decorr_stereo_pass_cont_mcf5249 (dpp, buffer + 16, sample_count - 8);

+#elif defined(CPU_ARM) && !defined(SIMULATOR)

+                if (((flags & MAG_MASK) >> MAG_LSB) > 15)

+                    decorr_stereo_pass_cont_arml (dpp, buffer + 16, sample_count - 8);

+                else

+                    decorr_stereo_pass_cont_arm (dpp, buffer + 16, sample_count - 8);

+#else

+                decorr_stereo_pass_cont (dpp, buffer + 16, sample_count - 8);

+#endif

+            }

+

+        if (flags & JOINT_STEREO)

+            for (bptr = buffer; bptr < eptr; bptr += 2) {

+                bptr [0] += (bptr [1] -= (bptr [0] >> 1));

+

+                if (labs (bptr [0]) > mute_limit || labs (bptr [1]) > mute_limit) {

+                    i = (bptr - buffer) / 2;

+                    break;

+                }

+

+                crc = (crc * 3 + bptr [0]) * 3 + bptr [1];

+            }

+        else

+            for (bptr = buffer; bptr < eptr; bptr += 2) {

+                if (labs (bptr [0]) > mute_limit || labs (bptr [1]) > mute_limit) {

+                    i = (bptr - buffer) / 2;

+                    break;

+                }

+

+                crc = (crc * 3 + bptr [0]) * 3 + bptr [1];

+            }

+    }

+

+    if (i != sample_count) {

+        memset (buffer, 0, sample_count * (flags & MONO_FLAG ? 4 : 8));

+        wps->mute_error = TRUE;

+        i = sample_count;

+    }

+

+    fixup_samples (wps, buffer, i);

+

+    if (flags & FALSE_STEREO) {

+        int32_t *dptr = buffer + i * 2;

+        int32_t *sptr = buffer + i;

+        int32_t c = i;

+

+        while (c--) {

+            *--dptr = *--sptr;

+            *--dptr = *sptr;

+        }

+    }

+

+    wps->sample_index += i;

+    wps->crc = crc;

+

+    return i;

+}

+

+static void decorr_stereo_pass (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count)

+{

+    int32_t delta = dpp->delta, weight_A = dpp->weight_A, weight_B = dpp->weight_B;

+    int32_t *bptr, *eptr = buffer + (sample_count * 2), sam_A, sam_B;

+    int m, k;

+

+    switch (dpp->term) {

+

+        case 17:

+            for (bptr = buffer; bptr < eptr; bptr += 2) {

+                sam_A = 2 * dpp->samples_A [0] - dpp->samples_A [1];

+                dpp->samples_A [1] = dpp->samples_A [0];

+                dpp->samples_A [0] = apply_weight (weight_A, sam_A) + bptr [0];

+                update_weight (weight_A, delta, sam_A, bptr [0]);

+                bptr [0] = dpp->samples_A [0];

+

+                sam_A = 2 * dpp->samples_B [0] - dpp->samples_B [1];

+                dpp->samples_B [1] = dpp->samples_B [0];

+                dpp->samples_B [0] = apply_weight (weight_B, sam_A) + bptr [1];

+                update_weight (weight_B, delta, sam_A, bptr [1]);

+                bptr [1] = dpp->samples_B [0];

+            }

+

+            break;

+

+        case 18:

+            for (bptr = buffer; bptr < eptr; bptr += 2) {

+                sam_A = (3 * dpp->samples_A [0] - dpp->samples_A [1]) >> 1;

+                dpp->samples_A [1] = dpp->samples_A [0];

+                dpp->samples_A [0] = apply_weight (weight_A, sam_A) + bptr [0];

+                update_weight (weight_A, delta, sam_A, bptr [0]);

+                bptr [0] = dpp->samples_A [0];

+

+                sam_A = (3 * dpp->samples_B [0] - dpp->samples_B [1]) >> 1;

+                dpp->samples_B [1] = dpp->samples_B [0];

+                dpp->samples_B [0] = apply_weight (weight_B, sam_A) + bptr [1];

+                update_weight (weight_B, delta, sam_A, bptr [1]);

+                bptr [1] = dpp->samples_B [0];

+            }

+

+            break;

+

+        default:

+            for (m = 0, k = dpp->term & (MAX_TERM - 1), bptr = buffer; bptr < eptr; bptr += 2) {

+                sam_A = dpp->samples_A [m];

+                dpp->samples_A [k] = apply_weight (weight_A, sam_A) + bptr [0];

+                update_weight (weight_A, delta, sam_A, bptr [0]);

+                bptr [0] = dpp->samples_A [k];

+

+                sam_A = dpp->samples_B [m];

+                dpp->samples_B [k] = apply_weight (weight_B, sam_A) + bptr [1];

+                update_weight (weight_B, delta, sam_A, bptr [1]);

+                bptr [1] = dpp->samples_B [k];

+

+                m = (m + 1) & (MAX_TERM - 1);

+                k = (k + 1) & (MAX_TERM - 1);

+            }

+

+            if (m) {

+                int32_t temp_samples [MAX_TERM];

+

+                memcpy (temp_samples, dpp->samples_A, sizeof (dpp->samples_A));

+

+                for (k = 0; k < MAX_TERM; k++, m++)

+                    dpp->samples_A [k] = temp_samples [m & (MAX_TERM - 1)];

+

+                memcpy (temp_samples, dpp->samples_B, sizeof (dpp->samples_B));

+

+                for (k = 0; k < MAX_TERM; k++, m++)

+                    dpp->samples_B [k] = temp_samples [m & (MAX_TERM - 1)];

+            }

+

+            break;

+

+        case -1:

+            for (bptr = buffer; bptr < eptr; bptr += 2) {

+                sam_A = bptr [0] + apply_weight (weight_A, dpp->samples_A [0]);

+                update_weight_clip (weight_A, delta, dpp->samples_A [0], bptr [0]);

+                bptr [0] = sam_A;

+                dpp->samples_A [0] = bptr [1] + apply_weight (weight_B, sam_A);

+                update_weight_clip (weight_B, delta, sam_A, bptr [1]);

+                bptr [1] = dpp->samples_A [0];

+            }

+

+            break;

+

+        case -2:

+            for (bptr = buffer; bptr < eptr; bptr += 2) {

+                sam_B = bptr [1] + apply_weight (weight_B, dpp->samples_B [0]);

+                update_weight_clip (weight_B, delta, dpp->samples_B [0], bptr [1]);

+                bptr [1] = sam_B;

+                dpp->samples_B [0] = bptr [0] + apply_weight (weight_A, sam_B);

+                update_weight_clip (weight_A, delta, sam_B, bptr [0]);

+                bptr [0] = dpp->samples_B [0];

+            }

+

+            break;

+

+        case -3:

+            for (bptr = buffer; bptr < eptr; bptr += 2) {

+                sam_A = bptr [0] + apply_weight (weight_A, dpp->samples_A [0]);

+                update_weight_clip (weight_A, delta, dpp->samples_A [0], bptr [0]);

+                sam_B = bptr [1] + apply_weight (weight_B, dpp->samples_B [0]);

+                update_weight_clip (weight_B, delta, dpp->samples_B [0], bptr [1]);

+                bptr [0] = dpp->samples_B [0] = sam_A;

+                bptr [1] = dpp->samples_A [0] = sam_B;

+            }

+

+            break;

+    }

+

+    dpp->weight_A = weight_A;

+    dpp->weight_B = weight_B;

+}

+

+#if (!defined(CPU_COLDFIRE) && !defined(CPU_ARM)) || defined(SIMULATOR)

+

+static void decorr_stereo_pass_cont (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count)

+{

+    int32_t delta = dpp->delta, weight_A = dpp->weight_A, weight_B = dpp->weight_B;

+    int32_t *bptr, *tptr, *eptr = buffer + (sample_count * 2), sam_A, sam_B;

+    int k, i;

+

+    switch (dpp->term) {

+

+        case 17:

+            for (bptr = buffer; bptr < eptr; bptr += 2) {

+                sam_A = 2 * bptr [-2] - bptr [-4];

+                bptr [0] = apply_weight (weight_A, sam_A) + (sam_B = bptr [0]);

+                update_weight (weight_A, delta, sam_A, sam_B);

+

+                sam_A = 2 * bptr [-1] - bptr [-3];

+                bptr [1] = apply_weight (weight_B, sam_A) + (sam_B = bptr [1]);

+                update_weight (weight_B, delta, sam_A, sam_B);

+            }

+

+            dpp->samples_B [0] = bptr [-1];

+            dpp->samples_A [0] = bptr [-2];

+            dpp->samples_B [1] = bptr [-3];

+            dpp->samples_A [1] = bptr [-4];

+            break;

+

+        case 18:

+            for (bptr = buffer; bptr < eptr; bptr += 2) {

+                sam_A = (3 * bptr [-2] - bptr [-4]) >> 1;

+                bptr [0] = apply_weight (weight_A, sam_A) + (sam_B = bptr [0]);

+                update_weight (weight_A, delta, sam_A, sam_B);

+

+                sam_A = (3 * bptr [-1] - bptr [-3]) >> 1;

+                bptr [1] = apply_weight (weight_B, sam_A) + (sam_B = bptr [1]);

+                update_weight (weight_B, delta, sam_A, sam_B);

+            }

+

+            dpp->samples_B [0] = bptr [-1];

+            dpp->samples_A [0] = bptr [-2];

+            dpp->samples_B [1] = bptr [-3];

+            dpp->samples_A [1] = bptr [-4];

+            break;

+

+        default:

+            for (bptr = buffer, tptr = buffer - (dpp->term * 2); bptr < eptr; bptr += 2, tptr += 2) {

+                bptr [0] = apply_weight (weight_A, tptr [0]) + (sam_A = bptr [0]);

+                update_weight (weight_A, delta, tptr [0], sam_A);

+

+                bptr [1] = apply_weight (weight_B, tptr [1]) + (sam_A = bptr [1]);

+                update_weight (weight_B, delta, tptr [1], sam_A);

+            }

+

+            for (k = dpp->term - 1, i = 8; i--; k--) {

+                dpp->samples_B [k & (MAX_TERM - 1)] = *--bptr;

+                dpp->samples_A [k & (MAX_TERM - 1)] = *--bptr;

+            }

+

+            break;

+

+        case -1:

+            for (bptr = buffer; bptr < eptr; bptr += 2) {

+                bptr [0] = apply_weight (weight_A, bptr [-1]) + (sam_A = bptr [0]);

+                update_weight_clip (weight_A, delta, bptr [-1], sam_A);

+                bptr [1] = apply_weight (weight_B, bptr [0]) + (sam_A = bptr [1]);

+                update_weight_clip (weight_B, delta, bptr [0], sam_A);

+            }

+

+            dpp->samples_A [0] = bptr [-1];

+            break;

+

+        case -2:

+            for (bptr = buffer; bptr < eptr; bptr += 2) {

+                bptr [1] = apply_weight (weight_B, bptr [-2]) + (sam_A = bptr [1]);

+                update_weight_clip (weight_B, delta, bptr [-2], sam_A);

+                bptr [0] = apply_weight (weight_A, bptr [1]) + (sam_A = bptr [0]);

+                update_weight_clip (weight_A, delta, bptr [1], sam_A);

+            }

+

+            dpp->samples_B [0] = bptr [-2];

+            break;

+

+        case -3:

+            for (bptr = buffer; bptr < eptr; bptr += 2) {

+                bptr [0] = apply_weight (weight_A, bptr [-1]) + (sam_A = bptr [0]);

+                update_weight_clip (weight_A, delta, bptr [-1], sam_A);

+                bptr [1] = apply_weight (weight_B, bptr [-2]) + (sam_A = bptr [1]);

+                update_weight_clip (weight_B, delta, bptr [-2], sam_A);

+            }

+

+            dpp->samples_A [0] = bptr [-1];

+            dpp->samples_B [0] = bptr [-2];

+            break;

+    }

+

+    dpp->weight_A = weight_A;

+    dpp->weight_B = weight_B;

+}

+

+#endif

+

+static void decorr_mono_pass (struct decorr_pass *dpp, int32_t *buffer, int32_t sample_count)

+{

+    int32_t delta = dpp->delta, weight_A = dpp->weight_A;

+    int32_t *bptr, *eptr = buffer + sample_count, sam_A;

+    int m, k;

+

+    switch (dpp->term) {

+

+        case 17:

+            for (bptr = buffer; bptr < eptr; bptr++) {

+                sam_A = 2 * dpp->samples_A [0] - dpp->samples_A [1];

+                dpp->samples_A [1] = dpp->samples_A [0];

+                dpp->samples_A [0] = apply_weight (weight_A, sam_A) + bptr [0];

+                update_weight (weight_A, delta, sam_A, bptr [0]);

+                bptr [0] = dpp->samples_A [0];

+            }

+

+            break;

+

+        case 18:

+            for (bptr = buffer; bptr < eptr; bptr++) {

+                sam_A = (3 * dpp->samples_A [0] - dpp->samples_A [1]) >> 1;

+                dpp->samples_A [1] = dpp->samples_A [0];

+                dpp->samples_A [0] = apply_weight (weight_A, sam_A) + bptr [0];

+                update_weight (weight_A, delta, sam_A, bptr [0]);

+                bptr [0] = dpp->samples_A [0];

+            }

+

+            break;

+

+        default:

+            for (m = 0, k = dpp->term & (MAX_TERM - 1), bptr = buffer; bptr < eptr; bptr++) {

+                sam_A = dpp->samples_A [m];

+                dpp->samples_A [k] = apply_weight (weight_A, sam_A) + bptr [0];

+                update_weight (weight_A, delta, sam_A, bptr [0]);

+                bptr [0] = dpp->samples_A [k];

+                m = (m + 1) & (MAX_TERM - 1);

+                k = (k + 1) & (MAX_TERM - 1);

+            }

+

+            if (m) {

+                int32_t temp_samples [MAX_TERM];

+

+                memcpy (temp_samples, dpp->samples_A, sizeof (dpp->samples_A));

+

+                for (k = 0; k < MAX_TERM; k++, m++)

+                    dpp->samples_A [k] = temp_samples [m & (MAX_TERM - 1)];

+            }

+

+            break;

+    }

+

+    dpp->weight_A = weight_A;

+}

+

+

+// This is a helper function for unpack_samples() that applies several final

+// operations. First, if the data is 32-bit float data, then that conversion

+// is done in the float.c module (whether lossy or lossless) and we return.

+// Otherwise, if the extended integer data applies, then that operation is

+// executed first. If the unpacked data is lossy (and not corrected) then

+// it is clipped and shifted in a single operation. Otherwise, if it's

+// lossless then the last step is to apply the final shift (if any).

+

+static void fixup_samples (WavpackStream *wps, int32_t *buffer, uint32_t sample_count)

+{

+    uint32_t flags = wps->wphdr.flags;

+    int shift = (flags & SHIFT_MASK) >> SHIFT_LSB;

+

+    if (flags & FLOAT_DATA) {

+        float_values (wps, buffer, (flags & MONO_FLAG) ? sample_count : sample_count * 2);

+        return;

+    }

+

+    if (flags & INT32_DATA) {

+        uint32_t count = (flags & MONO_FLAG) ? sample_count : sample_count * 2;

+        int sent_bits = wps->int32_sent_bits, zeros = wps->int32_zeros;

+        int ones = wps->int32_ones, dups = wps->int32_dups;

+        int32_t *dptr = buffer;

+

+        if (!(flags & HYBRID_FLAG) && !sent_bits && (zeros + ones + dups))

+            while (count--) {

+                if (zeros)

+                    *dptr <<= zeros;

+                else if (ones)

+                    *dptr = ((*dptr + 1) << ones) - 1;

+                else if (dups)

+                    *dptr = ((*dptr + (*dptr & 1)) << dups) - (*dptr & 1);

+

+                dptr++;

+            }

+        else

+            shift += zeros + sent_bits + ones + dups;

+    }

+

+    if (flags & HYBRID_FLAG) {

+        int32_t min_value, max_value, min_shifted, max_shifted;

+

+        switch (flags & BYTES_STORED) {

+            case 0:

+                min_shifted = (min_value = -128 >> shift) << shift;

+                max_shifted = (max_value = 127 >> shift) << shift;

+                break;

+

+            case 1:

+                min_shifted = (min_value = -32768 >> shift) << shift;

+                max_shifted = (max_value = 32767 >> shift) << shift;

+                break;

+

+            case 2:

+                min_shifted = (min_value = -8388608 >> shift) << shift;

+                max_shifted = (max_value = 8388607 >> shift) << shift;

+                break;

+

+            case 3:

+            default:

+                min_shifted = (min_value = (int32_t) 0x80000000 >> shift) << shift;

+                max_shifted = (max_value = (int32_t) 0x7FFFFFFF >> shift) << shift;

+                break;

+        }

+

+        if (!(flags & MONO_FLAG))

+            sample_count *= 2;

+

+        while (sample_count--) {

+            if (*buffer < min_value)

+                *buffer++ = min_shifted;

+            else if (*buffer > max_value)

+                *buffer++ = max_shifted;

+            else

+                *buffer++ <<= shift;

+        }

+    }

+    else if (shift) {

+        if (!(flags & MONO_FLAG))

+            sample_count *= 2;

+

+        while (sample_count--)

+            *buffer++ <<= shift;

+    }

+}

+

+// This function checks the crc value(s) for an unpacked block, returning the

+// number of actual crc errors detected for the block. The block must be

+// completely unpacked before this test is valid. For losslessly unpacked

+// blocks of float or extended integer data the extended crc is also checked.

+// Note that WavPack's crc is not a CCITT approved polynomial algorithm, but

+// is a much simpler method that is virtually as robust for real world data.

+

+int check_crc_error (WavpackContext *wpc)

+{

+    WavpackStream *wps = &wpc->stream;

+    int result = 0;

+

+    if (wps->crc != wps->wphdr.crc)

+        ++result;

+

+    return result;

+}

diff --git a/src/engine/external/wavpack/wavpack.h b/src/engine/external/wavpack/wavpack.h
new file mode 100644
index 00000000..7c260586
--- /dev/null
+++ b/src/engine/external/wavpack/wavpack.h
@@ -0,0 +1,384 @@
+////////////////////////////////////////////////////////////////////////////

+//                           **** WAVPACK ****                            //

+//                  Hybrid Lossless Wavefile Compressor                   //

+//              Copyright (c) 1998 - 2004 Conifer Software.               //

+//                          All Rights Reserved.                          //

+//      Distributed under the BSD Software License (see license.txt)      //

+////////////////////////////////////////////////////////////////////////////

+

+// wavpack.h

+

+#include <sys/types.h>

+

+// This header file contains all the definitions required by WavPack.

+

+#ifdef __BORLANDC__

+typedef unsigned long uint32_t;

+typedef long int32_t;

+#elif defined(_WIN32) && !defined(__MINGW32__)

+#include <stdlib.h>

+typedef unsigned __int64 uint64_t;

+typedef unsigned __int32 uint32_t;

+typedef __int64 int64_t;

+typedef __int32 int32_t;

+#else

+#include <inttypes.h>

+#endif

+

+typedef unsigned char   uchar;

+

+#if !defined(__GNUC__) || defined(WIN32)

+typedef unsigned short  ushort;

+typedef unsigned int    uint;

+#endif

+

+#include <stdio.h>

+

+#define FALSE 0

+#define TRUE 1

+

+////////////////////////////// WavPack Header /////////////////////////////////

+

+// Note that this is the ONLY structure that is written to (or read from)

+// WavPack 4.0 files, and is the preamble to every block in both the .wv

+// and .wvc files.

+

+typedef struct {

+    char ckID [4];

+    uint32_t ckSize;

+    short version;

+    uchar track_no, index_no;

+    uint32_t total_samples, block_index, block_samples, flags, crc;

+} WavpackHeader;

+

+#define WavpackHeaderFormat "4LS2LLLLL"

+

+// or-values for "flags"

+

+#define BYTES_STORED    3       // 1-4 bytes/sample

+#define MONO_FLAG       4       // not stereo

+#define HYBRID_FLAG     8       // hybrid mode

+#define JOINT_STEREO    0x10    // joint stereo

+#define CROSS_DECORR    0x20    // no-delay cross decorrelation

+#define HYBRID_SHAPE    0x40    // noise shape (hybrid mode only)

+#define FLOAT_DATA      0x80    // ieee 32-bit floating point data

+

+#define INT32_DATA      0x100   // special extended int handling

+#define HYBRID_BITRATE  0x200   // bitrate noise (hybrid mode only)

+#define HYBRID_BALANCE  0x400   // balance noise (hybrid stereo mode only)

+

+#define INITIAL_BLOCK   0x800   // initial block of multichannel segment

+#define FINAL_BLOCK     0x1000  // final block of multichannel segment

+

+#define SHIFT_LSB       13

+#define SHIFT_MASK      (0x1fL << SHIFT_LSB)

+

+#define MAG_LSB         18

+#define MAG_MASK        (0x1fL << MAG_LSB)

+

+#define SRATE_LSB       23

+#define SRATE_MASK      (0xfL << SRATE_LSB)

+

+#define FALSE_STEREO    0x40000000      // block is stereo, but data is mono

+

+#define IGNORED_FLAGS   0x18000000      // reserved, but ignore if encountered

+#define NEW_SHAPING     0x20000000      // use IIR filter for negative shaping

+#define UNKNOWN_FLAGS   0x80000000      // also reserved, but refuse decode if

+                                        //  encountered

+

+#define MONO_DATA (MONO_FLAG | FALSE_STEREO)

+

+#define MIN_STREAM_VERS     0x402       // lowest stream version we'll decode

+#define MAX_STREAM_VERS     0x410       // highest stream version we'll decode

+

+//////////////////////////// WavPack Metadata /////////////////////////////////

+

+// This is an internal representation of metadata.

+

+typedef struct {

+    int32_t byte_length;

+    void *data;

+    uchar id;

+} WavpackMetadata;

+

+#define ID_OPTIONAL_DATA        0x20

+#define ID_ODD_SIZE             0x40

+#define ID_LARGE                0x80

+

+#define ID_DUMMY                0x0

+#define ID_ENCODER_INFO         0x1

+#define ID_DECORR_TERMS         0x2

+#define ID_DECORR_WEIGHTS       0x3

+#define ID_DECORR_SAMPLES       0x4

+#define ID_ENTROPY_VARS         0x5

+#define ID_HYBRID_PROFILE       0x6

+#define ID_SHAPING_WEIGHTS      0x7

+#define ID_FLOAT_INFO           0x8

+#define ID_INT32_INFO           0x9

+#define ID_WV_BITSTREAM         0xa

+#define ID_WVC_BITSTREAM        0xb

+#define ID_WVX_BITSTREAM        0xc

+#define ID_CHANNEL_INFO         0xd

+

+#define ID_RIFF_HEADER          (ID_OPTIONAL_DATA | 0x1)

+#define ID_RIFF_TRAILER         (ID_OPTIONAL_DATA | 0x2)

+#define ID_REPLAY_GAIN          (ID_OPTIONAL_DATA | 0x3)

+#define ID_CUESHEET             (ID_OPTIONAL_DATA | 0x4)

+#define ID_CONFIG_BLOCK         (ID_OPTIONAL_DATA | 0x5)

+#define ID_MD5_CHECKSUM         (ID_OPTIONAL_DATA | 0x6)

+

+///////////////////////// WavPack Configuration ///////////////////////////////

+

+// This internal structure is used during encode to provide configuration to

+// the encoding engine and during decoding to provide fle information back to

+// the higher level functions. Not all fields are used in both modes.

+

+typedef struct {

+    int bits_per_sample, bytes_per_sample;

+    int num_channels, float_norm_exp;

+    uint32_t flags, sample_rate, channel_mask;

+} WavpackConfig;

+

+#define CONFIG_BYTES_STORED     3       // 1-4 bytes/sample

+#define CONFIG_MONO_FLAG        4       // not stereo

+#define CONFIG_HYBRID_FLAG      8       // hybrid mode

+#define CONFIG_JOINT_STEREO     0x10    // joint stereo

+#define CONFIG_CROSS_DECORR     0x20    // no-delay cross decorrelation

+#define CONFIG_HYBRID_SHAPE     0x40    // noise shape (hybrid mode only)

+#define CONFIG_FLOAT_DATA       0x80    // ieee 32-bit floating point data

+

+#define CONFIG_FAST_FLAG        0x200   // fast mode

+#define CONFIG_HIGH_FLAG        0x800   // high quality mode

+#define CONFIG_VERY_HIGH_FLAG   0x1000  // very high

+#define CONFIG_BITRATE_KBPS     0x2000  // bitrate is kbps, not bits / sample

+#define CONFIG_AUTO_SHAPING     0x4000  // automatic noise shaping

+#define CONFIG_SHAPE_OVERRIDE   0x8000  // shaping mode specified

+#define CONFIG_JOINT_OVERRIDE   0x10000 // joint-stereo mode specified

+#define CONFIG_CREATE_EXE       0x40000 // create executable

+#define CONFIG_CREATE_WVC       0x80000 // create correction file

+#define CONFIG_OPTIMIZE_WVC     0x100000 // maximize bybrid compression

+#define CONFIG_CALC_NOISE       0x800000 // calc noise in hybrid mode

+#define CONFIG_LOSSY_MODE       0x1000000 // obsolete (for information)

+#define CONFIG_EXTRA_MODE       0x2000000 // extra processing mode

+#define CONFIG_SKIP_WVX         0x4000000 // no wvx stream w/ floats & big ints

+#define CONFIG_MD5_CHECKSUM     0x8000000 // compute & store MD5 signature

+#define CONFIG_OPTIMIZE_MONO    0x80000000 // optimize for mono streams posing as stereo

+

+//////////////////////////////// WavPack Stream ///////////////////////////////

+

+// This internal structure contains everything required to handle a WavPack

+// "stream", which is defined as a stereo or mono stream of audio samples. For

+// multichannel audio several of these would be required. Each stream contains

+// pointers to hold a complete allocated block of WavPack data, although it's

+// possible to decode WavPack blocks without buffering an entire block.

+

+typedef int32_t (*read_stream)(void *, int32_t);

+

+typedef struct bs {

+    uchar *buf, *end, *ptr;

+    void (*wrap)(struct bs *bs);

+    uint32_t file_bytes, sr;

+    int error, bc;

+    read_stream file;

+} Bitstream;

+

+#define MAX_NTERMS 16

+#define MAX_TERM 8

+

+struct decorr_pass {

+    short term, delta, weight_A, weight_B;

+    int32_t samples_A [MAX_TERM], samples_B [MAX_TERM];

+};

+

+struct entropy_data {

+    uint32_t median [3], slow_level, error_limit;

+};

+

+struct words_data {

+    uint32_t bitrate_delta [2], bitrate_acc [2];

+    uint32_t pend_data, holding_one, zeros_acc;

+    int holding_zero, pend_count;

+    struct entropy_data c [2];

+};

+

+typedef struct {

+    WavpackHeader wphdr;

+    Bitstream wvbits;

+

+    struct words_data w;

+

+    int num_terms, mute_error;

+    uint32_t sample_index, crc;

+

+    uchar int32_sent_bits, int32_zeros, int32_ones, int32_dups;

+    uchar float_flags, float_shift, float_max_exp, float_norm_exp;

+ 

+    struct decorr_pass decorr_passes [MAX_NTERMS];

+

+} WavpackStream;

+

+// flags for float_flags:

+

+#define FLOAT_SHIFT_ONES 1      // bits left-shifted into float = '1'

+#define FLOAT_SHIFT_SAME 2      // bits left-shifted into float are the same

+#define FLOAT_SHIFT_SENT 4      // bits shifted into float are sent literally

+#define FLOAT_ZEROS_SENT 8      // "zeros" are not all real zeros

+#define FLOAT_NEG_ZEROS  0x10   // contains negative zeros

+#define FLOAT_EXCEPTIONS 0x20   // contains exceptions (inf, nan, etc.)

+

+/////////////////////////////// WavPack Context ///////////////////////////////

+

+// This internal structure holds everything required to encode or decode WavPack

+// files. It is recommended that direct access to this structure be minimized

+// and the provided utilities used instead.

+

+typedef struct {

+    WavpackConfig config;

+    WavpackStream stream;

+

+    uchar read_buffer [1024];

+    char error_message [80];

+

+    read_stream infile;

+    uint32_t total_samples, crc_errors, first_flags;

+    int open_flags, norm_offset, reduced_channels, lossy_blocks;

+

+} WavpackContext;

+

+//////////////////////// function prototypes and macros //////////////////////

+

+#define CLEAR(destin) memset (&destin, 0, sizeof (destin));

+

+// bits.c

+

+void bs_open_read (Bitstream *bs, uchar *buffer_start, uchar *buffer_end, read_stream file, uint32_t file_bytes);

+

+#define bs_is_open(bs) ((bs)->ptr != NULL)

+

+#define getbit(bs) ( \

+    (((bs)->bc) ? \

+        ((bs)->bc--, (bs)->sr & 1) : \

+            (((++((bs)->ptr) != (bs)->end) ? (void) 0 : (bs)->wrap (bs)), (bs)->bc = 7, ((bs)->sr = *((bs)->ptr)) & 1) \

+    ) ? \

+        ((bs)->sr >>= 1, 1) : \

+        ((bs)->sr >>= 1, 0) \

+)

+

+#define getbits(value, nbits, bs) { \

+    while ((nbits) > (bs)->bc) { \

+        if (++((bs)->ptr) == (bs)->end) (bs)->wrap (bs); \

+        (bs)->sr |= (int32_t)*((bs)->ptr) << (bs)->bc; \

+        (bs)->bc += 8; \

+    } \

+    *(value) = (bs)->sr; \

+    if ((bs)->bc > 32) { \

+        (bs)->bc -= (nbits); \

+        (bs)->sr = *((bs)->ptr) >> (8 - (bs)->bc); \

+    } \

+    else { \

+        (bs)->bc -= (nbits); \

+        (bs)->sr >>= (nbits); \

+    } \

+}

+

+void little_endian_to_native (void *data, char *format);

+void native_to_little_endian (void *data, char *format);

+

+// These macros implement the weight application and update operations

+// that are at the heart of the decorrelation loops. Note that when there

+// are several alternative versions of the same macro (marked with PERFCOND)

+// then the versions are functionally equivalent with respect to WavPack

+// decoding and the user should choose the one that provides the best

+// performance. This may be easier to check when NOT using the assembly

+// language optimizations.

+

+#if 1   // PERFCOND

+#define apply_weight_i(weight, sample) ((weight * sample + 512) >> 10)

+#else

+#define apply_weight_i(weight, sample) ((((weight * sample) >> 8) + 2) >> 2)

+#endif

+

+#define apply_weight_f(weight, sample) (((((sample & 0xffffL) * weight) >> 9) + \

+    (((sample & ~0xffffL) >> 9) * weight) + 1) >> 1)

+

+#if 1   // PERFCOND

+#define apply_weight(weight, sample) (sample != (short) sample ? \

+    apply_weight_f (weight, sample) : apply_weight_i (weight, sample))

+#else

+#define apply_weight(weight, sample) ((int32_t)((weight * (int64_t) sample + 512) >> 10))

+#endif

+

+#if 0   // PERFCOND

+#define update_weight(weight, delta, source, result) \

+    if (source && result) { int32_t s = (int32_t) (source ^ result) >> 31; weight = (delta ^ s) + (weight - s); }

+#elif 1

+#define update_weight(weight, delta, source, result) \

+    if (source && result) weight += (((source ^ result) >> 30) | 1) * delta

+#else

+#define update_weight(weight, delta, source, result) \

+    if (source && result) (source ^ result) < 0 ? (weight -= delta) : (weight += delta)

+#endif

+

+#define update_weight_clip(weight, delta, source, result) \

+    if (source && result && ((source ^ result) < 0 ? (weight -= delta) < -1024 : (weight += delta) > 1024)) \

+        weight = weight < 0 ? -1024 : 1024

+

+// unpack.c

+

+int unpack_init (WavpackContext *wpc);

+int init_wv_bitstream (WavpackContext *wpc, WavpackMetadata *wpmd);

+int read_decorr_terms (WavpackStream *wps, WavpackMetadata *wpmd);

+int read_decorr_weights (WavpackStream *wps, WavpackMetadata *wpmd);

+int read_decorr_samples (WavpackStream *wps, WavpackMetadata *wpmd);

+int read_float_info (WavpackStream *wps, WavpackMetadata *wpmd);

+int read_int32_info (WavpackStream *wps, WavpackMetadata *wpmd);

+int read_channel_info (WavpackContext *wpc, WavpackMetadata *wpmd);

+int read_config_info (WavpackContext *wpc, WavpackMetadata *wpmd);

+int32_t unpack_samples (WavpackContext *wpc, int32_t *buffer, uint32_t sample_count);

+int check_crc_error (WavpackContext *wpc);

+

+// metadata.c stuff

+

+int read_metadata_buff (WavpackContext *wpc, WavpackMetadata *wpmd);

+int process_metadata (WavpackContext *wpc, WavpackMetadata *wpmd);

+

+// words.c stuff

+

+int read_entropy_vars (WavpackStream *wps, WavpackMetadata *wpmd);

+int read_hybrid_profile (WavpackStream *wps, WavpackMetadata *wpmd);

+int32_t get_words (int32_t *buffer, int nsamples, uint32_t flags,

+                struct words_data *w, Bitstream *bs);

+int32_t exp2s (int log);

+int restore_weight (signed char weight);

+

+#define WORD_EOF (1L << 31)

+

+// float.c

+

+int read_float_info (WavpackStream *wps, WavpackMetadata *wpmd);

+void float_values (WavpackStream *wps, int32_t *values, int32_t num_values);

+

+// wputils.c

+

+WavpackContext *WavpackOpenFileInput (read_stream infile, char *error);

+

+int WavpackGetMode (WavpackContext *wpc);

+

+#define MODE_WVC        0x1

+#define MODE_LOSSLESS   0x2

+#define MODE_HYBRID     0x4

+#define MODE_FLOAT      0x8

+#define MODE_VALID_TAG  0x10

+#define MODE_HIGH       0x20

+#define MODE_FAST       0x40

+

+uint32_t WavpackUnpackSamples (WavpackContext *wpc, int32_t *buffer, uint32_t samples);

+uint32_t WavpackGetNumSamples (WavpackContext *wpc);

+uint32_t WavpackGetSampleIndex (WavpackContext *wpc);

+int WavpackGetNumErrors (WavpackContext *wpc);

+int WavpackLossyBlocks (WavpackContext *wpc);

+uint32_t WavpackGetSampleRate (WavpackContext *wpc);

+int WavpackGetBitsPerSample (WavpackContext *wpc);

+int WavpackGetBytesPerSample (WavpackContext *wpc);

+int WavpackGetNumChannels (WavpackContext *wpc);

+int WavpackGetReducedChannels (WavpackContext *wpc);

diff --git a/src/engine/external/wavpack/words.c b/src/engine/external/wavpack/words.c
new file mode 100644
index 00000000..0e5a3db7
--- /dev/null
+++ b/src/engine/external/wavpack/words.c
@@ -0,0 +1,560 @@
+////////////////////////////////////////////////////////////////////////////

+//                           **** WAVPACK ****                            //

+//                  Hybrid Lossless Wavefile Compressor                   //

+//              Copyright (c) 1998 - 2006 Conifer Software.               //

+//                          All Rights Reserved.                          //

+//      Distributed under the BSD Software License (see license.txt)      //

+////////////////////////////////////////////////////////////////////////////

+

+// words.c

+

+// This module provides entropy word encoding and decoding functions using

+// a variation on the Rice method.  This was introduced in version 3.93

+// because it allows splitting the data into a "lossy" stream and a

+// "correction" stream in a very efficient manner and is therefore ideal

+// for the "hybrid" mode.  For 4.0, the efficiency of this method was

+// significantly improved by moving away from the normal Rice restriction of

+// using powers of two for the modulus divisions and now the method can be

+// used for both hybrid and pure lossless encoding.

+

+// Samples are divided by median probabilities at 5/7 (71.43%), 10/49 (20.41%),

+// and 20/343 (5.83%). Each zone has 3.5 times fewer samples than the

+// previous. Using standard Rice coding on this data would result in 1.4

+// bits per sample average (not counting sign bit). However, there is a

+// very simple encoding that is over 99% efficient with this data and

+// results in about 1.22 bits per sample.

+

+#include "wavpack.h"

+

+#include <string.h>

+

+//////////////////////////////// local macros /////////////////////////////////

+

+#define LIMIT_ONES 16   // maximum consecutive 1s sent for "div" data

+

+// these control the time constant "slow_level" which is used for hybrid mode

+// that controls bitrate as a function of residual level (HYBRID_BITRATE).

+#define SLS 8

+#define SLO ((1 << (SLS - 1)))

+

+// these control the time constant of the 3 median level breakpoints

+#define DIV0 128        // 5/7 of samples

+#define DIV1 64         // 10/49 of samples

+#define DIV2 32         // 20/343 of samples

+

+// this macro retrieves the specified median breakpoint (without frac; min = 1)

+#define GET_MED(med) (((c->median [med]) >> 4) + 1)

+

+// These macros update the specified median breakpoints. Note that the median

+// is incremented when the sample is higher than the median, else decremented.

+// They are designed so that the median will never drop below 1 and the value

+// is essentially stationary if there are 2 increments for every 5 decrements.

+

+#define INC_MED0() (c->median [0] += ((c->median [0] + DIV0) / DIV0) * 5)

+#define DEC_MED0() (c->median [0] -= ((c->median [0] + (DIV0-2)) / DIV0) * 2)

+#define INC_MED1() (c->median [1] += ((c->median [1] + DIV1) / DIV1) * 5)

+#define DEC_MED1() (c->median [1] -= ((c->median [1] + (DIV1-2)) / DIV1) * 2)

+#define INC_MED2() (c->median [2] += ((c->median [2] + DIV2) / DIV2) * 5)

+#define DEC_MED2() (c->median [2] -= ((c->median [2] + (DIV2-2)) / DIV2) * 2)

+

+#define count_bits(av) ( \

+ (av) < (1 << 8) ? nbits_table [av] : \

+  ( \

+   (av) < (1L << 16) ? nbits_table [(av) >> 8] + 8 : \

+   ((av) < (1L << 24) ? nbits_table [(av) >> 16] + 16 : nbits_table [(av) >> 24] + 24) \

+  ) \

+)

+

+///////////////////////////// local table storage ////////////////////////////

+

+const char nbits_table [] = {

+    0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,     // 0 - 15

+    5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,     // 16 - 31

+    6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,     // 32 - 47

+    6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,     // 48 - 63

+    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,     // 64 - 79

+    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,     // 80 - 95

+    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,     // 96 - 111

+    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,     // 112 - 127

+    8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,     // 128 - 143

+    8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,     // 144 - 159

+    8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,     // 160 - 175

+    8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,     // 176 - 191

+    8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,     // 192 - 207

+    8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,     // 208 - 223

+    8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,     // 224 - 239

+    8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8      // 240 - 255

+};

+

+static const uchar log2_table [] = {

+    0x00, 0x01, 0x03, 0x04, 0x06, 0x07, 0x09, 0x0a, 0x0b, 0x0d, 0x0e, 0x10, 0x11, 0x12, 0x14, 0x15,

+    0x16, 0x18, 0x19, 0x1a, 0x1c, 0x1d, 0x1e, 0x20, 0x21, 0x22, 0x24, 0x25, 0x26, 0x28, 0x29, 0x2a,

+    0x2c, 0x2d, 0x2e, 0x2f, 0x31, 0x32, 0x33, 0x34, 0x36, 0x37, 0x38, 0x39, 0x3b, 0x3c, 0x3d, 0x3e,

+    0x3f, 0x41, 0x42, 0x43, 0x44, 0x45, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4d, 0x4e, 0x4f, 0x50, 0x51,

+    0x52, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5c, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63,

+    0x64, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x74, 0x75,

+    0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85,

+    0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95,

+    0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4,

+    0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb2,

+    0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc0,

+    0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcb, 0xcc, 0xcd, 0xce,

+    0xcf, 0xd0, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd8, 0xd9, 0xda, 0xdb,

+    0xdc, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe4, 0xe5, 0xe6, 0xe7, 0xe7,

+    0xe8, 0xe9, 0xea, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xee, 0xef, 0xf0, 0xf1, 0xf1, 0xf2, 0xf3, 0xf4,

+    0xf4, 0xf5, 0xf6, 0xf7, 0xf7, 0xf8, 0xf9, 0xf9, 0xfa, 0xfb, 0xfc, 0xfc, 0xfd, 0xfe, 0xff, 0xff

+};

+

+static const uchar exp2_table [] = {

+    0x00, 0x01, 0x01, 0x02, 0x03, 0x03, 0x04, 0x05, 0x06, 0x06, 0x07, 0x08, 0x08, 0x09, 0x0a, 0x0b,

+    0x0b, 0x0c, 0x0d, 0x0e, 0x0e, 0x0f, 0x10, 0x10, 0x11, 0x12, 0x13, 0x13, 0x14, 0x15, 0x16, 0x16,

+    0x17, 0x18, 0x19, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1d, 0x1e, 0x1f, 0x20, 0x20, 0x21, 0x22, 0x23,

+    0x24, 0x24, 0x25, 0x26, 0x27, 0x28, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,

+    0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3a, 0x3b, 0x3c, 0x3d,

+    0x3e, 0x3f, 0x40, 0x41, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x48, 0x49, 0x4a, 0x4b,

+    0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a,

+    0x5b, 0x5c, 0x5d, 0x5e, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,

+    0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,

+    0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x87, 0x88, 0x89, 0x8a,

+    0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b,

+    0x9c, 0x9d, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad,

+    0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0,

+    0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc8, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf, 0xd0, 0xd2, 0xd3, 0xd4,

+    0xd6, 0xd7, 0xd8, 0xd9, 0xdb, 0xdc, 0xdd, 0xde, 0xe0, 0xe1, 0xe2, 0xe4, 0xe5, 0xe6, 0xe8, 0xe9,

+    0xea, 0xec, 0xed, 0xee, 0xf0, 0xf1, 0xf2, 0xf4, 0xf5, 0xf6, 0xf8, 0xf9, 0xfa, 0xfc, 0xfd, 0xff

+};

+

+static const char ones_count_table [] = {

+    0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,

+    0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,

+    0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,

+    0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,7,

+    0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,

+    0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,

+    0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,

+    0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,8

+};

+

+///////////////////////////// executable code ////////////////////////////////

+

+void init_words (WavpackStream *wps)

+{

+    CLEAR (wps->w);

+}

+

+static int mylog2 (uint32_t avalue);

+

+// Read the median log2 values from the specifed metadata structure, convert

+// them back to 32-bit unsigned values and store them. If length is not

+// exactly correct then we flag and return an error.

+

+int read_entropy_vars (WavpackStream *wps, WavpackMetadata *wpmd)

+{

+    uchar *byteptr = wpmd->data;

+

+    if (wpmd->byte_length != ((wps->wphdr.flags & MONO_DATA) ? 6 : 12))

+        return FALSE;

+

+    wps->w.c [0].median [0] = exp2s (byteptr [0] + (byteptr [1] << 8));

+    wps->w.c [0].median [1] = exp2s (byteptr [2] + (byteptr [3] << 8));

+    wps->w.c [0].median [2] = exp2s (byteptr [4] + (byteptr [5] << 8));

+

+    if (!(wps->wphdr.flags & MONO_DATA)) {

+        wps->w.c [1].median [0] = exp2s (byteptr [6] + (byteptr [7] << 8));

+        wps->w.c [1].median [1] = exp2s (byteptr [8] + (byteptr [9] << 8));

+        wps->w.c [1].median [2] = exp2s (byteptr [10] + (byteptr [11] << 8));

+    }

+

+    return TRUE;

+}

+

+// Read the hybrid related values from the specifed metadata structure, convert

+// them back to their internal formats and store them. The extended profile

+// stuff is not implemented yet, so return an error if we get more data than

+// we know what to do with.

+

+int read_hybrid_profile (WavpackStream *wps, WavpackMetadata *wpmd)

+{

+    uchar *byteptr = wpmd->data;

+    uchar *endptr = byteptr + wpmd->byte_length;

+

+    if (wps->wphdr.flags & HYBRID_BITRATE) {

+        wps->w.c [0].slow_level = exp2s (byteptr [0] + (byteptr [1] << 8));

+        byteptr += 2;

+

+        if (!(wps->wphdr.flags & MONO_DATA)) {

+            wps->w.c [1].slow_level = exp2s (byteptr [0] + (byteptr [1] << 8));

+            byteptr += 2;

+        }

+    }

+

+    wps->w.bitrate_acc [0] = (int32_t)(byteptr [0] + (byteptr [1] << 8)) << 16;

+    byteptr += 2;

+

+    if (!(wps->wphdr.flags & MONO_DATA)) {

+        wps->w.bitrate_acc [1] = (int32_t)(byteptr [0] + (byteptr [1] << 8)) << 16;

+        byteptr += 2;

+    }

+

+    if (byteptr < endptr) {

+        wps->w.bitrate_delta [0] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8)));

+        byteptr += 2;

+

+        if (!(wps->wphdr.flags & MONO_DATA)) {

+            wps->w.bitrate_delta [1] = exp2s ((short)(byteptr [0] + (byteptr [1] << 8)));

+            byteptr += 2;

+        }

+

+        if (byteptr < endptr)

+            return FALSE;

+    }

+    else

+        wps->w.bitrate_delta [0] = wps->w.bitrate_delta [1] = 0;

+

+    return TRUE;

+}

+

+// This function is called during both encoding and decoding of hybrid data to

+// update the "error_limit" variable which determines the maximum sample error

+// allowed in the main bitstream. In the HYBRID_BITRATE mode (which is the only

+// currently implemented) this is calculated from the slow_level values and the

+// bitrate accumulators. Note that the bitrate accumulators can be changing.

+

+void update_error_limit (struct words_data *w, uint32_t flags)

+{

+    int bitrate_0 = (w->bitrate_acc [0] += w->bitrate_delta [0]) >> 16;

+

+    if (flags & MONO_DATA) {

+        if (flags & HYBRID_BITRATE) {

+            int slow_log_0 = (w->c [0].slow_level + SLO) >> SLS;

+

+            if (slow_log_0 - bitrate_0 > -0x100)

+                w->c [0].error_limit = exp2s (slow_log_0 - bitrate_0 + 0x100);

+            else

+                w->c [0].error_limit = 0;

+        }

+        else

+            w->c [0].error_limit = exp2s (bitrate_0);

+    }

+    else {

+        int bitrate_1 = (w->bitrate_acc [1] += w->bitrate_delta [1]) >> 16;

+

+        if (flags & HYBRID_BITRATE) {

+            int slow_log_0 = (w->c [0].slow_level + SLO) >> SLS;

+            int slow_log_1 = (w->c [1].slow_level + SLO) >> SLS;

+

+            if (flags & HYBRID_BALANCE) {

+                int balance = (slow_log_1 - slow_log_0 + bitrate_1 + 1) >> 1;

+

+                if (balance > bitrate_0) {

+                    bitrate_1 = bitrate_0 * 2;

+                    bitrate_0 = 0;

+                }

+                else if (-balance > bitrate_0) {

+                    bitrate_0 = bitrate_0 * 2;

+                    bitrate_1 = 0;

+                }

+                else {

+                    bitrate_1 = bitrate_0 + balance;

+                    bitrate_0 = bitrate_0 - balance;

+                }

+            }

+

+            if (slow_log_0 - bitrate_0 > -0x100)

+                w->c [0].error_limit = exp2s (slow_log_0 - bitrate_0 + 0x100);

+            else

+                w->c [0].error_limit = 0;

+

+            if (slow_log_1 - bitrate_1 > -0x100)

+                w->c [1].error_limit = exp2s (slow_log_1 - bitrate_1 + 0x100);

+            else

+                w->c [1].error_limit = 0;

+        }

+        else {

+            w->c [0].error_limit = exp2s (bitrate_0);

+            w->c [1].error_limit = exp2s (bitrate_1);

+        }

+    }

+}

+

+static uint32_t read_code (Bitstream *bs, uint32_t maxcode);

+

+// Read the next word from the bitstream "wvbits" and return the value. This

+// function can be used for hybrid or lossless streams, but since an

+// optimized version is available for lossless this function would normally

+// be used for hybrid only. If a hybrid lossless stream is being read then

+// the "correction" offset is written at the specified pointer. A return value

+// of WORD_EOF indicates that the end of the bitstream was reached (all 1s) or

+// some other error occurred.

+

+int32_t get_words (int32_t *buffer, int nsamples, uint32_t flags,

+                struct words_data *w, Bitstream *bs)

+{

+    register struct entropy_data *c = w->c;

+    int csamples;

+

+    if (!(flags & MONO_DATA))

+        nsamples *= 2;

+

+    for (csamples = 0; csamples < nsamples; ++csamples) {

+        uint32_t ones_count, low, mid, high;

+

+        if (!(flags & MONO_DATA))

+            c = w->c + (csamples & 1);

+

+        if (!(w->c [0].median [0] & ~1) && !w->holding_zero && !w->holding_one && !(w->c [1].median [0] & ~1)) {

+            uint32_t mask;

+            int cbits;

+

+            if (w->zeros_acc) {

+                if (--w->zeros_acc) {

+                    c->slow_level -= (c->slow_level + SLO) >> SLS;

+                    *buffer++ = 0;

+                    continue;

+                }

+            }

+            else {

+                for (cbits = 0; cbits < 33 && getbit (bs); ++cbits);

+

+                if (cbits == 33)

+                    break;

+

+                if (cbits < 2)

+                    w->zeros_acc = cbits;

+                else {

+                    for (mask = 1, w->zeros_acc = 0; --cbits; mask <<= 1)

+                        if (getbit (bs))

+                            w->zeros_acc |= mask;

+

+                    w->zeros_acc |= mask;

+                }

+

+                if (w->zeros_acc) {

+                    c->slow_level -= (c->slow_level + SLO) >> SLS;

+                    CLEAR (w->c [0].median);

+                    CLEAR (w->c [1].median);

+                    *buffer++ = 0;

+                    continue;

+                }

+            }

+        }

+

+        if (w->holding_zero)

+            ones_count = w->holding_zero = 0;

+        else {

+            int next8;

+

+            if (bs->bc < 8) {

+                if (++(bs->ptr) == bs->end)

+                    bs->wrap (bs);

+

+                next8 = (bs->sr |= *(bs->ptr) << bs->bc) & 0xff;

+                bs->bc += 8;

+            }

+            else

+                next8 = bs->sr & 0xff;

+

+            if (next8 == 0xff) {

+                bs->bc -= 8;

+                bs->sr >>= 8;

+

+                for (ones_count = 8; ones_count < (LIMIT_ONES + 1) && getbit (bs); ++ones_count);

+

+                if (ones_count == (LIMIT_ONES + 1))

+                    break;

+

+                if (ones_count == LIMIT_ONES) {

+                    uint32_t mask;

+                    int cbits;

+

+                    for (cbits = 0; cbits < 33 && getbit (bs); ++cbits);

+

+                    if (cbits == 33)

+                        break;

+

+                    if (cbits < 2)

+                        ones_count = cbits;

+                    else {

+                        for (mask = 1, ones_count = 0; --cbits; mask <<= 1)

+                            if (getbit (bs))

+                                ones_count |= mask;

+

+                        ones_count |= mask;

+                    }

+

+                    ones_count += LIMIT_ONES;

+                }

+            }

+            else {

+                bs->bc -= (ones_count = ones_count_table [next8]) + 1;

+                bs->sr >>= ones_count + 1;

+            }

+

+            if (w->holding_one) {

+                w->holding_one = ones_count & 1;

+                ones_count = (ones_count >> 1) + 1;

+            }

+            else {

+                w->holding_one = ones_count & 1;

+                ones_count >>= 1;

+            }

+

+            w->holding_zero = ~w->holding_one & 1;

+        }

+

+        if ((flags & HYBRID_FLAG) && ((flags & MONO_DATA) || !(csamples & 1)))

+            update_error_limit (w, flags);

+

+        if (ones_count == 0) {

+            low = 0;

+            high = GET_MED (0) - 1;

+            DEC_MED0 ();

+        }

+        else {

+            low = GET_MED (0);

+            INC_MED0 ();

+

+            if (ones_count == 1) {

+                high = low + GET_MED (1) - 1;

+                DEC_MED1 ();

+            }

+            else {

+                low += GET_MED (1);

+                INC_MED1 ();

+

+                if (ones_count == 2) {

+                    high = low + GET_MED (2) - 1;

+                    DEC_MED2 ();

+                }

+                else {

+                    low += (ones_count - 2) * GET_MED (2);

+                    high = low + GET_MED (2) - 1;

+                    INC_MED2 ();

+                }

+            }

+        }

+

+        mid = (high + low + 1) >> 1;

+

+        if (!c->error_limit)

+            mid = read_code (bs, high - low) + low;

+        else while (high - low > c->error_limit) {

+            if (getbit (bs))

+                mid = (high + (low = mid) + 1) >> 1;

+            else

+                mid = ((high = mid - 1) + low + 1) >> 1;

+        }

+

+        *buffer++ = getbit (bs) ? ~mid : mid;

+

+        if (flags & HYBRID_BITRATE)

+            c->slow_level = c->slow_level - ((c->slow_level + SLO) >> SLS) + mylog2 (mid);

+    }

+

+    return (flags & MONO_DATA) ? csamples : (csamples / 2);

+}

+

+// Read a single unsigned value from the specified bitstream with a value

+// from 0 to maxcode. If there are exactly a power of two number of possible

+// codes then this will read a fixed number of bits; otherwise it reads the

+// minimum number of bits and then determines whether another bit is needed

+// to define the code.

+

+static uint32_t read_code (Bitstream *bs, uint32_t maxcode)

+{

+    int bitcount = count_bits (maxcode);

+    uint32_t extras = (1L << bitcount) - maxcode - 1, code;

+

+    if (!bitcount)

+        return 0;

+

+    getbits (&code, bitcount - 1, bs);

+    code &= (1L << (bitcount - 1)) - 1;

+

+    if (code >= extras) {

+        code = (code << 1) - extras;

+

+        if (getbit (bs))

+            ++code;

+    }

+

+    return code;

+}

+

+// The concept of a base 2 logarithm is used in many parts of WavPack. It is

+// a way of sufficiently accurately representing 32-bit signed and unsigned

+// values storing only 16 bits (actually fewer). It is also used in the hybrid

+// mode for quickly comparing the relative magnitude of large values (i.e.

+// division) and providing smooth exponentials using only addition.

+

+// These are not strict logarithms in that they become linear around zero and

+// can therefore represent both zero and negative values. They have 8 bits

+// of precision and in "roundtrip" conversions the total error never exceeds 1

+// part in 225 except for the cases of +/-115 and +/-195 (which error by 1).

+

+

+// This function returns the log2 for the specified 32-bit unsigned value.

+// The maximum value allowed is about 0xff800000 and returns 8447.

+

+static int mylog2 (uint32_t avalue)

+{

+    int dbits;

+

+    if ((avalue += avalue >> 9) < (1 << 8)) {

+        dbits = nbits_table [avalue];

+        return (dbits << 8) + log2_table [(avalue << (9 - dbits)) & 0xff];

+    }

+    else {

+        if (avalue < (1L << 16))

+            dbits = nbits_table [avalue >> 8] + 8;

+        else if (avalue < (1L << 24))

+            dbits = nbits_table [avalue >> 16] + 16;

+        else

+            dbits = nbits_table [avalue >> 24] + 24;

+

+        return (dbits << 8) + log2_table [(avalue >> (dbits - 9)) & 0xff];

+    }

+}

+

+// This function returns the log2 for the specified 32-bit signed value.

+// All input values are valid and the return values are in the range of

+// +/- 8192.

+

+int log2s (int32_t value)

+{

+    return (value < 0) ? -mylog2 (-value) : mylog2 (value);

+}

+

+// This function returns the original integer represented by the supplied

+// logarithm (at least within the provided accuracy). The log is signed,

+// but since a full 32-bit value is returned this can be used for unsigned

+// conversions as well (i.e. the input range is -8192 to +8447).

+

+int32_t exp2s (int log)

+{

+    uint32_t value;

+

+    if (log < 0)

+        return -exp2s (-log);

+

+    value = exp2_table [log & 0xff] | 0x100;

+

+    if ((log >>= 8) <= 9)

+        return value >> (9 - log);

+    else

+        return value << (log - 9);

+}

+

+// These two functions convert internal weights (which are normally +/-1024)

+// to and from an 8-bit signed character version for storage in metadata. The

+// weights are clipped here in the case that they are outside that range.

+

+int restore_weight (signed char weight)

+{

+    int result;

+

+    if ((result = (int) weight << 3) > 0)

+        result += (result + 64) >> 7;

+

+    return result;

+}

diff --git a/src/engine/external/wavpack/wputils.c b/src/engine/external/wavpack/wputils.c
new file mode 100644
index 00000000..0d71af53
--- /dev/null
+++ b/src/engine/external/wavpack/wputils.c
@@ -0,0 +1,351 @@
+////////////////////////////////////////////////////////////////////////////

+//                           **** WAVPACK ****                            //

+//                  Hybrid Lossless Wavefile Compressor                   //

+//              Copyright (c) 1998 - 2006 Conifer Software.               //

+//                          All Rights Reserved.                          //

+//      Distributed under the BSD Software License (see license.txt)      //

+////////////////////////////////////////////////////////////////////////////

+

+// wputils.c

+

+// This module provides a high-level interface for decoding WavPack 4.0 audio

+// streams and files. WavPack data is read with a stream reading callback. No

+// direct seeking is provided for, but it is possible to start decoding

+// anywhere in a WavPack stream. In this case, WavPack will be able to provide

+// the sample-accurate position when it synchs with the data and begins

+// decoding.

+

+#include "wavpack.h"

+

+#include <string.h>

+

+///////////////////////////// local table storage ////////////////////////////

+

+const uint32_t sample_rates [] = { 6000, 8000, 9600, 11025, 12000, 16000, 22050,

+    24000, 32000, 44100, 48000, 64000, 88200, 96000, 192000 };

+

+///////////////////////////// executable code ////////////////////////////////

+

+static uint32_t read_next_header (read_stream infile, WavpackHeader *wphdr);

+        

+// This function reads data from the specified stream in search of a valid

+// WavPack 4.0 audio block. If this fails in 1 megabyte (or an invalid or

+// unsupported WavPack block is encountered) then an appropriate message is

+// copied to "error" and NULL is returned, otherwise a pointer to a

+// WavpackContext structure is returned (which is used to call all other

+// functions in this module). This can be initiated at the beginning of a

+// WavPack file, or anywhere inside a WavPack file. To determine the exact

+// position within the file use WavpackGetSampleIndex(). For demonstration

+// purposes this uses a single static copy of the WavpackContext structure,

+// so obviously it cannot be used for more than one file at a time. Also,

+// this function will not handle "correction" files, plays only the first

+// two channels of multi-channel files, and is limited in resolution in some

+// large integer or floating point files (but always provides at least 24 bits

+// of resolution).

+

+static WavpackContext wpc;

+

+WavpackContext *WavpackOpenFileInput (read_stream infile, char *error)

+{

+    WavpackStream *wps = &wpc.stream;

+    uint32_t bcount;

+

+    CLEAR (wpc);

+    wpc.infile = infile;

+    wpc.total_samples = (uint32_t) -1;

+    wpc.norm_offset = 0;

+    wpc.open_flags = 0;

+

+    // open the source file for reading and store the size

+

+    while (!wps->wphdr.block_samples) {

+

+        bcount = read_next_header (wpc.infile, &wps->wphdr);

+

+        if (bcount == (uint32_t) -1) {

+            strcpy (error, "not compatible with this version of WavPack file!");

+            return NULL;

+        }

+

+        if (wps->wphdr.block_samples && wps->wphdr.total_samples != (uint32_t) -1)

+            wpc.total_samples = wps->wphdr.total_samples;

+

+        if (!unpack_init (&wpc)) {

+            strcpy (error, wpc.error_message [0] ? wpc.error_message :

+                "not compatible with this version of WavPack file!");

+

+            return NULL;

+        }

+    }

+

+    wpc.config.flags &= ~0xff;

+    wpc.config.flags |= wps->wphdr.flags & 0xff;

+    wpc.config.bytes_per_sample = (wps->wphdr.flags & BYTES_STORED) + 1;

+    wpc.config.float_norm_exp = wps->float_norm_exp;

+

+    wpc.config.bits_per_sample = (wpc.config.bytes_per_sample * 8) - 

+        ((wps->wphdr.flags & SHIFT_MASK) >> SHIFT_LSB);

+

+    if (wpc.config.flags & FLOAT_DATA) {

+        wpc.config.bytes_per_sample = 3;

+        wpc.config.bits_per_sample = 24;

+    }

+

+    if (!wpc.config.sample_rate) {

+        if (!wps || !wps->wphdr.block_samples || (wps->wphdr.flags & SRATE_MASK) == SRATE_MASK)

+            wpc.config.sample_rate = 44100;

+        else

+            wpc.config.sample_rate = sample_rates [(wps->wphdr.flags & SRATE_MASK) >> SRATE_LSB];

+    }

+

+    if (!wpc.config.num_channels) {

+        wpc.config.num_channels = (wps->wphdr.flags & MONO_FLAG) ? 1 : 2;

+        wpc.config.channel_mask = 0x5 - wpc.config.num_channels;

+    }

+

+    if (!(wps->wphdr.flags & FINAL_BLOCK))

+        wpc.reduced_channels = (wps->wphdr.flags & MONO_FLAG) ? 1 : 2;

+

+    return &wpc;

+}

+

+// This function obtains general information about an open file and returns

+// a mask with the following bit values:

+

+// MODE_LOSSLESS:  file is lossless (pure lossless only)

+// MODE_HYBRID:  file is hybrid mode (lossy part only)

+// MODE_FLOAT:  audio data is 32-bit ieee floating point (but will provided

+//               in 24-bit integers for convenience)

+// MODE_HIGH:  file was created in "high" mode (information only)

+// MODE_FAST:  file was created in "fast" mode (information only)

+

+int WavpackGetMode (WavpackContext *wpc)

+{

+    int mode = 0;

+

+    if (wpc) {

+        if (wpc->config.flags & CONFIG_HYBRID_FLAG)

+            mode |= MODE_HYBRID;

+        else if (!(wpc->config.flags & CONFIG_LOSSY_MODE))

+            mode |= MODE_LOSSLESS;

+

+        if (wpc->lossy_blocks)

+            mode &= ~MODE_LOSSLESS;

+

+        if (wpc->config.flags & CONFIG_FLOAT_DATA)

+            mode |= MODE_FLOAT;

+

+        if (wpc->config.flags & CONFIG_HIGH_FLAG)

+            mode |= MODE_HIGH;

+

+        if (wpc->config.flags & CONFIG_FAST_FLAG)

+            mode |= MODE_FAST;

+    }

+

+    return mode;

+}

+

+// Unpack the specified number of samples from the current file position.

+// Note that "samples" here refers to "complete" samples, which would be

+// 2 longs for stereo files. The audio data is returned right-justified in

+// 32-bit longs in the endian mode native to the executing processor. So,

+// if the original data was 16-bit, then the values returned would be

+// +/-32k. Floating point data will be returned as 24-bit integers (and may

+// also be clipped). The actual number of samples unpacked is returned,

+// which should be equal to the number requested unless the end of fle is

+// encountered or an error occurs.

+

+uint32_t WavpackUnpackSamples (WavpackContext *wpc, int32_t *buffer, uint32_t samples)

+{

+    WavpackStream *wps = &wpc->stream;

+    uint32_t bcount, samples_unpacked = 0, samples_to_unpack;

+    int num_channels = wpc->config.num_channels;

+

+    while (samples) {

+        if (!wps->wphdr.block_samples || !(wps->wphdr.flags & INITIAL_BLOCK) ||

+            wps->sample_index >= wps->wphdr.block_index + wps->wphdr.block_samples) {

+                bcount = read_next_header (wpc->infile, &wps->wphdr);

+

+                if (bcount == (uint32_t) -1)

+                    break;

+

+                if (!wps->wphdr.block_samples || wps->sample_index == wps->wphdr.block_index)

+                    if (!unpack_init (wpc))

+                        break;

+        }

+

+        if (!wps->wphdr.block_samples || !(wps->wphdr.flags & INITIAL_BLOCK) ||

+            wps->sample_index >= wps->wphdr.block_index + wps->wphdr.block_samples)

+                continue;

+

+        if (wps->sample_index < wps->wphdr.block_index) {

+            samples_to_unpack = wps->wphdr.block_index - wps->sample_index;

+

+            if (samples_to_unpack > samples)

+                samples_to_unpack = samples;

+

+            wps->sample_index += samples_to_unpack;

+            samples_unpacked += samples_to_unpack;

+            samples -= samples_to_unpack;

+

+            if (wpc->reduced_channels)

+                samples_to_unpack *= wpc->reduced_channels;

+            else

+                samples_to_unpack *= num_channels;

+

+            while (samples_to_unpack--)

+                *buffer++ = 0;

+

+            continue;

+        }

+

+        samples_to_unpack = wps->wphdr.block_index + wps->wphdr.block_samples - wps->sample_index;

+

+        if (samples_to_unpack > samples)

+            samples_to_unpack = samples;

+

+        unpack_samples (wpc, buffer, samples_to_unpack);

+

+        if (wpc->reduced_channels)

+            buffer += samples_to_unpack * wpc->reduced_channels;

+        else

+            buffer += samples_to_unpack * num_channels;

+

+        samples_unpacked += samples_to_unpack;

+        samples -= samples_to_unpack;

+

+        if (wps->sample_index == wps->wphdr.block_index + wps->wphdr.block_samples) {

+            if (check_crc_error (wpc))

+                wpc->crc_errors++;

+        }

+

+        if (wps->sample_index == wpc->total_samples)

+            break;

+    }

+

+    return samples_unpacked;

+}

+

+// Get total number of samples contained in the WavPack file, or -1 if unknown

+

+uint32_t WavpackGetNumSamples (WavpackContext *wpc)

+{

+    return wpc ? wpc->total_samples : (uint32_t) -1;

+}

+

+// Get the current sample index position, or -1 if unknown

+

+uint32_t WavpackGetSampleIndex (WavpackContext *wpc)

+{

+    if (wpc)

+        return wpc->stream.sample_index;

+

+    return (uint32_t) -1;

+}

+

+// Get the number of errors encountered so far

+

+int WavpackGetNumErrors (WavpackContext *wpc)

+{

+    return wpc ? wpc->crc_errors : 0;

+}

+

+// return TRUE if any uncorrected lossy blocks were actually written or read

+

+int WavpackLossyBlocks (WavpackContext *wpc)

+{

+    return wpc ? wpc->lossy_blocks : 0;

+}

+

+// Returns the sample rate of the specified WavPack file

+

+uint32_t WavpackGetSampleRate (WavpackContext *wpc)

+{

+    return wpc ? wpc->config.sample_rate : 44100;

+}

+

+// Returns the number of channels of the specified WavPack file. Note that

+// this is the actual number of channels contained in the file, but this

+// version can only decode the first two.

+

+int WavpackGetNumChannels (WavpackContext *wpc)

+{

+    return wpc ? wpc->config.num_channels : 2;

+}

+

+// Returns the actual number of valid bits per sample contained in the

+// original file, which may or may not be a multiple of 8. Floating data

+// always has 32 bits, integers may be from 1 to 32 bits each. When this

+// value is not a multiple of 8, then the "extra" bits are located in the

+// LSBs of the results. That is, values are right justified when unpacked

+// into longs, but are left justified in the number of bytes used by the

+// original data.

+

+int WavpackGetBitsPerSample (WavpackContext *wpc)

+{

+    return wpc ? wpc->config.bits_per_sample : 16;

+}

+

+// Returns the number of bytes used for each sample (1 to 4) in the original

+// file. This is required information for the user of this module because the

+// audio data is returned in the LOWER bytes of the long buffer and must be

+// left-shifted 8, 16, or 24 bits if normalized longs are required.

+

+int WavpackGetBytesPerSample (WavpackContext *wpc)

+{

+    return wpc ? wpc->config.bytes_per_sample : 2;

+}

+

+// This function will return the actual number of channels decoded from the

+// file (which may or may not be less than the actual number of channels, but

+// will always be 1 or 2). Normally, this will be the front left and right

+// channels of a multi-channel file.

+

+int WavpackGetReducedChannels (WavpackContext *wpc)

+{

+    if (wpc)

+        return wpc->reduced_channels ? wpc->reduced_channels : wpc->config.num_channels;

+    else

+        return 2;

+}

+

+// Read from current file position until a valid 32-byte WavPack 4.0 header is

+// found and read into the specified pointer. The number of bytes skipped is

+// returned. If no WavPack header is found within 1 meg, then a -1 is returned

+// to indicate the error. No additional bytes are read past the header and it

+// is returned in the processor's native endian mode. Seeking is not required.

+

+static uint32_t read_next_header (read_stream infile, WavpackHeader *wphdr)

+{

+    char buffer [sizeof (*wphdr)], *sp = buffer + sizeof (*wphdr), *ep = sp;

+    uint32_t bytes_skipped = 0;

+    int bleft;

+

+    while (1) {

+        if (sp < ep) {

+            bleft = ep - sp;

+            memcpy (buffer, sp, bleft);

+        }

+        else

+            bleft = 0;

+

+        if (infile (buffer + bleft, sizeof (*wphdr) - bleft) != (int32_t) sizeof (*wphdr) - bleft)

+            return -1;

+

+        sp = buffer;

+

+        if (*sp++ == 'w' && *sp == 'v' && *++sp == 'p' && *++sp == 'k' &&

+            !(*++sp & 1) && sp [2] < 16 && !sp [3] && sp [5] == 4 &&

+            sp [4] >= (MIN_STREAM_VERS & 0xff) && sp [4] <= (MAX_STREAM_VERS & 0xff)) {

+                memcpy (wphdr, buffer, sizeof (*wphdr));

+                little_endian_to_native (wphdr, WavpackHeaderFormat);

+                return bytes_skipped;

+            }

+

+        while (sp < ep && *sp != 'w')

+            sp++;

+

+        if ((bytes_skipped += sp - buffer) > 1048576L)

+            return -1;

+    }

+}

diff --git a/src/engine/external/wavpack/wvfilter.c.no_compile b/src/engine/external/wavpack/wvfilter.c.no_compile
new file mode 100644
index 00000000..f80d73dd
--- /dev/null
+++ b/src/engine/external/wavpack/wvfilter.c.no_compile
@@ -0,0 +1,200 @@
+////////////////////////////////////////////////////////////////////////////

+//                           **** WAVPACK ****                            //

+//                  Hybrid Lossless Wavefile Compressor                   //

+//              Copyright (c) 1998 - 2006 Conifer Software.               //

+//                          All Rights Reserved.                          //

+//      Distributed under the BSD Software License (see license.txt)      //

+////////////////////////////////////////////////////////////////////////////

+

+// wv_filter.c

+

+// This is the main module for the demonstration WavPack command-line

+// decoder filter. It uses the tiny "hardware" version of the decoder and

+// accepts WavPack files on stdin and outputs a standard MS wav file to

+// stdout. Note that this involves converting the data to little-endian

+// (if the executing processor is not), possibly packing the data into

+// fewer bytes per sample, and generating an appropriate riff wav header.

+// Note that this is NOT the copy of the RIFF header that might be stored

+// in the file, and any additional RIFF information and tags are lost.

+// See wputils.c for further limitations.

+

+#include "wavpack.h"

+

+#if defined(WIN32)

+#include <io.h>

+#include <fcntl.h>

+#endif

+

+#include <string.h>

+

+// These structures are used to place a wav riff header at the beginning of

+// the output.

+

+typedef struct {

+    char ckID [4];

+    uint32_t ckSize;

+    char formType [4];

+} RiffChunkHeader;

+

+typedef struct {

+    char ckID [4];

+    uint32_t ckSize;

+} ChunkHeader;

+

+#define ChunkHeaderFormat "4L"

+

+typedef struct {

+    ushort FormatTag, NumChannels;

+    uint32_t SampleRate, BytesPerSecond;

+    ushort BlockAlign, BitsPerSample;

+} WaveHeader;

+

+#define WaveHeaderFormat "SSLLSS"

+

+static uchar *format_samples (int bps, uchar *dst, int32_t *src, uint32_t samcnt);

+static int32_t read_bytes (void *buff, int32_t bcount);

+static int32_t temp_buffer [256];

+

+int main ()

+{

+    ChunkHeader FormatChunkHeader, DataChunkHeader;

+    RiffChunkHeader RiffChunkHeader;

+    WaveHeader WaveHeader;

+

+    uint32_t total_unpacked_samples = 0, total_samples;

+    int num_channels, bps;

+    WavpackContext *wpc;

+    char error [80];

+

+#if defined(WIN32)

+    setmode (fileno (stdin), O_BINARY);

+    setmode (fileno (stdout), O_BINARY);

+#endif

+

+    wpc = WavpackOpenFileInput (read_bytes, error);

+

+    if (!wpc) {

+        fputs (error, stderr);

+        fputs ("\n", stderr);

+        return 1;

+    }

+

+    num_channels = WavpackGetReducedChannels (wpc);

+    total_samples = WavpackGetNumSamples (wpc);

+    bps = WavpackGetBytesPerSample (wpc);

+

+    strncpy (RiffChunkHeader.ckID, "RIFF", sizeof (RiffChunkHeader.ckID));

+    RiffChunkHeader.ckSize = total_samples * num_channels * bps + sizeof (ChunkHeader) * 2 + sizeof (WaveHeader) + 4;

+    strncpy (RiffChunkHeader.formType, "WAVE", sizeof (RiffChunkHeader.formType));

+

+    strncpy (FormatChunkHeader.ckID, "fmt ", sizeof (FormatChunkHeader.ckID));

+    FormatChunkHeader.ckSize = sizeof (WaveHeader);

+

+    WaveHeader.FormatTag = 1;

+    WaveHeader.NumChannels = num_channels;

+    WaveHeader.SampleRate = WavpackGetSampleRate (wpc);

+    WaveHeader.BlockAlign = num_channels * bps;

+    WaveHeader.BytesPerSecond = WaveHeader.SampleRate * WaveHeader.BlockAlign;

+    WaveHeader.BitsPerSample = WavpackGetBitsPerSample (wpc);

+

+    strncpy (DataChunkHeader.ckID, "data", sizeof (DataChunkHeader.ckID));

+    DataChunkHeader.ckSize = total_samples * num_channels * bps;

+

+    native_to_little_endian (&RiffChunkHeader, ChunkHeaderFormat);

+    native_to_little_endian (&FormatChunkHeader, ChunkHeaderFormat);

+    native_to_little_endian (&WaveHeader, WaveHeaderFormat);

+    native_to_little_endian (&DataChunkHeader, ChunkHeaderFormat);

+

+    if (!fwrite (&RiffChunkHeader, sizeof (RiffChunkHeader), 1, stdout) ||

+        !fwrite (&FormatChunkHeader, sizeof (FormatChunkHeader), 1, stdout) ||

+        !fwrite (&WaveHeader, sizeof (WaveHeader), 1, stdout) ||

+        !fwrite (&DataChunkHeader, sizeof (DataChunkHeader), 1, stdout)) {

+            fputs ("can't write .WAV data, disk probably full!\n", stderr);

+            return 1;

+        }

+

+    while (1) {

+        uint32_t samples_unpacked;

+

+        samples_unpacked = WavpackUnpackSamples (wpc, temp_buffer, 256 / num_channels);

+        total_unpacked_samples += samples_unpacked;

+

+        if (samples_unpacked) {

+            format_samples (bps, (uchar *) temp_buffer, temp_buffer, samples_unpacked *= num_channels);

+

+            if (fwrite (temp_buffer, bps, samples_unpacked, stdout) != samples_unpacked) {

+                fputs ("can't write .WAV data, disk probably full!\n", stderr);

+                return 1;

+            }

+        }

+

+        if (!samples_unpacked)

+            break;

+    }

+

+    fflush (stdout);

+

+    if (WavpackGetNumSamples (wpc) != (uint32_t) -1 &&

+        total_unpacked_samples != WavpackGetNumSamples (wpc)) {

+            fputs ("incorrect number of samples!\n", stderr);

+            return 1;

+    }

+

+    if (WavpackGetNumErrors (wpc)) {

+        fputs ("crc errors detected!\n", stderr);

+        return 1;

+    }

+

+    return 0;

+}

+

+static int32_t read_bytes (void *buff, int32_t bcount)

+{

+    return fread (buff, 1, bcount, stdin);

+}

+

+// Reformat samples from longs in processor's native endian mode to

+// little-endian data with (possibly) less than 4 bytes / sample.

+

+static uchar *format_samples (int bps, uchar *dst, int32_t *src, uint32_t samcnt)

+{

+    int32_t temp;

+

+    switch (bps) {

+

+        case 1:

+            while (samcnt--)

+                *dst++ = *src++ + 128;

+

+            break;

+

+        case 2:

+            while (samcnt--) {

+                *dst++ = (uchar)(temp = *src++);

+                *dst++ = (uchar)(temp >> 8);

+            }

+

+            break;

+

+        case 3:

+            while (samcnt--) {

+                *dst++ = (uchar)(temp = *src++);

+                *dst++ = (uchar)(temp >> 8);

+                *dst++ = (uchar)(temp >> 16);

+            }

+

+            break;

+

+        case 4:

+            while (samcnt--) {

+                *dst++ = (uchar)(temp = *src++);

+                *dst++ = (uchar)(temp >> 8);

+                *dst++ = (uchar)(temp >> 16);

+                *dst++ = (uchar)(temp >> 24);

+            }

+

+            break;

+    }

+

+    return dst;

+}

diff --git a/src/engine/external/zlib/VERSION b/src/engine/external/zlib/VERSION
new file mode 100644
index 00000000..0495c4a8
--- /dev/null
+++ b/src/engine/external/zlib/VERSION
@@ -0,0 +1 @@
+1.2.3
diff --git a/src/engine/external/zlib/adler32.c b/src/engine/external/zlib/adler32.c
new file mode 100644
index 00000000..007ba262
--- /dev/null
+++ b/src/engine/external/zlib/adler32.c
@@ -0,0 +1,149 @@
+/* adler32.c -- compute the Adler-32 checksum of a data stream
+ * Copyright (C) 1995-2004 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* @(#) $Id$ */
+
+#define ZLIB_INTERNAL
+#include "zlib.h"
+
+#define BASE 65521UL    /* 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 */
+#ifdef NO_DIVIDE
+#  define MOD(a) \
+    do { \
+        if (a >= (BASE << 16)) a -= (BASE << 16); \
+        if (a >= (BASE << 15)) a -= (BASE << 15); \
+        if (a >= (BASE << 14)) a -= (BASE << 14); \
+        if (a >= (BASE << 13)) a -= (BASE << 13); \
+        if (a >= (BASE << 12)) a -= (BASE << 12); \
+        if (a >= (BASE << 11)) a -= (BASE << 11); \
+        if (a >= (BASE << 10)) a -= (BASE << 10); \
+        if (a >= (BASE << 9)) a -= (BASE << 9); \
+        if (a >= (BASE << 8)) a -= (BASE << 8); \
+        if (a >= (BASE << 7)) a -= (BASE << 7); \
+        if (a >= (BASE << 6)) a -= (BASE << 6); \
+        if (a >= (BASE << 5)) a -= (BASE << 5); \
+        if (a >= (BASE << 4)) a -= (BASE << 4); \
+        if (a >= (BASE << 3)) a -= (BASE << 3); \
+        if (a >= (BASE << 2)) a -= (BASE << 2); \
+        if (a >= (BASE << 1)) a -= (BASE << 1); \
+        if (a >= BASE) a -= BASE; \
+    } while (0)
+#  define MOD4(a) \
+    do { \
+        if (a >= (BASE << 4)) a -= (BASE << 4); \
+        if (a >= (BASE << 3)) a -= (BASE << 3); \
+        if (a >= (BASE << 2)) a -= (BASE << 2); \
+        if (a >= (BASE << 1)) a -= (BASE << 1); \
+        if (a >= BASE) a -= BASE; \
+    } while (0)
+#else
+#  define MOD(a) a %= BASE
+#  define MOD4(a) a %= BASE
+#endif
+
+/* ========================================================================= */
+uLong ZEXPORT adler32(adler, buf, len)
+    uLong adler;
+    const Bytef *buf;
+    uInt 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;
+        MOD4(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_combine(adler1, adler2, len2)
+    uLong adler1;
+    uLong adler2;
+    z_off_t len2;
+{
+    unsigned long sum1;
+    unsigned long sum2;
+    unsigned rem;
+
+    /* the derivation of this formula is left as an exercise for the reader */
+    rem = (unsigned)(len2 % BASE);
+    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 > (BASE << 1)) sum2 -= (BASE << 1);
+    if (sum2 > BASE) sum2 -= BASE;
+    return sum1 | (sum2 << 16);
+}
diff --git a/src/engine/external/zlib/compress.c b/src/engine/external/zlib/compress.c
new file mode 100644
index 00000000..df04f014
--- /dev/null
+++ b/src/engine/external/zlib/compress.c
@@ -0,0 +1,79 @@
+/* compress.c -- compress a memory buffer
+ * Copyright (C) 1995-2003 Jean-loup Gailly.
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* @(#) $Id$ */
+
+#define ZLIB_INTERNAL
+#include "zlib.h"
+
+/* ===========================================================================
+     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 0.1% larger than sourceLen plus
+   12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
+
+     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.
+*/
+int ZEXPORT compress2 (dest, destLen, source, sourceLen, level)
+    Bytef *dest;
+    uLongf *destLen;
+    const Bytef *source;
+    uLong sourceLen;
+    int level;
+{
+    z_stream stream;
+    int err;
+
+    stream.next_in = (Bytef*)source;
+    stream.avail_in = (uInt)sourceLen;
+#ifdef MAXSEG_64K
+    /* Check for source > 64K on 16-bit machine: */
+    if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
+#endif
+    stream.next_out = dest;
+    stream.avail_out = (uInt)*destLen;
+    if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
+
+    stream.zalloc = (alloc_func)0;
+    stream.zfree = (free_func)0;
+    stream.opaque = (voidpf)0;
+
+    err = deflateInit(&stream, level);
+    if (err != Z_OK) return err;
+
+    err = deflate(&stream, Z_FINISH);
+    if (err != Z_STREAM_END) {
+        deflateEnd(&stream);
+        return err == Z_OK ? Z_BUF_ERROR : err;
+    }
+    *destLen = stream.total_out;
+
+    err = deflateEnd(&stream);
+    return err;
+}
+
+/* ===========================================================================
+ */
+int ZEXPORT compress (dest, destLen, source, sourceLen)
+    Bytef *dest;
+    uLongf *destLen;
+    const Bytef *source;
+    uLong sourceLen;
+{
+    return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
+}
+
+/* ===========================================================================
+     If the default memLevel or windowBits for deflateInit() is changed, then
+   this function needs to be updated.
+ */
+uLong ZEXPORT compressBound (sourceLen)
+    uLong sourceLen;
+{
+    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
+}
diff --git a/src/engine/external/zlib/crc32.c b/src/engine/external/zlib/crc32.c
new file mode 100644
index 00000000..f658a9ef
--- /dev/null
+++ b/src/engine/external/zlib/crc32.c
@@ -0,0 +1,423 @@
+/* crc32.c -- compute the CRC-32 of a data stream
+ * Copyright (C) 1995-2005 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().
+ */
+
+#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 */
+
+#define local static
+
+/* Find a four-byte integer type for crc32_little() and crc32_big(). */
+#ifndef NOBYFOUR
+#  ifdef STDC           /* need ANSI C limits.h to determine sizes */
+#    include <limits.h>
+#    define BYFOUR
+#    if (UINT_MAX == 0xffffffffUL)
+       typedef unsigned int u4;
+#    else
+#      if (ULONG_MAX == 0xffffffffUL)
+         typedef unsigned long u4;
+#      else
+#        if (USHRT_MAX == 0xffffffffUL)
+           typedef unsigned short u4;
+#        else
+#          undef BYFOUR     /* can't find a four-byte integer type! */
+#        endif
+#      endif
+#    endif
+#  endif /* STDC */
+#endif /* !NOBYFOUR */
+
+/* Definitions for doing the crc four data bytes at a time. */
+#ifdef BYFOUR
+#  define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
+                (((w)&0xff00)<<8)+(((w)&0xff)<<24))
+   local unsigned long crc32_little OF((unsigned long,
+                        const unsigned char FAR *, unsigned));
+   local unsigned long crc32_big OF((unsigned long,
+                        const unsigned char FAR *, unsigned));
+#  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));
+
+#ifdef DYNAMIC_CRC_TABLE
+
+local volatile int crc_table_empty = 1;
+local unsigned long FAR crc_table[TBLS][256];
+local void make_crc_table OF((void));
+#ifdef MAKECRCH
+   local void write_table OF((FILE *, const unsigned long 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()
+{
+    unsigned long c;
+    int n, k;
+    unsigned long 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 = 0UL;
+        for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
+            poly |= 1UL << (31 - p[n]);
+
+        /* generate a crc for every 8-bit value */
+        for (n = 0; n < 256; n++) {
+            c = (unsigned long)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] = REV(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] = REV(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 unsigned long 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 unsigned long FAR *table;
+{
+    int n;
+
+    for (n = 0; n < 256; n++)
+        fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : "    ", 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 unsigned long FAR * ZEXPORT get_crc_table()
+{
+#ifdef DYNAMIC_CRC_TABLE
+    if (crc_table_empty)
+        make_crc_table();
+#endif /* DYNAMIC_CRC_TABLE */
+    return (const unsigned long 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(crc, buf, len)
+    unsigned long crc;
+    const unsigned char FAR *buf;
+    unsigned 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)) {
+        u4 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;
+}
+
+#ifdef BYFOUR
+
+/* ========================================================================= */
+#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;
+    unsigned len;
+{
+    register u4 c;
+    register const u4 FAR *buf4;
+
+    c = (u4)crc;
+    c = ~c;
+    while (len && ((ptrdiff_t)buf & 3)) {
+        c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
+        len--;
+    }
+
+    buf4 = (const u4 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;
+    unsigned len;
+{
+    register u4 c;
+    register const u4 FAR *buf4;
+
+    c = REV((u4)crc);
+    c = ~c;
+    while (len && ((ptrdiff_t)buf & 3)) {
+        c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
+        len--;
+    }
+
+    buf4 = (const u4 FAR *)(const void FAR *)buf;
+    buf4--;
+    while (len >= 32) {
+        DOBIG32;
+        len -= 32;
+    }
+    while (len >= 4) {
+        DOBIG4;
+        len -= 4;
+    }
+    buf4++;
+    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)(REV(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]);
+}
+
+/* ========================================================================= */
+uLong ZEXPORT crc32_combine(crc1, crc2, len2)
+    uLong crc1;
+    uLong crc2;
+    z_off_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 */
+    if (len2 == 0)
+        return crc1;
+
+    /* put operator for one zero bit in odd */
+    odd[0] = 0xedb88320L;           /* 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;
+}
diff --git a/src/engine/external/zlib/crc32.h b/src/engine/external/zlib/crc32.h
new file mode 100644
index 00000000..8053b611
--- /dev/null
+++ b/src/engine/external/zlib/crc32.h
@@ -0,0 +1,441 @@
+/* crc32.h -- tables for rapid CRC calculation
+ * Generated automatically by crc32.c
+ */
+
+local const unsigned long 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
+  }
+};
diff --git a/src/engine/external/zlib/deflate.c b/src/engine/external/zlib/deflate.c
new file mode 100644
index 00000000..29ce1f64
--- /dev/null
+++ b/src/engine/external/zlib/deflate.c
@@ -0,0 +1,1736 @@
+/* deflate.c -- compress data using the deflation algorithm
+ * Copyright (C) 1995-2005 Jean-loup Gailly.
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/*
+ *  ALGORITHM
+ *
+ *      The "deflation" process depends on being able to identify portions
+ *      of the input text which are identical to earlier input (within a
+ *      sliding window trailing behind the input currently being processed).
+ *
+ *      The most straightforward technique turns out to be the fastest for
+ *      most input files: try all possible matches and select the longest.
+ *      The key feature of this algorithm is that insertions into the string
+ *      dictionary are very simple and thus fast, and deletions are avoided
+ *      completely. Insertions are performed at each input character, whereas
+ *      string matches are performed only when the previous match ends. So it
+ *      is preferable to spend more time in matches to allow very fast string
+ *      insertions and avoid deletions. The matching algorithm for small
+ *      strings is inspired from that of Rabin & Karp. A brute force approach
+ *      is used to find longer strings when a small match has been found.
+ *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
+ *      (by Leonid Broukhis).
+ *         A previous version of this file used a more sophisticated algorithm
+ *      (by Fiala and Greene) which is guaranteed to run in linear amortized
+ *      time, but has a larger average cost, uses more memory and is patented.
+ *      However the F&G algorithm may be faster for some highly redundant
+ *      files if the parameter max_chain_length (described below) is too large.
+ *
+ *  ACKNOWLEDGEMENTS
+ *
+ *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
+ *      I found it in 'freeze' written by Leonid Broukhis.
+ *      Thanks to many people for bug reports and testing.
+ *
+ *  REFERENCES
+ *
+ *      Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
+ *      Available in http://www.ietf.org/rfc/rfc1951.txt
+ *
+ *      A description of the Rabin and Karp algorithm is given in the book
+ *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
+ *
+ *      Fiala,E.R., and Greene,D.H.
+ *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
+ *
+ */
+
+/* @(#) $Id$ */
+
+#include "deflate.h"
+
+const char deflate_copyright[] =
+   " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
+/*
+  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.
+ */
+
+/* ===========================================================================
+ *  Function prototypes.
+ */
+typedef enum {
+    need_more,      /* block not completed, need more input or more output */
+    block_done,     /* block flush performed */
+    finish_started, /* finish started, need only more output at next deflate */
+    finish_done     /* finish done, accept no more input or output */
+} block_state;
+
+typedef block_state (*compress_func) OF((deflate_state *s, int flush));
+/* Compression function. Returns the block state after the call. */
+
+local void fill_window    OF((deflate_state *s));
+local block_state deflate_stored OF((deflate_state *s, int flush));
+local block_state deflate_fast   OF((deflate_state *s, int flush));
+#ifndef FASTEST
+local block_state deflate_slow   OF((deflate_state *s, int flush));
+#endif
+local void lm_init        OF((deflate_state *s));
+local void putShortMSB    OF((deflate_state *s, uInt b));
+local void flush_pending  OF((z_streamp strm));
+local int read_buf        OF((z_streamp strm, Bytef *buf, unsigned size));
+#ifndef FASTEST
+#ifdef ASMV
+      void match_init OF((void)); /* asm code initialization */
+      uInt longest_match  OF((deflate_state *s, IPos cur_match));
+#else
+local uInt longest_match  OF((deflate_state *s, IPos cur_match));
+#endif
+#endif
+local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
+
+#ifdef DEBUG
+local  void check_match OF((deflate_state *s, IPos start, IPos match,
+                            int length));
+#endif
+
+/* ===========================================================================
+ * Local data
+ */
+
+#define NIL 0
+/* Tail of hash chains */
+
+#ifndef TOO_FAR
+#  define TOO_FAR 4096
+#endif
+/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
+
+#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
+/* Minimum amount of lookahead, except at the end of the input file.
+ * See deflate.c for comments about the MIN_MATCH+1.
+ */
+
+/* Values for max_lazy_match, good_match and max_chain_length, depending on
+ * the desired pack level (0..9). The values given below have been tuned to
+ * exclude worst case performance for pathological files. Better values may be
+ * found for specific files.
+ */
+typedef struct config_s {
+   ush good_length; /* reduce lazy search above this match length */
+   ush max_lazy;    /* do not perform lazy search above this match length */
+   ush nice_length; /* quit search above this match length */
+   ush max_chain;
+   compress_func func;
+} config;
+
+#ifdef FASTEST
+local const config configuration_table[2] = {
+/*      good lazy nice chain */
+/* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
+/* 1 */ {4,    4,  8,    4, deflate_fast}}; /* max speed, no lazy matches */
+#else
+local const config configuration_table[10] = {
+/*      good lazy nice chain */
+/* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
+/* 1 */ {4,    4,  8,    4, deflate_fast}, /* max speed, no lazy matches */
+/* 2 */ {4,    5, 16,    8, deflate_fast},
+/* 3 */ {4,    6, 32,   32, deflate_fast},
+
+/* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */
+/* 5 */ {8,   16, 32,   32, deflate_slow},
+/* 6 */ {8,   16, 128, 128, deflate_slow},
+/* 7 */ {8,   32, 128, 256, deflate_slow},
+/* 8 */ {32, 128, 258, 1024, deflate_slow},
+/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
+#endif
+
+/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
+ * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
+ * meaning.
+ */
+
+#define EQUAL 0
+/* result of memcmp for equal strings */
+
+#ifndef NO_DUMMY_DECL
+struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
+#endif
+
+/* ===========================================================================
+ * Update a hash value with the given input byte
+ * IN  assertion: all calls to to UPDATE_HASH are made with consecutive
+ *    input characters, so that a running hash key can be computed from the
+ *    previous key instead of complete recalculation each time.
+ */
+#define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
+
+
+/* ===========================================================================
+ * Insert string str in the dictionary and set match_head to the previous head
+ * of the hash chain (the most recent string with same hash key). Return
+ * the previous length of the hash chain.
+ * If this file is compiled with -DFASTEST, the compression level is forced
+ * to 1, and no hash chains are maintained.
+ * IN  assertion: all calls to to INSERT_STRING are made with consecutive
+ *    input characters and the first MIN_MATCH bytes of str are valid
+ *    (except for the last MIN_MATCH-1 bytes of the input file).
+ */
+#ifdef FASTEST
+#define INSERT_STRING(s, str, match_head) \
+   (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
+    match_head = s->head[s->ins_h], \
+    s->head[s->ins_h] = (Pos)(str))
+#else
+#define INSERT_STRING(s, str, match_head) \
+   (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
+    match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
+    s->head[s->ins_h] = (Pos)(str))
+#endif
+
+/* ===========================================================================
+ * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
+ * prev[] will be initialized on the fly.
+ */
+#define CLEAR_HASH(s) \
+    s->head[s->hash_size-1] = NIL; \
+    zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
+
+/* ========================================================================= */
+int ZEXPORT deflateInit_(strm, level, version, stream_size)
+    z_streamp strm;
+    int level;
+    const char *version;
+    int stream_size;
+{
+    return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
+                         Z_DEFAULT_STRATEGY, version, stream_size);
+    /* To do: ignore strm->next_in if we use it as window */
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
+                  version, stream_size)
+    z_streamp strm;
+    int  level;
+    int  method;
+    int  windowBits;
+    int  memLevel;
+    int  strategy;
+    const char *version;
+    int stream_size;
+{
+    deflate_state *s;
+    int wrap = 1;
+    static const char my_version[] = ZLIB_VERSION;
+
+    ushf *overlay;
+    /* We overlay pending_buf and d_buf+l_buf. This works since the average
+     * output size for (length,distance) codes is <= 24 bits.
+     */
+
+    if (version == Z_NULL || version[0] != my_version[0] ||
+        stream_size != sizeof(z_stream)) {
+        return Z_VERSION_ERROR;
+    }
+    if (strm == Z_NULL) return Z_STREAM_ERROR;
+
+    strm->msg = Z_NULL;
+    if (strm->zalloc == (alloc_func)0) {
+        strm->zalloc = zcalloc;
+        strm->opaque = (voidpf)0;
+    }
+    if (strm->zfree == (free_func)0) strm->zfree = zcfree;
+
+#ifdef FASTEST
+    if (level != 0) level = 1;
+#else
+    if (level == Z_DEFAULT_COMPRESSION) level = 6;
+#endif
+
+    if (windowBits < 0) { /* suppress zlib wrapper */
+        wrap = 0;
+        windowBits = -windowBits;
+    }
+#ifdef GZIP
+    else if (windowBits > 15) {
+        wrap = 2;       /* write gzip wrapper instead */
+        windowBits -= 16;
+    }
+#endif
+    if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
+        windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
+        strategy < 0 || strategy > Z_FIXED) {
+        return Z_STREAM_ERROR;
+    }
+    if (windowBits == 8) windowBits = 9;  /* until 256-byte window bug fixed */
+    s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
+    if (s == Z_NULL) return Z_MEM_ERROR;
+    strm->state = (struct internal_state FAR *)s;
+    s->strm = strm;
+
+    s->wrap = wrap;
+    s->gzhead = Z_NULL;
+    s->w_bits = windowBits;
+    s->w_size = 1 << s->w_bits;
+    s->w_mask = s->w_size - 1;
+
+    s->hash_bits = memLevel + 7;
+    s->hash_size = 1 << s->hash_bits;
+    s->hash_mask = s->hash_size - 1;
+    s->hash_shift =  ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
+
+    s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
+    s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));
+    s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));
+
+    s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
+
+    overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
+    s->pending_buf = (uchf *) overlay;
+    s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
+
+    if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
+        s->pending_buf == Z_NULL) {
+        s->status = FINISH_STATE;
+        strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
+        deflateEnd (strm);
+        return Z_MEM_ERROR;
+    }
+    s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
+    s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
+
+    s->level = level;
+    s->strategy = strategy;
+    s->method = (Byte)method;
+
+    return deflateReset(strm);
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
+    z_streamp strm;
+    const Bytef *dictionary;
+    uInt  dictLength;
+{
+    deflate_state *s;
+    uInt length = dictLength;
+    uInt n;
+    IPos hash_head = 0;
+
+    if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
+        strm->state->wrap == 2 ||
+        (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
+        return Z_STREAM_ERROR;
+
+    s = strm->state;
+    if (s->wrap)
+        strm->adler = adler32(strm->adler, dictionary, dictLength);
+
+    if (length < MIN_MATCH) return Z_OK;
+    if (length > MAX_DIST(s)) {
+        length = MAX_DIST(s);
+        dictionary += dictLength - length; /* use the tail of the dictionary */
+    }
+    zmemcpy(s->window, dictionary, length);
+    s->strstart = length;
+    s->block_start = (long)length;
+
+    /* Insert all strings in the hash table (except for the last two bytes).
+     * s->lookahead stays null, so s->ins_h will be recomputed at the next
+     * call of fill_window.
+     */
+    s->ins_h = s->window[0];
+    UPDATE_HASH(s, s->ins_h, s->window[1]);
+    for (n = 0; n <= length - MIN_MATCH; n++) {
+        INSERT_STRING(s, n, hash_head);
+    }
+    if (hash_head) hash_head = 0;  /* to make compiler happy */
+    return Z_OK;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateReset (strm)
+    z_streamp strm;
+{
+    deflate_state *s;
+
+    if (strm == Z_NULL || strm->state == Z_NULL ||
+        strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
+        return Z_STREAM_ERROR;
+    }
+
+    strm->total_in = strm->total_out = 0;
+    strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
+    strm->data_type = Z_UNKNOWN;
+
+    s = (deflate_state *)strm->state;
+    s->pending = 0;
+    s->pending_out = s->pending_buf;
+
+    if (s->wrap < 0) {
+        s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
+    }
+    s->status = s->wrap ? INIT_STATE : BUSY_STATE;
+    strm->adler =
+#ifdef GZIP
+        s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
+#endif
+        adler32(0L, Z_NULL, 0);
+    s->last_flush = Z_NO_FLUSH;
+
+    _tr_init(s);
+    lm_init(s);
+
+    return Z_OK;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateSetHeader (strm, head)
+    z_streamp strm;
+    gz_headerp head;
+{
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    if (strm->state->wrap != 2) return Z_STREAM_ERROR;
+    strm->state->gzhead = head;
+    return Z_OK;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflatePrime (strm, bits, value)
+    z_streamp strm;
+    int bits;
+    int value;
+{
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    strm->state->bi_valid = bits;
+    strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
+    return Z_OK;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateParams(strm, level, strategy)
+    z_streamp strm;
+    int level;
+    int strategy;
+{
+    deflate_state *s;
+    compress_func func;
+    int err = Z_OK;
+
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    s = strm->state;
+
+#ifdef FASTEST
+    if (level != 0) level = 1;
+#else
+    if (level == Z_DEFAULT_COMPRESSION) level = 6;
+#endif
+    if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
+        return Z_STREAM_ERROR;
+    }
+    func = configuration_table[s->level].func;
+
+    if (func != configuration_table[level].func && strm->total_in != 0) {
+        /* Flush the last buffer: */
+        err = deflate(strm, Z_PARTIAL_FLUSH);
+    }
+    if (s->level != level) {
+        s->level = level;
+        s->max_lazy_match   = configuration_table[level].max_lazy;
+        s->good_match       = configuration_table[level].good_length;
+        s->nice_match       = configuration_table[level].nice_length;
+        s->max_chain_length = configuration_table[level].max_chain;
+    }
+    s->strategy = strategy;
+    return err;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
+    z_streamp strm;
+    int good_length;
+    int max_lazy;
+    int nice_length;
+    int max_chain;
+{
+    deflate_state *s;
+
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    s = strm->state;
+    s->good_match = good_length;
+    s->max_lazy_match = max_lazy;
+    s->nice_match = nice_length;
+    s->max_chain_length = max_chain;
+    return Z_OK;
+}
+
+/* =========================================================================
+ * For the default windowBits of 15 and memLevel of 8, this function returns
+ * a close to exact, as well as small, upper bound on the compressed size.
+ * They are coded as constants here for a reason--if the #define's are
+ * changed, then this function needs to be changed as well.  The return
+ * value for 15 and 8 only works for those exact settings.
+ *
+ * For any setting other than those defaults for windowBits and memLevel,
+ * the value returned is a conservative worst case for the maximum expansion
+ * resulting from using fixed blocks instead of stored blocks, which deflate
+ * can emit on compressed data for some combinations of the parameters.
+ *
+ * This function could be more sophisticated to provide closer upper bounds
+ * for every combination of windowBits and memLevel, as well as wrap.
+ * But even the conservative upper bound of about 14% expansion does not
+ * seem onerous for output buffer allocation.
+ */
+uLong ZEXPORT deflateBound(strm, sourceLen)
+    z_streamp strm;
+    uLong sourceLen;
+{
+    deflate_state *s;
+    uLong destLen;
+
+    /* conservative upper bound */
+    destLen = sourceLen +
+              ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
+
+    /* if can't get parameters, return conservative bound */
+    if (strm == Z_NULL || strm->state == Z_NULL)
+        return destLen;
+
+    /* if not default parameters, return conservative bound */
+    s = strm->state;
+    if (s->w_bits != 15 || s->hash_bits != 8 + 7)
+        return destLen;
+
+    /* default settings: return tight bound for that case */
+    return compressBound(sourceLen);
+}
+
+/* =========================================================================
+ * Put a short in the pending buffer. The 16-bit value is put in MSB order.
+ * IN assertion: the stream state is correct and there is enough room in
+ * pending_buf.
+ */
+local void putShortMSB (s, b)
+    deflate_state *s;
+    uInt b;
+{
+    put_byte(s, (Byte)(b >> 8));
+    put_byte(s, (Byte)(b & 0xff));
+}
+
+/* =========================================================================
+ * Flush as much pending output as possible. All deflate() output goes
+ * through this function so some applications may wish to modify it
+ * to avoid allocating a large strm->next_out buffer and copying into it.
+ * (See also read_buf()).
+ */
+local void flush_pending(strm)
+    z_streamp strm;
+{
+    unsigned len = strm->state->pending;
+
+    if (len > strm->avail_out) len = strm->avail_out;
+    if (len == 0) return;
+
+    zmemcpy(strm->next_out, strm->state->pending_out, len);
+    strm->next_out  += len;
+    strm->state->pending_out  += len;
+    strm->total_out += len;
+    strm->avail_out  -= len;
+    strm->state->pending -= len;
+    if (strm->state->pending == 0) {
+        strm->state->pending_out = strm->state->pending_buf;
+    }
+}
+
+/* ========================================================================= */
+int ZEXPORT deflate (strm, flush)
+    z_streamp strm;
+    int flush;
+{
+    int old_flush; /* value of flush param for previous deflate call */
+    deflate_state *s;
+
+    if (strm == Z_NULL || strm->state == Z_NULL ||
+        flush > Z_FINISH || flush < 0) {
+        return Z_STREAM_ERROR;
+    }
+    s = strm->state;
+
+    if (strm->next_out == Z_NULL ||
+        (strm->next_in == Z_NULL && strm->avail_in != 0) ||
+        (s->status == FINISH_STATE && flush != Z_FINISH)) {
+        ERR_RETURN(strm, Z_STREAM_ERROR);
+    }
+    if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
+
+    s->strm = strm; /* just in case */
+    old_flush = s->last_flush;
+    s->last_flush = flush;
+
+    /* Write the header */
+    if (s->status == INIT_STATE) {
+#ifdef GZIP
+        if (s->wrap == 2) {
+            strm->adler = crc32(0L, Z_NULL, 0);
+            put_byte(s, 31);
+            put_byte(s, 139);
+            put_byte(s, 8);
+            if (s->gzhead == NULL) {
+                put_byte(s, 0);
+                put_byte(s, 0);
+                put_byte(s, 0);
+                put_byte(s, 0);
+                put_byte(s, 0);
+                put_byte(s, s->level == 9 ? 2 :
+                            (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
+                             4 : 0));
+                put_byte(s, OS_CODE);
+                s->status = BUSY_STATE;
+            }
+            else {
+                put_byte(s, (s->gzhead->text ? 1 : 0) +
+                            (s->gzhead->hcrc ? 2 : 0) +
+                            (s->gzhead->extra == Z_NULL ? 0 : 4) +
+                            (s->gzhead->name == Z_NULL ? 0 : 8) +
+                            (s->gzhead->comment == Z_NULL ? 0 : 16)
+                        );
+                put_byte(s, (Byte)(s->gzhead->time & 0xff));
+                put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
+                put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
+                put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
+                put_byte(s, s->level == 9 ? 2 :
+                            (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
+                             4 : 0));
+                put_byte(s, s->gzhead->os & 0xff);
+                if (s->gzhead->extra != NULL) {
+                    put_byte(s, s->gzhead->extra_len & 0xff);
+                    put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
+                }
+                if (s->gzhead->hcrc)
+                    strm->adler = crc32(strm->adler, s->pending_buf,
+                                        s->pending);
+                s->gzindex = 0;
+                s->status = EXTRA_STATE;
+            }
+        }
+        else
+#endif
+        {
+            uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
+            uInt level_flags;
+
+            if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
+                level_flags = 0;
+            else if (s->level < 6)
+                level_flags = 1;
+            else if (s->level == 6)
+                level_flags = 2;
+            else
+                level_flags = 3;
+            header |= (level_flags << 6);
+            if (s->strstart != 0) header |= PRESET_DICT;
+            header += 31 - (header % 31);
+
+            s->status = BUSY_STATE;
+            putShortMSB(s, header);
+
+            /* Save the adler32 of the preset dictionary: */
+            if (s->strstart != 0) {
+                putShortMSB(s, (uInt)(strm->adler >> 16));
+                putShortMSB(s, (uInt)(strm->adler & 0xffff));
+            }
+            strm->adler = adler32(0L, Z_NULL, 0);
+        }
+    }
+#ifdef GZIP
+    if (s->status == EXTRA_STATE) {
+        if (s->gzhead->extra != NULL) {
+            uInt beg = s->pending;  /* start of bytes to update crc */
+
+            while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
+                if (s->pending == s->pending_buf_size) {
+                    if (s->gzhead->hcrc && s->pending > beg)
+                        strm->adler = crc32(strm->adler, s->pending_buf + beg,
+                                            s->pending - beg);
+                    flush_pending(strm);
+                    beg = s->pending;
+                    if (s->pending == s->pending_buf_size)
+                        break;
+                }
+                put_byte(s, s->gzhead->extra[s->gzindex]);
+                s->gzindex++;
+            }
+            if (s->gzhead->hcrc && s->pending > beg)
+                strm->adler = crc32(strm->adler, s->pending_buf + beg,
+                                    s->pending - beg);
+            if (s->gzindex == s->gzhead->extra_len) {
+                s->gzindex = 0;
+                s->status = NAME_STATE;
+            }
+        }
+        else
+            s->status = NAME_STATE;
+    }
+    if (s->status == NAME_STATE) {
+        if (s->gzhead->name != NULL) {
+            uInt beg = s->pending;  /* start of bytes to update crc */
+            int val;
+
+            do {
+                if (s->pending == s->pending_buf_size) {
+                    if (s->gzhead->hcrc && s->pending > beg)
+                        strm->adler = crc32(strm->adler, s->pending_buf + beg,
+                                            s->pending - beg);
+                    flush_pending(strm);
+                    beg = s->pending;
+                    if (s->pending == s->pending_buf_size) {
+                        val = 1;
+                        break;
+                    }
+                }
+                val = s->gzhead->name[s->gzindex++];
+                put_byte(s, val);
+            } while (val != 0);
+            if (s->gzhead->hcrc && s->pending > beg)
+                strm->adler = crc32(strm->adler, s->pending_buf + beg,
+                                    s->pending - beg);
+            if (val == 0) {
+                s->gzindex = 0;
+                s->status = COMMENT_STATE;
+            }
+        }
+        else
+            s->status = COMMENT_STATE;
+    }
+    if (s->status == COMMENT_STATE) {
+        if (s->gzhead->comment != NULL) {
+            uInt beg = s->pending;  /* start of bytes to update crc */
+            int val;
+
+            do {
+                if (s->pending == s->pending_buf_size) {
+                    if (s->gzhead->hcrc && s->pending > beg)
+                        strm->adler = crc32(strm->adler, s->pending_buf + beg,
+                                            s->pending - beg);
+                    flush_pending(strm);
+                    beg = s->pending;
+                    if (s->pending == s->pending_buf_size) {
+                        val = 1;
+                        break;
+                    }
+                }
+                val = s->gzhead->comment[s->gzindex++];
+                put_byte(s, val);
+            } while (val != 0);
+            if (s->gzhead->hcrc && s->pending > beg)
+                strm->adler = crc32(strm->adler, s->pending_buf + beg,
+                                    s->pending - beg);
+            if (val == 0)
+                s->status = HCRC_STATE;
+        }
+        else
+            s->status = HCRC_STATE;
+    }
+    if (s->status == HCRC_STATE) {
+        if (s->gzhead->hcrc) {
+            if (s->pending + 2 > s->pending_buf_size)
+                flush_pending(strm);
+            if (s->pending + 2 <= s->pending_buf_size) {
+                put_byte(s, (Byte)(strm->adler & 0xff));
+                put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
+                strm->adler = crc32(0L, Z_NULL, 0);
+                s->status = BUSY_STATE;
+            }
+        }
+        else
+            s->status = BUSY_STATE;
+    }
+#endif
+
+    /* Flush as much pending output as possible */
+    if (s->pending != 0) {
+        flush_pending(strm);
+        if (strm->avail_out == 0) {
+            /* Since avail_out is 0, deflate will be called again with
+             * more output space, but possibly with both pending and
+             * avail_in equal to zero. There won't be anything to do,
+             * but this is not an error situation so make sure we
+             * return OK instead of BUF_ERROR at next call of deflate:
+             */
+            s->last_flush = -1;
+            return Z_OK;
+        }
+
+    /* Make sure there is something to do and avoid duplicate consecutive
+     * flushes. For repeated and useless calls with Z_FINISH, we keep
+     * returning Z_STREAM_END instead of Z_BUF_ERROR.
+     */
+    } else if (strm->avail_in == 0 && flush <= old_flush &&
+               flush != Z_FINISH) {
+        ERR_RETURN(strm, Z_BUF_ERROR);
+    }
+
+    /* User must not provide more input after the first FINISH: */
+    if (s->status == FINISH_STATE && strm->avail_in != 0) {
+        ERR_RETURN(strm, Z_BUF_ERROR);
+    }
+
+    /* Start a new block or continue the current one.
+     */
+    if (strm->avail_in != 0 || s->lookahead != 0 ||
+        (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
+        block_state bstate;
+
+        bstate = (*(configuration_table[s->level].func))(s, flush);
+
+        if (bstate == finish_started || bstate == finish_done) {
+            s->status = FINISH_STATE;
+        }
+        if (bstate == need_more || bstate == finish_started) {
+            if (strm->avail_out == 0) {
+                s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
+            }
+            return Z_OK;
+            /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
+             * of deflate should use the same flush parameter to make sure
+             * that the flush is complete. So we don't have to output an
+             * empty block here, this will be done at next call. This also
+             * ensures that for a very small output buffer, we emit at most
+             * one empty block.
+             */
+        }
+        if (bstate == block_done) {
+            if (flush == Z_PARTIAL_FLUSH) {
+                _tr_align(s);
+            } else { /* FULL_FLUSH or SYNC_FLUSH */
+                _tr_stored_block(s, (char*)0, 0L, 0);
+                /* For a full flush, this empty block will be recognized
+                 * as a special marker by inflate_sync().
+                 */
+                if (flush == Z_FULL_FLUSH) {
+                    CLEAR_HASH(s);             /* forget history */
+                }
+            }
+            flush_pending(strm);
+            if (strm->avail_out == 0) {
+              s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
+              return Z_OK;
+            }
+        }
+    }
+    Assert(strm->avail_out > 0, "bug2");
+
+    if (flush != Z_FINISH) return Z_OK;
+    if (s->wrap <= 0) return Z_STREAM_END;
+
+    /* Write the trailer */
+#ifdef GZIP
+    if (s->wrap == 2) {
+        put_byte(s, (Byte)(strm->adler & 0xff));
+        put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
+        put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
+        put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
+        put_byte(s, (Byte)(strm->total_in & 0xff));
+        put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
+        put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
+        put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
+    }
+    else
+#endif
+    {
+        putShortMSB(s, (uInt)(strm->adler >> 16));
+        putShortMSB(s, (uInt)(strm->adler & 0xffff));
+    }
+    flush_pending(strm);
+    /* If avail_out is zero, the application will call deflate again
+     * to flush the rest.
+     */
+    if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
+    return s->pending != 0 ? Z_OK : Z_STREAM_END;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateEnd (strm)
+    z_streamp strm;
+{
+    int status;
+
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+
+    status = strm->state->status;
+    if (status != INIT_STATE &&
+        status != EXTRA_STATE &&
+        status != NAME_STATE &&
+        status != COMMENT_STATE &&
+        status != HCRC_STATE &&
+        status != BUSY_STATE &&
+        status != FINISH_STATE) {
+      return Z_STREAM_ERROR;
+    }
+
+    /* Deallocate in reverse order of allocations: */
+    TRY_FREE(strm, strm->state->pending_buf);
+    TRY_FREE(strm, strm->state->head);
+    TRY_FREE(strm, strm->state->prev);
+    TRY_FREE(strm, strm->state->window);
+
+    ZFREE(strm, strm->state);
+    strm->state = Z_NULL;
+
+    return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
+}
+
+/* =========================================================================
+ * Copy the source state to the destination state.
+ * To simplify the source, this is not supported for 16-bit MSDOS (which
+ * doesn't have enough memory anyway to duplicate compression states).
+ */
+int ZEXPORT deflateCopy (dest, source)
+    z_streamp dest;
+    z_streamp source;
+{
+#ifdef MAXSEG_64K
+    return Z_STREAM_ERROR;
+#else
+    deflate_state *ds;
+    deflate_state *ss;
+    ushf *overlay;
+
+
+    if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
+        return Z_STREAM_ERROR;
+    }
+
+    ss = source->state;
+
+    zmemcpy(dest, source, sizeof(z_stream));
+
+    ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
+    if (ds == Z_NULL) return Z_MEM_ERROR;
+    dest->state = (struct internal_state FAR *) ds;
+    zmemcpy(ds, ss, sizeof(deflate_state));
+    ds->strm = dest;
+
+    ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
+    ds->prev   = (Posf *)  ZALLOC(dest, ds->w_size, sizeof(Pos));
+    ds->head   = (Posf *)  ZALLOC(dest, ds->hash_size, sizeof(Pos));
+    overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
+    ds->pending_buf = (uchf *) overlay;
+
+    if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
+        ds->pending_buf == Z_NULL) {
+        deflateEnd (dest);
+        return Z_MEM_ERROR;
+    }
+    /* following zmemcpy do not work for 16-bit MSDOS */
+    zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
+    zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
+    zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
+    zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
+
+    ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
+    ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
+    ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
+
+    ds->l_desc.dyn_tree = ds->dyn_ltree;
+    ds->d_desc.dyn_tree = ds->dyn_dtree;
+    ds->bl_desc.dyn_tree = ds->bl_tree;
+
+    return Z_OK;
+#endif /* MAXSEG_64K */
+}
+
+/* ===========================================================================
+ * Read a new buffer from the current input stream, update the adler32
+ * and total number of bytes read.  All deflate() input goes through
+ * this function so some applications may wish to modify it to avoid
+ * allocating a large strm->next_in buffer and copying from it.
+ * (See also flush_pending()).
+ */
+local int read_buf(strm, buf, size)
+    z_streamp strm;
+    Bytef *buf;
+    unsigned size;
+{
+    unsigned len = strm->avail_in;
+
+    if (len > size) len = size;
+    if (len == 0) return 0;
+
+    strm->avail_in  -= len;
+
+    if (strm->state->wrap == 1) {
+        strm->adler = adler32(strm->adler, strm->next_in, len);
+    }
+#ifdef GZIP
+    else if (strm->state->wrap == 2) {
+        strm->adler = crc32(strm->adler, strm->next_in, len);
+    }
+#endif
+    zmemcpy(buf, strm->next_in, len);
+    strm->next_in  += len;
+    strm->total_in += len;
+
+    return (int)len;
+}
+
+/* ===========================================================================
+ * Initialize the "longest match" routines for a new zlib stream
+ */
+local void lm_init (s)
+    deflate_state *s;
+{
+    s->window_size = (ulg)2L*s->w_size;
+
+    CLEAR_HASH(s);
+
+    /* Set the default configuration parameters:
+     */
+    s->max_lazy_match   = configuration_table[s->level].max_lazy;
+    s->good_match       = configuration_table[s->level].good_length;
+    s->nice_match       = configuration_table[s->level].nice_length;
+    s->max_chain_length = configuration_table[s->level].max_chain;
+
+    s->strstart = 0;
+    s->block_start = 0L;
+    s->lookahead = 0;
+    s->match_length = s->prev_length = MIN_MATCH-1;
+    s->match_available = 0;
+    s->ins_h = 0;
+#ifndef FASTEST
+#ifdef ASMV
+    match_init(); /* initialize the asm code */
+#endif
+#endif
+}
+
+#ifndef FASTEST
+/* ===========================================================================
+ * Set match_start to the longest match starting at the given string and
+ * return its length. Matches shorter or equal to prev_length are discarded,
+ * in which case the result is equal to prev_length and match_start is
+ * garbage.
+ * IN assertions: cur_match is the head of the hash chain for the current
+ *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
+ * OUT assertion: the match length is not greater than s->lookahead.
+ */
+#ifndef ASMV
+/* For 80x86 and 680x0, an optimized version will be provided in match.asm or
+ * match.S. The code will be functionally equivalent.
+ */
+local uInt longest_match(s, cur_match)
+    deflate_state *s;
+    IPos cur_match;                             /* current match */
+{
+    unsigned chain_length = s->max_chain_length;/* max hash chain length */
+    register Bytef *scan = s->window + s->strstart; /* current string */
+    register Bytef *match;                       /* matched string */
+    register int len;                           /* length of current match */
+    int best_len = s->prev_length;              /* best match length so far */
+    int nice_match = s->nice_match;             /* stop if match long enough */
+    IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
+        s->strstart - (IPos)MAX_DIST(s) : NIL;
+    /* Stop when cur_match becomes <= limit. To simplify the code,
+     * we prevent matches with the string of window index 0.
+     */
+    Posf *prev = s->prev;
+    uInt wmask = s->w_mask;
+
+#ifdef UNALIGNED_OK
+    /* Compare two bytes at a time. Note: this is not always beneficial.
+     * Try with and without -DUNALIGNED_OK to check.
+     */
+    register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
+    register ush scan_start = *(ushf*)scan;
+    register ush scan_end   = *(ushf*)(scan+best_len-1);
+#else
+    register Bytef *strend = s->window + s->strstart + MAX_MATCH;
+    register Byte scan_end1  = scan[best_len-1];
+    register Byte scan_end   = scan[best_len];
+#endif
+
+    /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
+     * It is easy to get rid of this optimization if necessary.
+     */
+    Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
+
+    /* Do not waste too much time if we already have a good match: */
+    if (s->prev_length >= s->good_match) {
+        chain_length >>= 2;
+    }
+    /* Do not look for matches beyond the end of the input. This is necessary
+     * to make deflate deterministic.
+     */
+    if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
+
+    Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
+
+    do {
+        Assert(cur_match < s->strstart, "no future");
+        match = s->window + cur_match;
+
+        /* Skip to next match if the match length cannot increase
+         * or if the match length is less than 2.  Note that the checks below
+         * for insufficient lookahead only occur occasionally for performance
+         * reasons.  Therefore uninitialized memory will be accessed, and
+         * conditional jumps will be made that depend on those values.
+         * However the length of the match is limited to the lookahead, so
+         * the output of deflate is not affected by the uninitialized values.
+         */
+#if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
+        /* This code assumes sizeof(unsigned short) == 2. Do not use
+         * UNALIGNED_OK if your compiler uses a different size.
+         */
+        if (*(ushf*)(match+best_len-1) != scan_end ||
+            *(ushf*)match != scan_start) continue;
+
+        /* It is not necessary to compare scan[2] and match[2] since they are
+         * always equal when the other bytes match, given that the hash keys
+         * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
+         * strstart+3, +5, ... up to strstart+257. We check for insufficient
+         * lookahead only every 4th comparison; the 128th check will be made
+         * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
+         * necessary to put more guard bytes at the end of the window, or
+         * to check more often for insufficient lookahead.
+         */
+        Assert(scan[2] == match[2], "scan[2]?");
+        scan++, match++;
+        do {
+        } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
+                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
+                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
+                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
+                 scan < strend);
+        /* The funny "do {}" generates better code on most compilers */
+
+        /* Here, scan <= window+strstart+257 */
+        Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
+        if (*scan == *match) scan++;
+
+        len = (MAX_MATCH - 1) - (int)(strend-scan);
+        scan = strend - (MAX_MATCH-1);
+
+#else /* UNALIGNED_OK */
+
+        if (match[best_len]   != scan_end  ||
+            match[best_len-1] != scan_end1 ||
+            *match            != *scan     ||
+            *++match          != scan[1])      continue;
+
+        /* The check at best_len-1 can be removed because it will be made
+         * again later. (This heuristic is not always a win.)
+         * It is not necessary to compare scan[2] and match[2] since they
+         * are always equal when the other bytes match, given that
+         * the hash keys are equal and that HASH_BITS >= 8.
+         */
+        scan += 2, match++;
+        Assert(*scan == *match, "match[2]?");
+
+        /* We check for insufficient lookahead only every 8th comparison;
+         * the 256th check will be made at strstart+258.
+         */
+        do {
+        } while (*++scan == *++match && *++scan == *++match &&
+                 *++scan == *++match && *++scan == *++match &&
+                 *++scan == *++match && *++scan == *++match &&
+                 *++scan == *++match && *++scan == *++match &&
+                 scan < strend);
+
+        Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
+
+        len = MAX_MATCH - (int)(strend - scan);
+        scan = strend - MAX_MATCH;
+
+#endif /* UNALIGNED_OK */
+
+        if (len > best_len) {
+            s->match_start = cur_match;
+            best_len = len;
+            if (len >= nice_match) break;
+#ifdef UNALIGNED_OK
+            scan_end = *(ushf*)(scan+best_len-1);
+#else
+            scan_end1  = scan[best_len-1];
+            scan_end   = scan[best_len];
+#endif
+        }
+    } while ((cur_match = prev[cur_match & wmask]) > limit
+             && --chain_length != 0);
+
+    if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
+    return s->lookahead;
+}
+#endif /* ASMV */
+#endif /* FASTEST */
+
+/* ---------------------------------------------------------------------------
+ * Optimized version for level == 1 or strategy == Z_RLE only
+ */
+local uInt longest_match_fast(s, cur_match)
+    deflate_state *s;
+    IPos cur_match;                             /* current match */
+{
+    register Bytef *scan = s->window + s->strstart; /* current string */
+    register Bytef *match;                       /* matched string */
+    register int len;                           /* length of current match */
+    register Bytef *strend = s->window + s->strstart + MAX_MATCH;
+
+    /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
+     * It is easy to get rid of this optimization if necessary.
+     */
+    Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
+
+    Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
+
+    Assert(cur_match < s->strstart, "no future");
+
+    match = s->window + cur_match;
+
+    /* Return failure if the match length is less than 2:
+     */
+    if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
+
+    /* The check at best_len-1 can be removed because it will be made
+     * again later. (This heuristic is not always a win.)
+     * It is not necessary to compare scan[2] and match[2] since they
+     * are always equal when the other bytes match, given that
+     * the hash keys are equal and that HASH_BITS >= 8.
+     */
+    scan += 2, match += 2;
+    Assert(*scan == *match, "match[2]?");
+
+    /* We check for insufficient lookahead only every 8th comparison;
+     * the 256th check will be made at strstart+258.
+     */
+    do {
+    } while (*++scan == *++match && *++scan == *++match &&
+             *++scan == *++match && *++scan == *++match &&
+             *++scan == *++match && *++scan == *++match &&
+             *++scan == *++match && *++scan == *++match &&
+             scan < strend);
+
+    Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
+
+    len = MAX_MATCH - (int)(strend - scan);
+
+    if (len < MIN_MATCH) return MIN_MATCH - 1;
+
+    s->match_start = cur_match;
+    return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
+}
+
+#ifdef DEBUG
+/* ===========================================================================
+ * Check that the match at match_start is indeed a match.
+ */
+local void check_match(s, start, match, length)
+    deflate_state *s;
+    IPos start, match;
+    int length;
+{
+    /* check that the match is indeed a match */
+    if (zmemcmp(s->window + match,
+                s->window + start, length) != EQUAL) {
+        fprintf(stderr, " start %u, match %u, length %d\n",
+                start, match, length);
+        do {
+            fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
+        } while (--length != 0);
+        z_error("invalid match");
+    }
+    if (z_verbose > 1) {
+        fprintf(stderr,"\\[%d,%d]", start-match, length);
+        do { putc(s->window[start++], stderr); } while (--length != 0);
+    }
+}
+#else
+#  define check_match(s, start, match, length)
+#endif /* DEBUG */
+
+/* ===========================================================================
+ * Fill the window when the lookahead becomes insufficient.
+ * Updates strstart and lookahead.
+ *
+ * IN assertion: lookahead < MIN_LOOKAHEAD
+ * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
+ *    At least one byte has been read, or avail_in == 0; reads are
+ *    performed for at least two bytes (required for the zip translate_eol
+ *    option -- not supported here).
+ */
+local void fill_window(s)
+    deflate_state *s;
+{
+    register unsigned n, m;
+    register Posf *p;
+    unsigned more;    /* Amount of free space at the end of the window. */
+    uInt wsize = s->w_size;
+
+    do {
+        more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
+
+        /* Deal with !@#$% 64K limit: */
+        if (sizeof(int) <= 2) {
+            if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
+                more = wsize;
+
+            } else if (more == (unsigned)(-1)) {
+                /* Very unlikely, but possible on 16 bit machine if
+                 * strstart == 0 && lookahead == 1 (input done a byte at time)
+                 */
+                more--;
+            }
+        }
+
+        /* If the window is almost full and there is insufficient lookahead,
+         * move the upper half to the lower one to make room in the upper half.
+         */
+        if (s->strstart >= wsize+MAX_DIST(s)) {
+
+            zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
+            s->match_start -= wsize;
+            s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
+            s->block_start -= (long) wsize;
+
+            /* Slide the hash table (could be avoided with 32 bit values
+               at the expense of memory usage). We slide even when level == 0
+               to keep the hash table consistent if we switch back to level > 0
+               later. (Using level 0 permanently is not an optimal usage of
+               zlib, so we don't care about this pathological case.)
+             */
+            /* %%% avoid this when Z_RLE */
+            n = s->hash_size;
+            p = &s->head[n];
+            do {
+                m = *--p;
+                *p = (Pos)(m >= wsize ? m-wsize : NIL);
+            } while (--n);
+
+            n = wsize;
+#ifndef FASTEST
+            p = &s->prev[n];
+            do {
+                m = *--p;
+                *p = (Pos)(m >= wsize ? m-wsize : NIL);
+                /* If n is not on any hash chain, prev[n] is garbage but
+                 * its value will never be used.
+                 */
+            } while (--n);
+#endif
+            more += wsize;
+        }
+        if (s->strm->avail_in == 0) return;
+
+        /* If there was no sliding:
+         *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
+         *    more == window_size - lookahead - strstart
+         * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
+         * => more >= window_size - 2*WSIZE + 2
+         * In the BIG_MEM or MMAP case (not yet supported),
+         *   window_size == input_size + MIN_LOOKAHEAD  &&
+         *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
+         * Otherwise, window_size == 2*WSIZE so more >= 2.
+         * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
+         */
+        Assert(more >= 2, "more < 2");
+
+        n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
+        s->lookahead += n;
+
+        /* Initialize the hash value now that we have some input: */
+        if (s->lookahead >= MIN_MATCH) {
+            s->ins_h = s->window[s->strstart];
+            UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
+#if MIN_MATCH != 3
+            Call UPDATE_HASH() MIN_MATCH-3 more times
+#endif
+        }
+        /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
+         * but this is not important since only literal bytes will be emitted.
+         */
+
+    } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
+}
+
+/* ===========================================================================
+ * Flush the current block, with given end-of-file flag.
+ * IN assertion: strstart is set to the end of the current match.
+ */
+#define FLUSH_BLOCK_ONLY(s, eof) { \
+   _tr_flush_block(s, (s->block_start >= 0L ? \
+                   (charf *)&s->window[(unsigned)s->block_start] : \
+                   (charf *)Z_NULL), \
+                (ulg)((long)s->strstart - s->block_start), \
+                (eof)); \
+   s->block_start = s->strstart; \
+   flush_pending(s->strm); \
+   Tracev((stderr,"[FLUSH]")); \
+}
+
+/* Same but force premature exit if necessary. */
+#define FLUSH_BLOCK(s, eof) { \
+   FLUSH_BLOCK_ONLY(s, eof); \
+   if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
+}
+
+/* ===========================================================================
+ * Copy without compression as much as possible from the input stream, return
+ * the current block state.
+ * This function does not insert new strings in the dictionary since
+ * uncompressible data is probably not useful. This function is used
+ * only for the level=0 compression option.
+ * NOTE: this function should be optimized to avoid extra copying from
+ * window to pending_buf.
+ */
+local block_state deflate_stored(s, flush)
+    deflate_state *s;
+    int flush;
+{
+    /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
+     * to pending_buf_size, and each stored block has a 5 byte header:
+     */
+    ulg max_block_size = 0xffff;
+    ulg max_start;
+
+    if (max_block_size > s->pending_buf_size - 5) {
+        max_block_size = s->pending_buf_size - 5;
+    }
+
+    /* Copy as much as possible from input to output: */
+    for (;;) {
+        /* Fill the window as much as possible: */
+        if (s->lookahead <= 1) {
+
+            Assert(s->strstart < s->w_size+MAX_DIST(s) ||
+                   s->block_start >= (long)s->w_size, "slide too late");
+
+            fill_window(s);
+            if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
+
+            if (s->lookahead == 0) break; /* flush the current block */
+        }
+        Assert(s->block_start >= 0L, "block gone");
+
+        s->strstart += s->lookahead;
+        s->lookahead = 0;
+
+        /* Emit a stored block if pending_buf will be full: */
+        max_start = s->block_start + max_block_size;
+        if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
+            /* strstart == 0 is possible when wraparound on 16-bit machine */
+            s->lookahead = (uInt)(s->strstart - max_start);
+            s->strstart = (uInt)max_start;
+            FLUSH_BLOCK(s, 0);
+        }
+        /* Flush if we may have to slide, otherwise block_start may become
+         * negative and the data will be gone:
+         */
+        if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
+            FLUSH_BLOCK(s, 0);
+        }
+    }
+    FLUSH_BLOCK(s, flush == Z_FINISH);
+    return flush == Z_FINISH ? finish_done : block_done;
+}
+
+/* ===========================================================================
+ * Compress as much as possible from the input stream, return the current
+ * block state.
+ * This function does not perform lazy evaluation of matches and inserts
+ * new strings in the dictionary only for unmatched strings or for short
+ * matches. It is used only for the fast compression options.
+ */
+local block_state deflate_fast(s, flush)
+    deflate_state *s;
+    int flush;
+{
+    IPos hash_head = NIL; /* head of the hash chain */
+    int bflush;           /* set if current block must be flushed */
+
+    for (;;) {
+        /* Make sure that we always have enough lookahead, except
+         * at the end of the input file. We need MAX_MATCH bytes
+         * for the next match, plus MIN_MATCH bytes to insert the
+         * string following the next match.
+         */
+        if (s->lookahead < MIN_LOOKAHEAD) {
+            fill_window(s);
+            if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
+                return need_more;
+            }
+            if (s->lookahead == 0) break; /* flush the current block */
+        }
+
+        /* Insert the string window[strstart .. strstart+2] in the
+         * dictionary, and set hash_head to the head of the hash chain:
+         */
+        if (s->lookahead >= MIN_MATCH) {
+            INSERT_STRING(s, s->strstart, hash_head);
+        }
+
+        /* Find the longest match, discarding those <= prev_length.
+         * At this point we have always match_length < MIN_MATCH
+         */
+        if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
+            /* To simplify the code, we prevent matches with the string
+             * of window index 0 (in particular we have to avoid a match
+             * of the string with itself at the start of the input file).
+             */
+#ifdef FASTEST
+            if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
+                (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
+                s->match_length = longest_match_fast (s, hash_head);
+            }
+#else
+            if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
+                s->match_length = longest_match (s, hash_head);
+            } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
+                s->match_length = longest_match_fast (s, hash_head);
+            }
+#endif
+            /* longest_match() or longest_match_fast() sets match_start */
+        }
+        if (s->match_length >= MIN_MATCH) {
+            check_match(s, s->strstart, s->match_start, s->match_length);
+
+            _tr_tally_dist(s, s->strstart - s->match_start,
+                           s->match_length - MIN_MATCH, bflush);
+
+            s->lookahead -= s->match_length;
+
+            /* Insert new strings in the hash table only if the match length
+             * is not too large. This saves time but degrades compression.
+             */
+#ifndef FASTEST
+            if (s->match_length <= s->max_insert_length &&
+                s->lookahead >= MIN_MATCH) {
+                s->match_length--; /* string at strstart already in table */
+                do {
+                    s->strstart++;
+                    INSERT_STRING(s, s->strstart, hash_head);
+                    /* strstart never exceeds WSIZE-MAX_MATCH, so there are
+                     * always MIN_MATCH bytes ahead.
+                     */
+                } while (--s->match_length != 0);
+                s->strstart++;
+            } else
+#endif
+            {
+                s->strstart += s->match_length;
+                s->match_length = 0;
+                s->ins_h = s->window[s->strstart];
+                UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
+#if MIN_MATCH != 3
+                Call UPDATE_HASH() MIN_MATCH-3 more times
+#endif
+                /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
+                 * matter since it will be recomputed at next deflate call.
+                 */
+            }
+        } else {
+            /* No match, output a literal byte */
+            Tracevv((stderr,"%c", s->window[s->strstart]));
+            _tr_tally_lit (s, s->window[s->strstart], bflush);
+            s->lookahead--;
+            s->strstart++;
+        }
+        if (bflush) FLUSH_BLOCK(s, 0);
+    }
+    FLUSH_BLOCK(s, flush == Z_FINISH);
+    return flush == Z_FINISH ? finish_done : block_done;
+}
+
+#ifndef FASTEST
+/* ===========================================================================
+ * Same as above, but achieves better compression. We use a lazy
+ * evaluation for matches: a match is finally adopted only if there is
+ * no better match at the next window position.
+ */
+local block_state deflate_slow(s, flush)
+    deflate_state *s;
+    int flush;
+{
+    IPos hash_head = NIL;    /* head of hash chain */
+    int bflush;              /* set if current block must be flushed */
+
+    /* Process the input block. */
+    for (;;) {
+        /* Make sure that we always have enough lookahead, except
+         * at the end of the input file. We need MAX_MATCH bytes
+         * for the next match, plus MIN_MATCH bytes to insert the
+         * string following the next match.
+         */
+        if (s->lookahead < MIN_LOOKAHEAD) {
+            fill_window(s);
+            if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
+                return need_more;
+            }
+            if (s->lookahead == 0) break; /* flush the current block */
+        }
+
+        /* Insert the string window[strstart .. strstart+2] in the
+         * dictionary, and set hash_head to the head of the hash chain:
+         */
+        if (s->lookahead >= MIN_MATCH) {
+            INSERT_STRING(s, s->strstart, hash_head);
+        }
+
+        /* Find the longest match, discarding those <= prev_length.
+         */
+        s->prev_length = s->match_length, s->prev_match = s->match_start;
+        s->match_length = MIN_MATCH-1;
+
+        if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
+            s->strstart - hash_head <= MAX_DIST(s)) {
+            /* To simplify the code, we prevent matches with the string
+             * of window index 0 (in particular we have to avoid a match
+             * of the string with itself at the start of the input file).
+             */
+            if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
+                s->match_length = longest_match (s, hash_head);
+            } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
+                s->match_length = longest_match_fast (s, hash_head);
+            }
+            /* longest_match() or longest_match_fast() sets match_start */
+
+            if (s->match_length <= 5 && (s->strategy == Z_FILTERED
+#if TOO_FAR <= 32767
+                || (s->match_length == MIN_MATCH &&
+                    s->strstart - s->match_start > TOO_FAR)
+#endif
+                )) {
+
+                /* If prev_match is also MIN_MATCH, match_start is garbage
+                 * but we will ignore the current match anyway.
+                 */
+                s->match_length = MIN_MATCH-1;
+            }
+        }
+        /* If there was a match at the previous step and the current
+         * match is not better, output the previous match:
+         */
+        if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
+            uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
+            /* Do not insert strings in hash table beyond this. */
+
+            check_match(s, s->strstart-1, s->prev_match, s->prev_length);
+
+            _tr_tally_dist(s, s->strstart -1 - s->prev_match,
+                           s->prev_length - MIN_MATCH, bflush);
+
+            /* Insert in hash table all strings up to the end of the match.
+             * strstart-1 and strstart are already inserted. If there is not
+             * enough lookahead, the last two strings are not inserted in
+             * the hash table.
+             */
+            s->lookahead -= s->prev_length-1;
+            s->prev_length -= 2;
+            do {
+                if (++s->strstart <= max_insert) {
+                    INSERT_STRING(s, s->strstart, hash_head);
+                }
+            } while (--s->prev_length != 0);
+            s->match_available = 0;
+            s->match_length = MIN_MATCH-1;
+            s->strstart++;
+
+            if (bflush) FLUSH_BLOCK(s, 0);
+
+        } else if (s->match_available) {
+            /* If there was no match at the previous position, output a
+             * single literal. If there was a match but the current match
+             * is longer, truncate the previous match to a single literal.
+             */
+            Tracevv((stderr,"%c", s->window[s->strstart-1]));
+            _tr_tally_lit(s, s->window[s->strstart-1], bflush);
+            if (bflush) {
+                FLUSH_BLOCK_ONLY(s, 0);
+            }
+            s->strstart++;
+            s->lookahead--;
+            if (s->strm->avail_out == 0) return need_more;
+        } else {
+            /* There is no previous match to compare with, wait for
+             * the next step to decide.
+             */
+            s->match_available = 1;
+            s->strstart++;
+            s->lookahead--;
+        }
+    }
+    Assert (flush != Z_NO_FLUSH, "no flush?");
+    if (s->match_available) {
+        Tracevv((stderr,"%c", s->window[s->strstart-1]));
+        _tr_tally_lit(s, s->window[s->strstart-1], bflush);
+        s->match_available = 0;
+    }
+    FLUSH_BLOCK(s, flush == Z_FINISH);
+    return flush == Z_FINISH ? finish_done : block_done;
+}
+#endif /* FASTEST */
+
+#if 0
+/* ===========================================================================
+ * For Z_RLE, simply look for runs of bytes, generate matches only of distance
+ * one.  Do not maintain a hash table.  (It will be regenerated if this run of
+ * deflate switches away from Z_RLE.)
+ */
+local block_state deflate_rle(s, flush)
+    deflate_state *s;
+    int flush;
+{
+    int bflush;         /* set if current block must be flushed */
+    uInt run;           /* length of run */
+    uInt max;           /* maximum length of run */
+    uInt prev;          /* byte at distance one to match */
+    Bytef *scan;        /* scan for end of run */
+
+    for (;;) {
+        /* Make sure that we always have enough lookahead, except
+         * at the end of the input file. We need MAX_MATCH bytes
+         * for the longest encodable run.
+         */
+        if (s->lookahead < MAX_MATCH) {
+            fill_window(s);
+            if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
+                return need_more;
+            }
+            if (s->lookahead == 0) break; /* flush the current block */
+        }
+
+        /* See how many times the previous byte repeats */
+        run = 0;
+        if (s->strstart > 0) {      /* if there is a previous byte, that is */
+            max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
+            scan = s->window + s->strstart - 1;
+            prev = *scan++;
+            do {
+                if (*scan++ != prev)
+                    break;
+            } while (++run < max);
+        }
+
+        /* Emit match if have run of MIN_MATCH or longer, else emit literal */
+        if (run >= MIN_MATCH) {
+            check_match(s, s->strstart, s->strstart - 1, run);
+            _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
+            s->lookahead -= run;
+            s->strstart += run;
+        } else {
+            /* No match, output a literal byte */
+            Tracevv((stderr,"%c", s->window[s->strstart]));
+            _tr_tally_lit (s, s->window[s->strstart], bflush);
+            s->lookahead--;
+            s->strstart++;
+        }
+        if (bflush) FLUSH_BLOCK(s, 0);
+    }
+    FLUSH_BLOCK(s, flush == Z_FINISH);
+    return flush == Z_FINISH ? finish_done : block_done;
+}
+#endif
diff --git a/src/engine/external/zlib/deflate.h b/src/engine/external/zlib/deflate.h
new file mode 100644
index 00000000..05a5ab3a
--- /dev/null
+++ b/src/engine/external/zlib/deflate.h
@@ -0,0 +1,331 @@
+/* deflate.h -- internal compression state
+ * Copyright (C) 1995-2004 Jean-loup Gailly
+ * 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 DEFLATE_H
+#define DEFLATE_H
+
+#include "zutil.h"
+
+/* define NO_GZIP when compiling if you want to disable gzip header and
+   trailer creation by deflate().  NO_GZIP would be used to avoid linking in
+   the crc code when it is not needed.  For shared libraries, gzip encoding
+   should be left enabled. */
+#ifndef NO_GZIP
+#  define GZIP
+#endif
+
+/* ===========================================================================
+ * Internal compression state.
+ */
+
+#define LENGTH_CODES 29
+/* number of length codes, not counting the special END_BLOCK code */
+
+#define LITERALS  256
+/* number of literal bytes 0..255 */
+
+#define L_CODES (LITERALS+1+LENGTH_CODES)
+/* number of Literal or Length codes, including the END_BLOCK code */
+
+#define D_CODES   30
+/* number of distance codes */
+
+#define BL_CODES  19
+/* number of codes used to transfer the bit lengths */
+
+#define HEAP_SIZE (2*L_CODES+1)
+/* maximum heap size */
+
+#define MAX_BITS 15
+/* All codes must not exceed MAX_BITS bits */
+
+#define INIT_STATE    42
+#define EXTRA_STATE   69
+#define NAME_STATE    73
+#define COMMENT_STATE 91
+#define HCRC_STATE   103
+#define BUSY_STATE   113
+#define FINISH_STATE 666
+/* Stream status */
+
+
+/* Data structure describing a single value and its code string. */
+typedef struct ct_data_s {
+    union {
+        ush  freq;       /* frequency count */
+        ush  code;       /* bit string */
+    } fc;
+    union {
+        ush  dad;        /* father node in Huffman tree */
+        ush  len;        /* length of bit string */
+    } dl;
+} FAR ct_data;
+
+#define Freq fc.freq
+#define Code fc.code
+#define Dad  dl.dad
+#define Len  dl.len
+
+typedef struct static_tree_desc_s  static_tree_desc;
+
+typedef struct tree_desc_s {
+    ct_data *dyn_tree;           /* the dynamic tree */
+    int     max_code;            /* largest code with non zero frequency */
+    static_tree_desc *stat_desc; /* the corresponding static tree */
+} FAR tree_desc;
+
+typedef ush Pos;
+typedef Pos FAR Posf;
+typedef unsigned IPos;
+
+/* A Pos is an index in the character window. We use short instead of int to
+ * save space in the various tables. IPos is used only for parameter passing.
+ */
+
+typedef struct internal_state {
+    z_streamp strm;      /* pointer back to this zlib stream */
+    int   status;        /* as the name implies */
+    Bytef *pending_buf;  /* output still pending */
+    ulg   pending_buf_size; /* size of pending_buf */
+    Bytef *pending_out;  /* next pending byte to output to the stream */
+    uInt   pending;      /* nb of bytes in the pending buffer */
+    int   wrap;          /* bit 0 true for zlib, bit 1 true for gzip */
+    gz_headerp  gzhead;  /* gzip header information to write */
+    uInt   gzindex;      /* where in extra, name, or comment */
+    Byte  method;        /* STORED (for zip only) or DEFLATED */
+    int   last_flush;    /* value of flush param for previous deflate call */
+
+                /* used by deflate.c: */
+
+    uInt  w_size;        /* LZ77 window size (32K by default) */
+    uInt  w_bits;        /* log2(w_size)  (8..16) */
+    uInt  w_mask;        /* w_size - 1 */
+
+    Bytef *window;
+    /* Sliding window. Input bytes are read into the second half of the window,
+     * and move to the first half later to keep a dictionary of at least wSize
+     * bytes. With this organization, matches are limited to a distance of
+     * wSize-MAX_MATCH bytes, but this ensures that IO is always
+     * performed with a length multiple of the block size. Also, it limits
+     * the window size to 64K, which is quite useful on MSDOS.
+     * To do: use the user input buffer as sliding window.
+     */
+
+    ulg window_size;
+    /* Actual size of window: 2*wSize, except when the user input buffer
+     * is directly used as sliding window.
+     */
+
+    Posf *prev;
+    /* Link to older string with same hash index. To limit the size of this
+     * array to 64K, this link is maintained only for the last 32K strings.
+     * An index in this array is thus a window index modulo 32K.
+     */
+
+    Posf *head; /* Heads of the hash chains or NIL. */
+
+    uInt  ins_h;          /* hash index of string to be inserted */
+    uInt  hash_size;      /* number of elements in hash table */
+    uInt  hash_bits;      /* log2(hash_size) */
+    uInt  hash_mask;      /* hash_size-1 */
+
+    uInt  hash_shift;
+    /* Number of bits by which ins_h must be shifted at each input
+     * step. It must be such that after MIN_MATCH steps, the oldest
+     * byte no longer takes part in the hash key, that is:
+     *   hash_shift * MIN_MATCH >= hash_bits
+     */
+
+    long block_start;
+    /* Window position at the beginning of the current output block. Gets
+     * negative when the window is moved backwards.
+     */
+
+    uInt match_length;           /* length of best match */
+    IPos prev_match;             /* previous match */
+    int match_available;         /* set if previous match exists */
+    uInt strstart;               /* start of string to insert */
+    uInt match_start;            /* start of matching string */
+    uInt lookahead;              /* number of valid bytes ahead in window */
+
+    uInt prev_length;
+    /* Length of the best match at previous step. Matches not greater than this
+     * are discarded. This is used in the lazy match evaluation.
+     */
+
+    uInt max_chain_length;
+    /* To speed up deflation, hash chains are never searched beyond this
+     * length.  A higher limit improves compression ratio but degrades the
+     * speed.
+     */
+
+    uInt max_lazy_match;
+    /* Attempt to find a better match only when the current match is strictly
+     * smaller than this value. This mechanism is used only for compression
+     * levels >= 4.
+     */
+#   define max_insert_length  max_lazy_match
+    /* Insert new strings in the hash table only if the match length is not
+     * greater than this length. This saves time but degrades compression.
+     * max_insert_length is used only for compression levels <= 3.
+     */
+
+    int level;    /* compression level (1..9) */
+    int strategy; /* favor or force Huffman coding*/
+
+    uInt good_match;
+    /* Use a faster search when the previous match is longer than this */
+
+    int nice_match; /* Stop searching when current match exceeds this */
+
+                /* used by trees.c: */
+    /* Didn't use ct_data typedef below to supress compiler warning */
+    struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
+    struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
+    struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */
+
+    struct tree_desc_s l_desc;               /* desc. for literal tree */
+    struct tree_desc_s d_desc;               /* desc. for distance tree */
+    struct tree_desc_s bl_desc;              /* desc. for bit length tree */
+
+    ush bl_count[MAX_BITS+1];
+    /* number of codes at each bit length for an optimal tree */
+
+    int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */
+    int heap_len;               /* number of elements in the heap */
+    int heap_max;               /* element of largest frequency */
+    /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
+     * The same heap array is used to build all trees.
+     */
+
+    uch depth[2*L_CODES+1];
+    /* Depth of each subtree used as tie breaker for trees of equal frequency
+     */
+
+    uchf *l_buf;          /* buffer for literals or lengths */
+
+    uInt  lit_bufsize;
+    /* Size of match buffer for literals/lengths.  There are 4 reasons for
+     * limiting lit_bufsize to 64K:
+     *   - frequencies can be kept in 16 bit counters
+     *   - if compression is not successful for the first block, all input
+     *     data is still in the window so we can still emit a stored block even
+     *     when input comes from standard input.  (This can also be done for
+     *     all blocks if lit_bufsize is not greater than 32K.)
+     *   - if compression is not successful for a file smaller than 64K, we can
+     *     even emit a stored file instead of a stored block (saving 5 bytes).
+     *     This is applicable only for zip (not gzip or zlib).
+     *   - creating new Huffman trees less frequently may not provide fast
+     *     adaptation to changes in the input data statistics. (Take for
+     *     example a binary file with poorly compressible code followed by
+     *     a highly compressible string table.) Smaller buffer sizes give
+     *     fast adaptation but have of course the overhead of transmitting
+     *     trees more frequently.
+     *   - I can't count above 4
+     */
+
+    uInt last_lit;      /* running index in l_buf */
+
+    ushf *d_buf;
+    /* Buffer for distances. To simplify the code, d_buf and l_buf have
+     * the same number of elements. To use different lengths, an extra flag
+     * array would be necessary.
+     */
+
+    ulg opt_len;        /* bit length of current block with optimal trees */
+    ulg static_len;     /* bit length of current block with static trees */
+    uInt matches;       /* number of string matches in current block */
+    int last_eob_len;   /* bit length of EOB code for last block */
+
+#ifdef DEBUG
+    ulg compressed_len; /* total bit length of compressed file mod 2^32 */
+    ulg bits_sent;      /* bit length of compressed data sent mod 2^32 */
+#endif
+
+    ush bi_buf;
+    /* Output buffer. bits are inserted starting at the bottom (least
+     * significant bits).
+     */
+    int bi_valid;
+    /* Number of valid bits in bi_buf.  All bits above the last valid bit
+     * are always zero.
+     */
+
+} FAR deflate_state;
+
+/* Output a byte on the stream.
+ * IN assertion: there is enough room in pending_buf.
+ */
+#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
+
+
+#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
+/* Minimum amount of lookahead, except at the end of the input file.
+ * See deflate.c for comments about the MIN_MATCH+1.
+ */
+
+#define MAX_DIST(s)  ((s)->w_size-MIN_LOOKAHEAD)
+/* In order to simplify the code, particularly on 16 bit machines, match
+ * distances are limited to MAX_DIST instead of WSIZE.
+ */
+
+        /* in trees.c */
+void _tr_init         OF((deflate_state *s));
+int  _tr_tally        OF((deflate_state *s, unsigned dist, unsigned lc));
+void _tr_flush_block  OF((deflate_state *s, charf *buf, ulg stored_len,
+                          int eof));
+void _tr_align        OF((deflate_state *s));
+void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
+                          int eof));
+
+#define d_code(dist) \
+   ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
+/* Mapping from a distance to a distance code. dist is the distance - 1 and
+ * must not have side effects. _dist_code[256] and _dist_code[257] are never
+ * used.
+ */
+
+#ifndef DEBUG
+/* Inline versions of _tr_tally for speed: */
+
+#if defined(GEN_TREES_H) || !defined(STDC)
+  extern uch _length_code[];
+  extern uch _dist_code[];
+#else
+  extern const uch _length_code[];
+  extern const uch _dist_code[];
+#endif
+
+# define _tr_tally_lit(s, c, flush) \
+  { uch cc = (c); \
+    s->d_buf[s->last_lit] = 0; \
+    s->l_buf[s->last_lit++] = cc; \
+    s->dyn_ltree[cc].Freq++; \
+    flush = (s->last_lit == s->lit_bufsize-1); \
+   }
+# define _tr_tally_dist(s, distance, length, flush) \
+  { uch len = (length); \
+    ush dist = (distance); \
+    s->d_buf[s->last_lit] = dist; \
+    s->l_buf[s->last_lit++] = len; \
+    dist--; \
+    s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
+    s->dyn_dtree[d_code(dist)].Freq++; \
+    flush = (s->last_lit == s->lit_bufsize-1); \
+  }
+#else
+# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
+# define _tr_tally_dist(s, distance, length, flush) \
+              flush = _tr_tally(s, distance, length)
+#endif
+
+#endif /* DEFLATE_H */
diff --git a/src/engine/external/zlib/gzio.c b/src/engine/external/zlib/gzio.c
new file mode 100644
index 00000000..7e90f492
--- /dev/null
+++ b/src/engine/external/zlib/gzio.c
@@ -0,0 +1,1026 @@
+/* gzio.c -- IO on .gz files
+ * Copyright (C) 1995-2005 Jean-loup Gailly.
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ *
+ * Compile this file with -DNO_GZCOMPRESS to avoid the compression code.
+ */
+
+/* @(#) $Id$ */
+
+#include <stdio.h>
+
+#include "zutil.h"
+
+#ifdef NO_DEFLATE       /* for compatibility with old definition */
+#  define NO_GZCOMPRESS
+#endif
+
+#ifndef NO_DUMMY_DECL
+struct internal_state {int dummy;}; /* for buggy compilers */
+#endif
+
+#ifndef Z_BUFSIZE
+#  ifdef MAXSEG_64K
+#    define Z_BUFSIZE 4096 /* minimize memory usage for 16-bit DOS */
+#  else
+#    define Z_BUFSIZE 16384
+#  endif
+#endif
+#ifndef Z_PRINTF_BUFSIZE
+#  define Z_PRINTF_BUFSIZE 4096
+#endif
+
+#ifdef __MVS__
+#  pragma map (fdopen , "\174\174FDOPEN")
+   FILE *fdopen(int, const char *);
+#endif
+
+#ifndef STDC
+extern voidp  malloc OF((uInt size));
+extern void   free   OF((voidpf ptr));
+#endif
+
+#define ALLOC(size) malloc(size)
+#define TRYFREE(p) {if (p) free(p);}
+
+static int const gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */
+
+/* gzip flag byte */
+#define ASCII_FLAG   0x01 /* bit 0 set: file probably ascii text */
+#define HEAD_CRC     0x02 /* bit 1 set: header CRC present */
+#define EXTRA_FIELD  0x04 /* bit 2 set: extra field present */
+#define ORIG_NAME    0x08 /* bit 3 set: original file name present */
+#define COMMENT      0x10 /* bit 4 set: file comment present */
+#define RESERVED     0xE0 /* bits 5..7: reserved */
+
+typedef struct gz_stream {
+    z_stream stream;
+    int      z_err;   /* error code for last stream operation */
+    int      z_eof;   /* set if end of input file */
+    FILE     *file;   /* .gz file */
+    Byte     *inbuf;  /* input buffer */
+    Byte     *outbuf; /* output buffer */
+    uLong    crc;     /* crc32 of uncompressed data */
+    char     *msg;    /* error message */
+    char     *path;   /* path name for debugging only */
+    int      transparent; /* 1 if input file is not a .gz file */
+    char     mode;    /* 'w' or 'r' */
+    z_off_t  start;   /* start of compressed data in file (header skipped) */
+    z_off_t  in;      /* bytes into deflate or inflate */
+    z_off_t  out;     /* bytes out of deflate or inflate */
+    int      back;    /* one character push-back */
+    int      last;    /* true if push-back is last character */
+} gz_stream;
+
+
+local gzFile gz_open      OF((const char *path, const char *mode, int  fd));
+local int do_flush        OF((gzFile file, int flush));
+local int    get_byte     OF((gz_stream *s));
+local void   check_header OF((gz_stream *s));
+local int    destroy      OF((gz_stream *s));
+local void   putLong      OF((FILE *file, uLong x));
+local uLong  getLong      OF((gz_stream *s));
+
+/* ===========================================================================
+     Opens a gzip (.gz) file for reading or writing. The mode parameter
+   is as in fopen ("rb" or "wb"). The file is given either by file descriptor
+   or path name (if fd == -1).
+     gz_open returns NULL if the file could not be opened or if there was
+   insufficient memory to allocate the (de)compression state; errno
+   can be checked to distinguish the two cases (if errno is zero, the
+   zlib error is Z_MEM_ERROR).
+*/
+local gzFile gz_open (path, mode, fd)
+    const char *path;
+    const char *mode;
+    int  fd;
+{
+    int err;
+    int level = Z_DEFAULT_COMPRESSION; /* compression level */
+    int strategy = Z_DEFAULT_STRATEGY; /* compression strategy */
+    char *p = (char*)mode;
+    gz_stream *s;
+    char fmode[80]; /* copy of mode, without the compression level */
+    char *m = fmode;
+
+    if (!path || !mode) return Z_NULL;
+
+    s = (gz_stream *)ALLOC(sizeof(gz_stream));
+    if (!s) return Z_NULL;
+
+    s->stream.zalloc = (alloc_func)0;
+    s->stream.zfree = (free_func)0;
+    s->stream.opaque = (voidpf)0;
+    s->stream.next_in = s->inbuf = Z_NULL;
+    s->stream.next_out = s->outbuf = Z_NULL;
+    s->stream.avail_in = s->stream.avail_out = 0;
+    s->file = NULL;
+    s->z_err = Z_OK;
+    s->z_eof = 0;
+    s->in = 0;
+    s->out = 0;
+    s->back = EOF;
+    s->crc = crc32(0L, Z_NULL, 0);
+    s->msg = NULL;
+    s->transparent = 0;
+
+    s->path = (char*)ALLOC(strlen(path)+1);
+    if (s->path == NULL) {
+        return destroy(s), (gzFile)Z_NULL;
+    }
+    strcpy(s->path, path); /* do this early for debugging */
+
+    s->mode = '\0';
+    do {
+        if (*p == 'r') s->mode = 'r';
+        if (*p == 'w' || *p == 'a') s->mode = 'w';
+        if (*p >= '0' && *p <= '9') {
+            level = *p - '0';
+        } else if (*p == 'f') {
+          strategy = Z_FILTERED;
+        } else if (*p == 'h') {
+          strategy = Z_HUFFMAN_ONLY;
+        } else if (*p == 'R') {
+          strategy = Z_RLE;
+        } else {
+            *m++ = *p; /* copy the mode */
+        }
+    } while (*p++ && m != fmode + sizeof(fmode));
+    if (s->mode == '\0') return destroy(s), (gzFile)Z_NULL;
+
+    if (s->mode == 'w') {
+#ifdef NO_GZCOMPRESS
+        err = Z_STREAM_ERROR;
+#else
+        err = deflateInit2(&(s->stream), level,
+                           Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, strategy);
+        /* windowBits is passed < 0 to suppress zlib header */
+
+        s->stream.next_out = s->outbuf = (Byte*)ALLOC(Z_BUFSIZE);
+#endif
+        if (err != Z_OK || s->outbuf == Z_NULL) {
+            return destroy(s), (gzFile)Z_NULL;
+        }
+    } else {
+        s->stream.next_in  = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE);
+
+        err = inflateInit2(&(s->stream), -MAX_WBITS);
+        /* windowBits is passed < 0 to tell that there is no zlib header.
+         * Note that in this case inflate *requires* an extra "dummy" byte
+         * after the compressed stream in order to complete decompression and
+         * return Z_STREAM_END. Here the gzip CRC32 ensures that 4 bytes are
+         * present after the compressed stream.
+         */
+        if (err != Z_OK || s->inbuf == Z_NULL) {
+            return destroy(s), (gzFile)Z_NULL;
+        }
+    }
+    s->stream.avail_out = Z_BUFSIZE;
+
+    errno = 0;
+    s->file = fd < 0 ? F_OPEN(path, fmode) : (FILE*)fdopen(fd, fmode);
+
+    if (s->file == NULL) {
+        return destroy(s), (gzFile)Z_NULL;
+    }
+    if (s->mode == 'w') {
+        /* Write a very simple .gz header:
+         */
+        fprintf(s->file, "%c%c%c%c%c%c%c%c%c%c", gz_magic[0], gz_magic[1],
+             Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/, OS_CODE);
+        s->start = 10L;
+        /* We use 10L instead of ftell(s->file) to because ftell causes an
+         * fflush on some systems. This version of the library doesn't use
+         * start anyway in write mode, so this initialization is not
+         * necessary.
+         */
+    } else {
+        check_header(s); /* skip the .gz header */
+        s->start = ftell(s->file) - s->stream.avail_in;
+    }
+
+    return (gzFile)s;
+}
+
+/* ===========================================================================
+     Opens a gzip (.gz) file for reading or writing.
+*/
+gzFile ZEXPORT gzopen (path, mode)
+    const char *path;
+    const char *mode;
+{
+    return gz_open (path, mode, -1);
+}
+
+/* ===========================================================================
+     Associate a gzFile with the file descriptor fd. fd is not dup'ed here
+   to mimic the behavio(u)r of fdopen.
+*/
+gzFile ZEXPORT gzdopen (fd, mode)
+    int fd;
+    const char *mode;
+{
+    char name[46];      /* allow for up to 128-bit integers */
+
+    if (fd < 0) return (gzFile)Z_NULL;
+    sprintf(name, "<fd:%d>", fd); /* for debugging */
+
+    return gz_open (name, mode, fd);
+}
+
+/* ===========================================================================
+ * Update the compression level and strategy
+ */
+int ZEXPORT gzsetparams (file, level, strategy)
+    gzFile file;
+    int level;
+    int strategy;
+{
+    gz_stream *s = (gz_stream*)file;
+
+    if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
+
+    /* Make room to allow flushing */
+    if (s->stream.avail_out == 0) {
+
+        s->stream.next_out = s->outbuf;
+        if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) {
+            s->z_err = Z_ERRNO;
+        }
+        s->stream.avail_out = Z_BUFSIZE;
+    }
+
+    return deflateParams (&(s->stream), level, strategy);
+}
+
+/* ===========================================================================
+     Read a byte from a gz_stream; update next_in and avail_in. Return EOF
+   for end of file.
+   IN assertion: the stream s has been sucessfully opened for reading.
+*/
+local int get_byte(s)
+    gz_stream *s;
+{
+    if (s->z_eof) return EOF;
+    if (s->stream.avail_in == 0) {
+        errno = 0;
+        s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file);
+        if (s->stream.avail_in == 0) {
+            s->z_eof = 1;
+            if (ferror(s->file)) s->z_err = Z_ERRNO;
+            return EOF;
+        }
+        s->stream.next_in = s->inbuf;
+    }
+    s->stream.avail_in--;
+    return *(s->stream.next_in)++;
+}
+
+/* ===========================================================================
+      Check the gzip header of a gz_stream opened for reading. Set the stream
+    mode to transparent if the gzip magic header is not present; set s->err
+    to Z_DATA_ERROR if the magic header is present but the rest of the header
+    is incorrect.
+    IN assertion: the stream s has already been created sucessfully;
+       s->stream.avail_in is zero for the first time, but may be non-zero
+       for concatenated .gz files.
+*/
+local void check_header(s)
+    gz_stream *s;
+{
+    int method; /* method byte */
+    int flags;  /* flags byte */
+    uInt len;
+    int c;
+
+    /* Assure two bytes in the buffer so we can peek ahead -- handle case
+       where first byte of header is at the end of the buffer after the last
+       gzip segment */
+    len = s->stream.avail_in;
+    if (len < 2) {
+        if (len) s->inbuf[0] = s->stream.next_in[0];
+        errno = 0;
+        len = (uInt)fread(s->inbuf + len, 1, Z_BUFSIZE >> len, s->file);
+        if (len == 0 && ferror(s->file)) s->z_err = Z_ERRNO;
+        s->stream.avail_in += len;
+        s->stream.next_in = s->inbuf;
+        if (s->stream.avail_in < 2) {
+            s->transparent = s->stream.avail_in;
+            return;
+        }
+    }
+
+    /* Peek ahead to check the gzip magic header */
+    if (s->stream.next_in[0] != gz_magic[0] ||
+        s->stream.next_in[1] != gz_magic[1]) {
+        s->transparent = 1;
+        return;
+    }
+    s->stream.avail_in -= 2;
+    s->stream.next_in += 2;
+
+    /* Check the rest of the gzip header */
+    method = get_byte(s);
+    flags = get_byte(s);
+    if (method != Z_DEFLATED || (flags & RESERVED) != 0) {
+        s->z_err = Z_DATA_ERROR;
+        return;
+    }
+
+    /* Discard time, xflags and OS code: */
+    for (len = 0; len < 6; len++) (void)get_byte(s);
+
+    if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */
+        len  =  (uInt)get_byte(s);
+        len += ((uInt)get_byte(s))<<8;
+        /* len is garbage if EOF but the loop below will quit anyway */
+        while (len-- != 0 && get_byte(s) != EOF) ;
+    }
+    if ((flags & ORIG_NAME) != 0) { /* skip the original file name */
+        while ((c = get_byte(s)) != 0 && c != EOF) ;
+    }
+    if ((flags & COMMENT) != 0) {   /* skip the .gz file comment */
+        while ((c = get_byte(s)) != 0 && c != EOF) ;
+    }
+    if ((flags & HEAD_CRC) != 0) {  /* skip the header crc */
+        for (len = 0; len < 2; len++) (void)get_byte(s);
+    }
+    s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK;
+}
+
+ /* ===========================================================================
+ * Cleanup then free the given gz_stream. Return a zlib error code.
+   Try freeing in the reverse order of allocations.
+ */
+local int destroy (s)
+    gz_stream *s;
+{
+    int err = Z_OK;
+
+    if (!s) return Z_STREAM_ERROR;
+
+    TRYFREE(s->msg);
+
+    if (s->stream.state != NULL) {
+        if (s->mode == 'w') {
+#ifdef NO_GZCOMPRESS
+            err = Z_STREAM_ERROR;
+#else
+            err = deflateEnd(&(s->stream));
+#endif
+        } else if (s->mode == 'r') {
+            err = inflateEnd(&(s->stream));
+        }
+    }
+    if (s->file != NULL && fclose(s->file)) {
+#ifdef ESPIPE
+        if (errno != ESPIPE) /* fclose is broken for pipes in HP/UX */
+#endif
+            err = Z_ERRNO;
+    }
+    if (s->z_err < 0) err = s->z_err;
+
+    TRYFREE(s->inbuf);
+    TRYFREE(s->outbuf);
+    TRYFREE(s->path);
+    TRYFREE(s);
+    return err;
+}
+
+/* ===========================================================================
+     Reads the given number of uncompressed bytes from the compressed file.
+   gzread returns the number of bytes actually read (0 for end of file).
+*/
+int ZEXPORT gzread (file, buf, len)
+    gzFile file;
+    voidp buf;
+    unsigned len;
+{
+    gz_stream *s = (gz_stream*)file;
+    Bytef *start = (Bytef*)buf; /* starting point for crc computation */
+    Byte  *next_out; /* == stream.next_out but not forced far (for MSDOS) */
+
+    if (s == NULL || s->mode != 'r') return Z_STREAM_ERROR;
+
+    if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO) return -1;
+    if (s->z_err == Z_STREAM_END) return 0;  /* EOF */
+
+    next_out = (Byte*)buf;
+    s->stream.next_out = (Bytef*)buf;
+    s->stream.avail_out = len;
+
+    if (s->stream.avail_out && s->back != EOF) {
+        *next_out++ = s->back;
+        s->stream.next_out++;
+        s->stream.avail_out--;
+        s->back = EOF;
+        s->out++;
+        start++;
+        if (s->last) {
+            s->z_err = Z_STREAM_END;
+            return 1;
+        }
+    }
+
+    while (s->stream.avail_out != 0) {
+
+        if (s->transparent) {
+            /* Copy first the lookahead bytes: */
+            uInt n = s->stream.avail_in;
+            if (n > s->stream.avail_out) n = s->stream.avail_out;
+            if (n > 0) {
+                zmemcpy(s->stream.next_out, s->stream.next_in, n);
+                next_out += n;
+                s->stream.next_out = next_out;
+                s->stream.next_in   += n;
+                s->stream.avail_out -= n;
+                s->stream.avail_in  -= n;
+            }
+            if (s->stream.avail_out > 0) {
+                s->stream.avail_out -=
+                    (uInt)fread(next_out, 1, s->stream.avail_out, s->file);
+            }
+            len -= s->stream.avail_out;
+            s->in  += len;
+            s->out += len;
+            if (len == 0) s->z_eof = 1;
+            return (int)len;
+        }
+        if (s->stream.avail_in == 0 && !s->z_eof) {
+
+            errno = 0;
+            s->stream.avail_in = (uInt)fread(s->inbuf, 1, Z_BUFSIZE, s->file);
+            if (s->stream.avail_in == 0) {
+                s->z_eof = 1;
+                if (ferror(s->file)) {
+                    s->z_err = Z_ERRNO;
+                    break;
+                }
+            }
+            s->stream.next_in = s->inbuf;
+        }
+        s->in += s->stream.avail_in;
+        s->out += s->stream.avail_out;
+        s->z_err = inflate(&(s->stream), Z_NO_FLUSH);
+        s->in -= s->stream.avail_in;
+        s->out -= s->stream.avail_out;
+
+        if (s->z_err == Z_STREAM_END) {
+            /* Check CRC and original size */
+            s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
+            start = s->stream.next_out;
+
+            if (getLong(s) != s->crc) {
+                s->z_err = Z_DATA_ERROR;
+            } else {
+                (void)getLong(s);
+                /* The uncompressed length returned by above getlong() may be
+                 * different from s->out in case of concatenated .gz files.
+                 * Check for such files:
+                 */
+                check_header(s);
+                if (s->z_err == Z_OK) {
+                    inflateReset(&(s->stream));
+                    s->crc = crc32(0L, Z_NULL, 0);
+                }
+            }
+        }
+        if (s->z_err != Z_OK || s->z_eof) break;
+    }
+    s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
+
+    if (len == s->stream.avail_out &&
+        (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO))
+        return -1;
+    return (int)(len - s->stream.avail_out);
+}
+
+
+/* ===========================================================================
+      Reads one byte from the compressed file. gzgetc returns this byte
+   or -1 in case of end of file or error.
+*/
+int ZEXPORT gzgetc(file)
+    gzFile file;
+{
+    unsigned char c;
+
+    return gzread(file, &c, 1) == 1 ? c : -1;
+}
+
+
+/* ===========================================================================
+      Push one byte back onto the stream.
+*/
+int ZEXPORT gzungetc(c, file)
+    int c;
+    gzFile file;
+{
+    gz_stream *s = (gz_stream*)file;
+
+    if (s == NULL || s->mode != 'r' || c == EOF || s->back != EOF) return EOF;
+    s->back = c;
+    s->out--;
+    s->last = (s->z_err == Z_STREAM_END);
+    if (s->last) s->z_err = Z_OK;
+    s->z_eof = 0;
+    return c;
+}
+
+
+/* ===========================================================================
+      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.  The string is then terminated
+   with a null character.
+      gzgets returns buf, or Z_NULL in case of error.
+
+      The current implementation is not optimized at all.
+*/
+char * ZEXPORT gzgets(file, buf, len)
+    gzFile file;
+    char *buf;
+    int len;
+{
+    char *b = buf;
+    if (buf == Z_NULL || len <= 0) return Z_NULL;
+
+    while (--len > 0 && gzread(file, buf, 1) == 1 && *buf++ != '\n') ;
+    *buf = '\0';
+    return b == buf && len > 0 ? Z_NULL : b;
+}
+
+
+#ifndef NO_GZCOMPRESS
+/* ===========================================================================
+     Writes the given number of uncompressed bytes into the compressed file.
+   gzwrite returns the number of bytes actually written (0 in case of error).
+*/
+int ZEXPORT gzwrite (file, buf, len)
+    gzFile file;
+    voidpc buf;
+    unsigned len;
+{
+    gz_stream *s = (gz_stream*)file;
+
+    if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
+
+    s->stream.next_in = (Bytef*)buf;
+    s->stream.avail_in = len;
+
+    while (s->stream.avail_in != 0) {
+
+        if (s->stream.avail_out == 0) {
+
+            s->stream.next_out = s->outbuf;
+            if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) {
+                s->z_err = Z_ERRNO;
+                break;
+            }
+            s->stream.avail_out = Z_BUFSIZE;
+        }
+        s->in += s->stream.avail_in;
+        s->out += s->stream.avail_out;
+        s->z_err = deflate(&(s->stream), Z_NO_FLUSH);
+        s->in -= s->stream.avail_in;
+        s->out -= s->stream.avail_out;
+        if (s->z_err != Z_OK) break;
+    }
+    s->crc = crc32(s->crc, (const Bytef *)buf, len);
+
+    return (int)(len - s->stream.avail_in);
+}
+
+
+/* ===========================================================================
+     Converts, formats, and writes the args to the compressed file under
+   control of the format string, as in fprintf. gzprintf returns the number of
+   uncompressed bytes actually written (0 in case of error).
+*/
+#ifdef STDC
+#include <stdarg.h>
+
+int ZEXPORTVA gzprintf (gzFile file, const char *format, /* args */ ...)
+{
+    char buf[Z_PRINTF_BUFSIZE];
+    va_list va;
+    int len;
+
+    buf[sizeof(buf) - 1] = 0;
+    va_start(va, format);
+#ifdef NO_vsnprintf
+#  ifdef HAS_vsprintf_void
+    (void)vsprintf(buf, format, va);
+    va_end(va);
+    for (len = 0; len < sizeof(buf); len++)
+        if (buf[len] == 0) break;
+#  else
+    len = vsprintf(buf, format, va);
+    va_end(va);
+#  endif
+#else
+#  ifdef HAS_vsnprintf_void
+    (void)vsnprintf(buf, sizeof(buf), format, va);
+    va_end(va);
+    len = strlen(buf);
+#  else
+    len = vsnprintf(buf, sizeof(buf), format, va);
+    va_end(va);
+#  endif
+#endif
+    if (len <= 0 || len >= (int)sizeof(buf) || buf[sizeof(buf) - 1] != 0)
+        return 0;
+    return gzwrite(file, buf, (unsigned)len);
+}
+#else /* not ANSI C */
+
+int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
+                       a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)
+    gzFile file;
+    const char *format;
+    int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
+        a11, a12, a13, a14, a15, a16, a17, a18, a19, a20;
+{
+    char buf[Z_PRINTF_BUFSIZE];
+    int len;
+
+    buf[sizeof(buf) - 1] = 0;
+#ifdef NO_snprintf
+#  ifdef HAS_sprintf_void
+    sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8,
+            a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
+    for (len = 0; len < sizeof(buf); len++)
+        if (buf[len] == 0) break;
+#  else
+    len = sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8,
+                a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
+#  endif
+#else
+#  ifdef HAS_snprintf_void
+    snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8,
+             a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
+    len = strlen(buf);
+#  else
+    len = snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8,
+                 a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
+#  endif
+#endif
+    if (len <= 0 || len >= sizeof(buf) || buf[sizeof(buf) - 1] != 0)
+        return 0;
+    return gzwrite(file, buf, len);
+}
+#endif
+
+/* ===========================================================================
+      Writes c, converted to an unsigned char, into the compressed file.
+   gzputc returns the value that was written, or -1 in case of error.
+*/
+int ZEXPORT gzputc(file, c)
+    gzFile file;
+    int c;
+{
+    unsigned char cc = (unsigned char) c; /* required for big endian systems */
+
+    return gzwrite(file, &cc, 1) == 1 ? (int)cc : -1;
+}
+
+
+/* ===========================================================================
+      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.
+*/
+int ZEXPORT gzputs(file, s)
+    gzFile file;
+    const char *s;
+{
+    return gzwrite(file, (char*)s, (unsigned)strlen(s));
+}
+
+
+/* ===========================================================================
+     Flushes all pending output into the compressed file. The parameter
+   flush is as in the deflate() function.
+*/
+local int do_flush (file, flush)
+    gzFile file;
+    int flush;
+{
+    uInt len;
+    int done = 0;
+    gz_stream *s = (gz_stream*)file;
+
+    if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
+
+    s->stream.avail_in = 0; /* should be zero already anyway */
+
+    for (;;) {
+        len = Z_BUFSIZE - s->stream.avail_out;
+
+        if (len != 0) {
+            if ((uInt)fwrite(s->outbuf, 1, len, s->file) != len) {
+                s->z_err = Z_ERRNO;
+                return Z_ERRNO;
+            }
+            s->stream.next_out = s->outbuf;
+            s->stream.avail_out = Z_BUFSIZE;
+        }
+        if (done) break;
+        s->out += s->stream.avail_out;
+        s->z_err = deflate(&(s->stream), flush);
+        s->out -= s->stream.avail_out;
+
+        /* Ignore the second of two consecutive flushes: */
+        if (len == 0 && s->z_err == Z_BUF_ERROR) s->z_err = Z_OK;
+
+        /* deflate has finished flushing only when it hasn't used up
+         * all the available space in the output buffer:
+         */
+        done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END);
+
+        if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break;
+    }
+    return  s->z_err == Z_STREAM_END ? Z_OK : s->z_err;
+}
+
+int ZEXPORT gzflush (file, flush)
+     gzFile file;
+     int flush;
+{
+    gz_stream *s = (gz_stream*)file;
+    int err = do_flush (file, flush);
+
+    if (err) return err;
+    fflush(s->file);
+    return  s->z_err == Z_STREAM_END ? Z_OK : s->z_err;
+}
+#endif /* NO_GZCOMPRESS */
+
+/* ===========================================================================
+      Sets the starting position for the next gzread or gzwrite on the given
+   compressed file. The offset represents a number of bytes in the
+      gzseek returns the resulting offset location as measured in bytes from
+   the beginning of the uncompressed stream, or -1 in case of error.
+      SEEK_END is not implemented, returns error.
+      In this version of the library, gzseek can be extremely slow.
+*/
+z_off_t ZEXPORT gzseek (file, offset, whence)
+    gzFile file;
+    z_off_t offset;
+    int whence;
+{
+    gz_stream *s = (gz_stream*)file;
+
+    if (s == NULL || whence == SEEK_END ||
+        s->z_err == Z_ERRNO || s->z_err == Z_DATA_ERROR) {
+        return -1L;
+    }
+
+    if (s->mode == 'w') {
+#ifdef NO_GZCOMPRESS
+        return -1L;
+#else
+        if (whence == SEEK_SET) {
+            offset -= s->in;
+        }
+        if (offset < 0) return -1L;
+
+        /* At this point, offset is the number of zero bytes to write. */
+        if (s->inbuf == Z_NULL) {
+            s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); /* for seeking */
+            if (s->inbuf == Z_NULL) return -1L;
+            zmemzero(s->inbuf, Z_BUFSIZE);
+        }
+        while (offset > 0)  {
+            uInt size = Z_BUFSIZE;
+            if (offset < Z_BUFSIZE) size = (uInt)offset;
+
+            size = gzwrite(file, s->inbuf, size);
+            if (size == 0) return -1L;
+
+            offset -= size;
+        }
+        return s->in;
+#endif
+    }
+    /* Rest of function is for reading only */
+
+    /* compute absolute position */
+    if (whence == SEEK_CUR) {
+        offset += s->out;
+    }
+    if (offset < 0) return -1L;
+
+    if (s->transparent) {
+        /* map to fseek */
+        s->back = EOF;
+        s->stream.avail_in = 0;
+        s->stream.next_in = s->inbuf;
+        if (fseek(s->file, offset, SEEK_SET) < 0) return -1L;
+
+        s->in = s->out = offset;
+        return offset;
+    }
+
+    /* For a negative seek, rewind and use positive seek */
+    if (offset >= s->out) {
+        offset -= s->out;
+    } else if (gzrewind(file) < 0) {
+        return -1L;
+    }
+    /* offset is now the number of bytes to skip. */
+
+    if (offset != 0 && s->outbuf == Z_NULL) {
+        s->outbuf = (Byte*)ALLOC(Z_BUFSIZE);
+        if (s->outbuf == Z_NULL) return -1L;
+    }
+    if (offset && s->back != EOF) {
+        s->back = EOF;
+        s->out++;
+        offset--;
+        if (s->last) s->z_err = Z_STREAM_END;
+    }
+    while (offset > 0)  {
+        int size = Z_BUFSIZE;
+        if (offset < Z_BUFSIZE) size = (int)offset;
+
+        size = gzread(file, s->outbuf, (uInt)size);
+        if (size <= 0) return -1L;
+        offset -= size;
+    }
+    return s->out;
+}
+
+/* ===========================================================================
+     Rewinds input file.
+*/
+int ZEXPORT gzrewind (file)
+    gzFile file;
+{
+    gz_stream *s = (gz_stream*)file;
+
+    if (s == NULL || s->mode != 'r') return -1;
+
+    s->z_err = Z_OK;
+    s->z_eof = 0;
+    s->back = EOF;
+    s->stream.avail_in = 0;
+    s->stream.next_in = s->inbuf;
+    s->crc = crc32(0L, Z_NULL, 0);
+    if (!s->transparent) (void)inflateReset(&s->stream);
+    s->in = 0;
+    s->out = 0;
+    return fseek(s->file, s->start, SEEK_SET);
+}
+
+/* ===========================================================================
+     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.
+*/
+z_off_t ZEXPORT gztell (file)
+    gzFile file;
+{
+    return gzseek(file, 0L, SEEK_CUR);
+}
+
+/* ===========================================================================
+     Returns 1 when EOF has previously been detected reading the given
+   input stream, otherwise zero.
+*/
+int ZEXPORT gzeof (file)
+    gzFile file;
+{
+    gz_stream *s = (gz_stream*)file;
+
+    /* With concatenated compressed files that can have embedded
+     * crc trailers, z_eof is no longer the only/best indicator of EOF
+     * on a gz_stream. Handle end-of-stream error explicitly here.
+     */
+    if (s == NULL || s->mode != 'r') return 0;
+    if (s->z_eof) return 1;
+    return s->z_err == Z_STREAM_END;
+}
+
+/* ===========================================================================
+     Returns 1 if reading and doing so transparently, otherwise zero.
+*/
+int ZEXPORT gzdirect (file)
+    gzFile file;
+{
+    gz_stream *s = (gz_stream*)file;
+
+    if (s == NULL || s->mode != 'r') return 0;
+    return s->transparent;
+}
+
+/* ===========================================================================
+   Outputs a long in LSB order to the given file
+*/
+local void putLong (file, x)
+    FILE *file;
+    uLong x;
+{
+    int n;
+    for (n = 0; n < 4; n++) {
+        fputc((int)(x & 0xff), file);
+        x >>= 8;
+    }
+}
+
+/* ===========================================================================
+   Reads a long in LSB order from the given gz_stream. Sets z_err in case
+   of error.
+*/
+local uLong getLong (s)
+    gz_stream *s;
+{
+    uLong x = (uLong)get_byte(s);
+    int c;
+
+    x += ((uLong)get_byte(s))<<8;
+    x += ((uLong)get_byte(s))<<16;
+    c = get_byte(s);
+    if (c == EOF) s->z_err = Z_DATA_ERROR;
+    x += ((uLong)c)<<24;
+    return x;
+}
+
+/* ===========================================================================
+     Flushes all pending output if necessary, closes the compressed file
+   and deallocates all the (de)compression state.
+*/
+int ZEXPORT gzclose (file)
+    gzFile file;
+{
+    gz_stream *s = (gz_stream*)file;
+
+    if (s == NULL) return Z_STREAM_ERROR;
+
+    if (s->mode == 'w') {
+#ifdef NO_GZCOMPRESS
+        return Z_STREAM_ERROR;
+#else
+        if (do_flush (file, Z_FINISH) != Z_OK)
+            return destroy((gz_stream*)file);
+
+        putLong (s->file, s->crc);
+        putLong (s->file, (uLong)(s->in & 0xffffffff));
+#endif
+    }
+    return destroy((gz_stream*)file);
+}
+
+#ifdef STDC
+#  define zstrerror(errnum) strerror(errnum)
+#else
+#  define zstrerror(errnum) ""
+#endif
+
+/* ===========================================================================
+     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.
+*/
+const char * ZEXPORT gzerror (file, errnum)
+    gzFile file;
+    int *errnum;
+{
+    char *m;
+    gz_stream *s = (gz_stream*)file;
+
+    if (s == NULL) {
+        *errnum = Z_STREAM_ERROR;
+        return (const char*)ERR_MSG(Z_STREAM_ERROR);
+    }
+    *errnum = s->z_err;
+    if (*errnum == Z_OK) return (const char*)"";
+
+    m = (char*)(*errnum == Z_ERRNO ? zstrerror(errno) : s->stream.msg);
+
+    if (m == NULL || *m == '\0') m = (char*)ERR_MSG(s->z_err);
+
+    TRYFREE(s->msg);
+    s->msg = (char*)ALLOC(strlen(s->path) + strlen(m) + 3);
+    if (s->msg == Z_NULL) return (const char*)ERR_MSG(Z_MEM_ERROR);
+    strcpy(s->msg, s->path);
+    strcat(s->msg, ": ");
+    strcat(s->msg, m);
+    return (const char*)s->msg;
+}
+
+/* ===========================================================================
+     Clear the error and end-of-file flags, and do the same for the real file.
+*/
+void ZEXPORT gzclearerr (file)
+    gzFile file;
+{
+    gz_stream *s = (gz_stream*)file;
+
+    if (s == NULL) return;
+    if (s->z_err != Z_STREAM_END) s->z_err = Z_OK;
+    s->z_eof = 0;
+    clearerr(s->file);
+}
diff --git a/src/engine/external/zlib/infback.c b/src/engine/external/zlib/infback.c
new file mode 100644
index 00000000..455dbc9e
--- /dev/null
+++ b/src/engine/external/zlib/infback.c
@@ -0,0 +1,623 @@
+/* infback.c -- inflate using a call-back interface
+ * Copyright (C) 1995-2005 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/*
+   This code is largely copied from inflate.c.  Normally either infback.o or
+   inflate.o would be linked into an application--not both.  The interface
+   with inffast.c is retained so that optimized assembler-coded versions of
+   inflate_fast() can be used with either inflate.c or infback.c.
+ */
+
+#include "zutil.h"
+#include "inftrees.h"
+#include "inflate.h"
+#include "inffast.h"
+
+/* function prototypes */
+local void fixedtables OF((struct inflate_state FAR *state));
+
+/*
+   strm provides memory allocation functions in zalloc and zfree, or
+   Z_NULL to use the library memory allocation functions.
+
+   windowBits is in the range 8..15, and window is a user-supplied
+   window and output buffer that is 2**windowBits bytes.
+ */
+int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size)
+z_streamp strm;
+int windowBits;
+unsigned char FAR *window;
+const char *version;
+int stream_size;
+{
+    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 || window == Z_NULL ||
+        windowBits < 8 || windowBits > 15)
+        return Z_STREAM_ERROR;
+    strm->msg = Z_NULL;                 /* in case we return an error */
+    if (strm->zalloc == (alloc_func)0) {
+        strm->zalloc = zcalloc;
+        strm->opaque = (voidpf)0;
+    }
+    if (strm->zfree == (free_func)0) strm->zfree = zcfree;
+    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->dmax = 32768U;
+    state->wbits = windowBits;
+    state->wsize = 1U << windowBits;
+    state->window = window;
+    state->write = 0;
+    state->whave = 0;
+    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;
+}
+
+/* Macros for inflateBack(): */
+
+/* Load returned state from inflate_fast() */
+#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)
+
+/* Set state from registers for inflate_fast() */
+#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)
+
+/* Assure that some input is available.  If input is requested, but denied,
+   then return a Z_BUF_ERROR from inflateBack(). */
+#define PULL() \
+    do { \
+        if (have == 0) { \
+            have = in(in_desc, &next); \
+            if (have == 0) { \
+                next = Z_NULL; \
+                ret = Z_BUF_ERROR; \
+                goto inf_leave; \
+            } \
+        } \
+    } while (0)
+
+/* Get a byte of input into the bit accumulator, or return from inflateBack()
+   with an error if there is no input available. */
+#define PULLBYTE() \
+    do { \
+        PULL(); \
+        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 inflateBack() with
+   an error. */
+#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)
+
+/* Assure that some output space is available, by writing out the window
+   if it's full.  If the write fails, return from inflateBack() with a
+   Z_BUF_ERROR. */
+#define ROOM() \
+    do { \
+        if (left == 0) { \
+            put = state->window; \
+            left = state->wsize; \
+            state->whave = left; \
+            if (out(out_desc, put, left)) { \
+                ret = Z_BUF_ERROR; \
+                goto inf_leave; \
+            } \
+        } \
+    } while (0)
+
+/*
+   strm provides the memory allocation functions and window buffer on input,
+   and provides information on the unused input on return.  For Z_DATA_ERROR
+   returns, strm will also provide an error message.
+
+   in() and out() are the call-back input and output functions.  When
+   inflateBack() needs more input, it calls in().  When inflateBack() has
+   filled the window with output, or when it completes with data in the
+   window, it calls out() to write out the data.  The application must not
+   change the provided input until in() is called again or inflateBack()
+   returns.  The application must not change the window/output buffer until
+   inflateBack() returns.
+
+   in() and out() are called with a descriptor parameter provided in the
+   inflateBack() call.  This parameter can be a structure that provides the
+   information required to do the read or write, as well as accumulated
+   information on the input and output such as totals and check values.
+
+   in() should return zero on failure.  out() should return non-zero on
+   failure.  If either in() or out() fails, than inflateBack() returns a
+   Z_BUF_ERROR.  strm->next_in can be checked for Z_NULL to see whether it
+   was in() or out() that caused in the error.  Otherwise,  inflateBack()
+   returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format
+   error, or Z_MEM_ERROR if it could not allocate memory for the state.
+   inflateBack() can also return Z_STREAM_ERROR if the input parameters
+   are not correct, i.e. strm is Z_NULL or the state was not initialized.
+ */
+int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc)
+z_streamp strm;
+in_func in;
+void FAR *in_desc;
+out_func out;
+void FAR *out_desc;
+{
+    struct inflate_state FAR *state;
+    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 copy;              /* number of stored or match bytes to copy */
+    unsigned char FAR *from;    /* where to copy match bytes from */
+    code this;                  /* current decoding table entry */
+    code last;                  /* parent table entry */
+    unsigned len;               /* length to copy for repeats, bits to drop */
+    int ret;                    /* return code */
+    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};
+
+    /* Check that the strm exists and that the state was initialized */
+    if (strm == Z_NULL || strm->state == Z_NULL)
+        return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+
+    /* Reset the state */
+    strm->msg = Z_NULL;
+    state->mode = TYPE;
+    state->last = 0;
+    state->whave = 0;
+    next = strm->next_in;
+    have = next != Z_NULL ? strm->avail_in : 0;
+    hold = 0;
+    bits = 0;
+    put = state->window;
+    left = state->wsize;
+
+    /* Inflate until end of block marked as last */
+    for (;;)
+        switch (state->mode) {
+        case TYPE:
+            /* determine and dispatch block type */
+            if (state->last) {
+                BYTEBITS();
+                state->mode = DONE;
+                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 */
+                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:
+            /* get and verify stored block length */
+            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();
+
+            /* copy stored block from input to output */
+            while (state->length != 0) {
+                copy = state->length;
+                PULL();
+                ROOM();
+                if (copy > have) copy = have;
+                if (copy > left) copy = left;
+                zmemcpy(put, next, copy);
+                have -= copy;
+                next += copy;
+                left -= copy;
+                put += copy;
+                state->length -= copy;
+            }
+            Tracev((stderr, "inflate:       stored end\n"));
+            state->mode = TYPE;
+            break;
+
+        case TABLE:
+            /* get dynamic table entries descriptor */
+            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"));
+
+            /* get code length code lengths (not a typo) */
+            state->have = 0;
+            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 = (code const 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"));
+
+            /* get length and distance code code lengths */
+            state->have = 0;
+            while (state->have < state->nlen + state->ndist) {
+                for (;;) {
+                    this = state->lencode[BITS(state->lenbits)];
+                    if ((unsigned)(this.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                if (this.val < 16) {
+                    NEEDBITS(this.bits);
+                    DROPBITS(this.bits);
+                    state->lens[state->have++] = this.val;
+                }
+                else {
+                    if (this.val == 16) {
+                        NEEDBITS(this.bits + 2);
+                        DROPBITS(this.bits);
+                        if (state->have == 0) {
+                            strm->msg = (char *)"invalid bit length repeat";
+                            state->mode = BAD;
+                            break;
+                        }
+                        len = (unsigned)(state->lens[state->have - 1]);
+                        copy = 3 + BITS(2);
+                        DROPBITS(2);
+                    }
+                    else if (this.val == 17) {
+                        NEEDBITS(this.bits + 3);
+                        DROPBITS(this.bits);
+                        len = 0;
+                        copy = 3 + BITS(3);
+                        DROPBITS(3);
+                    }
+                    else {
+                        NEEDBITS(this.bits + 7);
+                        DROPBITS(this.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;
+
+            /* build code tables */
+            state->next = state->codes;
+            state->lencode = (code const 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 = (code const 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;
+
+        case LEN:
+            /* use inflate_fast() if we have enough input and output */
+            if (have >= 6 && left >= 258) {
+                RESTORE();
+                if (state->whave < state->wsize)
+                    state->whave = state->wsize - left;
+                inflate_fast(strm, state->wsize);
+                LOAD();
+                break;
+            }
+
+            /* get a literal, length, or end-of-block code */
+            for (;;) {
+                this = state->lencode[BITS(state->lenbits)];
+                if ((unsigned)(this.bits) <= bits) break;
+                PULLBYTE();
+            }
+            if (this.op && (this.op & 0xf0) == 0) {
+                last = this;
+                for (;;) {
+                    this = state->lencode[last.val +
+                            (BITS(last.bits + last.op) >> last.bits)];
+                    if ((unsigned)(last.bits + this.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                DROPBITS(last.bits);
+            }
+            DROPBITS(this.bits);
+            state->length = (unsigned)this.val;
+
+            /* process literal */
+            if (this.op == 0) {
+                Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
+                        "inflate:         literal '%c'\n" :
+                        "inflate:         literal 0x%02x\n", this.val));
+                ROOM();
+                *put++ = (unsigned char)(state->length);
+                left--;
+                state->mode = LEN;
+                break;
+            }
+
+            /* process end of block */
+            if (this.op & 32) {
+                Tracevv((stderr, "inflate:         end of block\n"));
+                state->mode = TYPE;
+                break;
+            }
+
+            /* invalid code */
+            if (this.op & 64) {
+                strm->msg = (char *)"invalid literal/length code";
+                state->mode = BAD;
+                break;
+            }
+
+            /* length code -- get extra bits, if any */
+            state->extra = (unsigned)(this.op) & 15;
+            if (state->extra != 0) {
+                NEEDBITS(state->extra);
+                state->length += BITS(state->extra);
+                DROPBITS(state->extra);
+            }
+            Tracevv((stderr, "inflate:         length %u\n", state->length));
+
+            /* get distance code */
+            for (;;) {
+                this = state->distcode[BITS(state->distbits)];
+                if ((unsigned)(this.bits) <= bits) break;
+                PULLBYTE();
+            }
+            if ((this.op & 0xf0) == 0) {
+                last = this;
+                for (;;) {
+                    this = state->distcode[last.val +
+                            (BITS(last.bits + last.op) >> last.bits)];
+                    if ((unsigned)(last.bits + this.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                DROPBITS(last.bits);
+            }
+            DROPBITS(this.bits);
+            if (this.op & 64) {
+                strm->msg = (char *)"invalid distance code";
+                state->mode = BAD;
+                break;
+            }
+            state->offset = (unsigned)this.val;
+
+            /* get distance extra bits, if any */
+            state->extra = (unsigned)(this.op) & 15;
+            if (state->extra != 0) {
+                NEEDBITS(state->extra);
+                state->offset += BITS(state->extra);
+                DROPBITS(state->extra);
+            }
+            if (state->offset > state->wsize - (state->whave < state->wsize ?
+                                                left : 0)) {
+                strm->msg = (char *)"invalid distance too far back";
+                state->mode = BAD;
+                break;
+            }
+            Tracevv((stderr, "inflate:         distance %u\n", state->offset));
+
+            /* copy match from window to output */
+            do {
+                ROOM();
+                copy = state->wsize - state->offset;
+                if (copy < left) {
+                    from = put + copy;
+                    copy = left - copy;
+                }
+                else {
+                    from = put - state->offset;
+                    copy = left;
+                }
+                if (copy > state->length) copy = state->length;
+                state->length -= copy;
+                left -= copy;
+                do {
+                    *put++ = *from++;
+                } while (--copy);
+            } while (state->length != 0);
+            break;
+
+        case DONE:
+            /* inflate stream terminated properly -- write leftover output */
+            ret = Z_STREAM_END;
+            if (left < state->wsize) {
+                if (out(out_desc, state->window, state->wsize - left))
+                    ret = Z_BUF_ERROR;
+            }
+            goto inf_leave;
+
+        case BAD:
+            ret = Z_DATA_ERROR;
+            goto inf_leave;
+
+        default:                /* can't happen, but makes compilers happy */
+            ret = Z_STREAM_ERROR;
+            goto inf_leave;
+        }
+
+    /* Return unused input */
+  inf_leave:
+    strm->next_in = next;
+    strm->avail_in = have;
+    return ret;
+}
+
+int ZEXPORT inflateBackEnd(strm)
+z_streamp strm;
+{
+    if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
+        return Z_STREAM_ERROR;
+    ZFREE(strm, strm->state);
+    strm->state = Z_NULL;
+    Tracev((stderr, "inflate: end\n"));
+    return Z_OK;
+}
diff --git a/src/engine/external/zlib/inffast.c b/src/engine/external/zlib/inffast.c
new file mode 100644
index 00000000..bbee92ed
--- /dev/null
+++ b/src/engine/external/zlib/inffast.c
@@ -0,0 +1,318 @@
+/* inffast.c -- fast decoding
+ * Copyright (C) 1995-2004 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"
+
+#ifndef ASMINF
+
+/* Allow machine dependent optimization for post-increment or pre-increment.
+   Based on testing to date,
+   Pre-increment preferred for:
+   - PowerPC G3 (Adler)
+   - MIPS R5000 (Randers-Pehrson)
+   Post-increment preferred for:
+   - none
+   No measurable difference:
+   - Pentium III (Anderson)
+   - M68060 (Nikl)
+ */
+#ifdef POSTINC
+#  define OFF 0
+#  define PUP(a) *(a)++
+#else
+#  define OFF 1
+#  define PUP(a) *++(a)
+#endif
+
+/*
+   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 inflate_fast(strm, start)
+z_streamp strm;
+unsigned start;         /* inflate()'s starting value for strm->avail_out */
+{
+    struct inflate_state FAR *state;
+    unsigned char FAR *in;      /* local strm->next_in */
+    unsigned char FAR *last;    /* while in < last, enough input available */
+    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 write;             /* 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 this;                  /* 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 - OFF;
+    last = in + (strm->avail_in - 5);
+    out = strm->next_out - OFF;
+    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;
+    write = state->write;
+    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)(PUP(in)) << bits;
+            bits += 8;
+            hold += (unsigned long)(PUP(in)) << bits;
+            bits += 8;
+        }
+        this = lcode[hold & lmask];
+      dolen:
+        op = (unsigned)(this.bits);
+        hold >>= op;
+        bits -= op;
+        op = (unsigned)(this.op);
+        if (op == 0) {                          /* literal */
+            Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
+                    "inflate:         literal '%c'\n" :
+                    "inflate:         literal 0x%02x\n", this.val));
+            PUP(out) = (unsigned char)(this.val);
+        }
+        else if (op & 16) {                     /* length base */
+            len = (unsigned)(this.val);
+            op &= 15;                           /* number of extra bits */
+            if (op) {
+                if (bits < op) {
+                    hold += (unsigned long)(PUP(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)(PUP(in)) << bits;
+                bits += 8;
+                hold += (unsigned long)(PUP(in)) << bits;
+                bits += 8;
+            }
+            this = dcode[hold & dmask];
+          dodist:
+            op = (unsigned)(this.bits);
+            hold >>= op;
+            bits -= op;
+            op = (unsigned)(this.op);
+            if (op & 16) {                      /* distance base */
+                dist = (unsigned)(this.val);
+                op &= 15;                       /* number of extra bits */
+                if (bits < op) {
+                    hold += (unsigned long)(PUP(in)) << bits;
+                    bits += 8;
+                    if (bits < op) {
+                        hold += (unsigned long)(PUP(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) {
+                        strm->msg = (char *)"invalid distance too far back";
+                        state->mode = BAD;
+                        break;
+                    }
+                    from = window - OFF;
+                    if (write == 0) {           /* very common case */
+                        from += wsize - op;
+                        if (op < len) {         /* some from window */
+                            len -= op;
+                            do {
+                                PUP(out) = PUP(from);
+                            } while (--op);
+                            from = out - dist;  /* rest from output */
+                        }
+                    }
+                    else if (write < op) {      /* wrap around window */
+                        from += wsize + write - op;
+                        op -= write;
+                        if (op < len) {         /* some from end of window */
+                            len -= op;
+                            do {
+                                PUP(out) = PUP(from);
+                            } while (--op);
+                            from = window - OFF;
+                            if (write < len) {  /* some from start of window */
+                                op = write;
+                                len -= op;
+                                do {
+                                    PUP(out) = PUP(from);
+                                } while (--op);
+                                from = out - dist;      /* rest from output */
+                            }
+                        }
+                    }
+                    else {                      /* contiguous in window */
+                        from += write - op;
+                        if (op < len) {         /* some from window */
+                            len -= op;
+                            do {
+                                PUP(out) = PUP(from);
+                            } while (--op);
+                            from = out - dist;  /* rest from output */
+                        }
+                    }
+                    while (len > 2) {
+                        PUP(out) = PUP(from);
+                        PUP(out) = PUP(from);
+                        PUP(out) = PUP(from);
+                        len -= 3;
+                    }
+                    if (len) {
+                        PUP(out) = PUP(from);
+                        if (len > 1)
+                            PUP(out) = PUP(from);
+                    }
+                }
+                else {
+                    from = out - dist;          /* copy direct from output */
+                    do {                        /* minimum length is three */
+                        PUP(out) = PUP(from);
+                        PUP(out) = PUP(from);
+                        PUP(out) = PUP(from);
+                        len -= 3;
+                    } while (len > 2);
+                    if (len) {
+                        PUP(out) = PUP(from);
+                        if (len > 1)
+                            PUP(out) = PUP(from);
+                    }
+                }
+            }
+            else if ((op & 64) == 0) {          /* 2nd level distance code */
+                this = dcode[this.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 */
+            this = lcode[this.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 + OFF;
+    strm->next_out = out + OFF;
+    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 write == 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 */
diff --git a/src/engine/external/zlib/inffast.h b/src/engine/external/zlib/inffast.h
new file mode 100644
index 00000000..1e88d2d9
--- /dev/null
+++ b/src/engine/external/zlib/inffast.h
@@ -0,0 +1,11 @@
+/* inffast.h -- header to use inffast.c
+ * Copyright (C) 1995-2003 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 inflate_fast OF((z_streamp strm, unsigned start));
diff --git a/src/engine/external/zlib/inffixed.h b/src/engine/external/zlib/inffixed.h
new file mode 100644
index 00000000..75ed4b59
--- /dev/null
+++ b/src/engine/external/zlib/inffixed.h
@@ -0,0 +1,94 @@
+    /* 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 the compression 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}
+    };
diff --git a/src/engine/external/zlib/inflate.c b/src/engine/external/zlib/inflate.c
new file mode 100644
index 00000000..792fdee8
--- /dev/null
+++ b/src/engine/external/zlib/inflate.c
@@ -0,0 +1,1368 @@
+/* inflate.c -- zlib decompression
+ * Copyright (C) 1995-2005 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 write == 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 void fixedtables OF((struct inflate_state FAR *state));
+local int updatewindow OF((z_streamp strm, unsigned out));
+#ifdef BUILDFIXED
+   void makefixed OF((void));
+#endif
+local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
+                              unsigned len));
+
+int ZEXPORT inflateReset(strm)
+z_streamp strm;
+{
+    struct inflate_state FAR *state;
+
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    strm->total_in = strm->total_out = state->total = 0;
+    strm->msg = Z_NULL;
+    strm->adler = 1;        /* to support ill-conceived Java test suite */
+    state->mode = HEAD;
+    state->last = 0;
+    state->havedict = 0;
+    state->dmax = 32768U;
+    state->head = Z_NULL;
+    state->wsize = 0;
+    state->whave = 0;
+    state->write = 0;
+    state->hold = 0;
+    state->bits = 0;
+    state->lencode = state->distcode = state->next = state->codes;
+    Tracev((stderr, "inflate: reset\n"));
+    return Z_OK;
+}
+
+int ZEXPORT inflatePrime(strm, bits, value)
+z_streamp strm;
+int bits;
+int value;
+{
+    struct inflate_state FAR *state;
+
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
+    value &= (1L << bits) - 1;
+    state->hold += value << state->bits;
+    state->bits += bits;
+    return Z_OK;
+}
+
+int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size)
+z_streamp strm;
+int windowBits;
+const char *version;
+int stream_size;
+{
+    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) {
+        strm->zalloc = zcalloc;
+        strm->opaque = (voidpf)0;
+    }
+    if (strm->zfree == (free_func)0) strm->zfree = zcfree;
+    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;
+    if (windowBits < 0) {
+        state->wrap = 0;
+        windowBits = -windowBits;
+    }
+    else {
+        state->wrap = (windowBits >> 4) + 1;
+#ifdef GUNZIP
+        if (windowBits < 48) windowBits &= 15;
+#endif
+    }
+    if (windowBits < 8 || windowBits > 15) {
+        ZFREE(strm, state);
+        strm->state = Z_NULL;
+        return Z_STREAM_ERROR;
+    }
+    state->wbits = (unsigned)windowBits;
+    state->window = Z_NULL;
+    return inflateReset(strm);
+}
+
+int ZEXPORT inflateInit_(strm, version, stream_size)
+z_streamp strm;
+const char *version;
+int stream_size;
+{
+    return inflateInit2_(strm, DEF_WBITS, version, stream_size);
+}
+
+/*
+   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}", 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, out)
+z_streamp strm;
+unsigned out;
+{
+    struct inflate_state FAR *state;
+    unsigned copy, 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->write = 0;
+        state->whave = 0;
+    }
+
+    /* copy state->wsize or less output bytes into the circular window */
+    copy = out - strm->avail_out;
+    if (copy >= state->wsize) {
+        zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
+        state->write = 0;
+        state->whave = state->wsize;
+    }
+    else {
+        dist = state->wsize - state->write;
+        if (dist > copy) dist = copy;
+        zmemcpy(state->window + state->write, strm->next_out - copy, dist);
+        copy -= dist;
+        if (copy) {
+            zmemcpy(state->window, strm->next_out - copy, copy);
+            state->write = copy;
+            state->whave = state->wsize;
+        }
+        else {
+            state->write += dist;
+            if (state->write == state->wsize) state->write = 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)
+
+/* Reverse the bytes in a 32-bit value */
+#define REVERSE(q) \
+    ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
+     (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
+
+/*
+   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;
+    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 this;                  /* 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 (strm == Z_NULL || strm->state == Z_NULL || 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 */
+                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 (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) 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) 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) 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) 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->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++] = len;
+                } while (len && copy < have);
+                if (state->flags & 0x0200)
+                    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++] = len;
+                } while (len && copy < have);
+                if (state->flags & 0x0200)
+                    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 (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 = REVERSE(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) 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 */
+                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;
+        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 = (code const 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 (;;) {
+                    this = state->lencode[BITS(state->lenbits)];
+                    if ((unsigned)(this.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                if (this.val < 16) {
+                    NEEDBITS(this.bits);
+                    DROPBITS(this.bits);
+                    state->lens[state->have++] = this.val;
+                }
+                else {
+                    if (this.val == 16) {
+                        NEEDBITS(this.bits + 2);
+                        DROPBITS(this.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 (this.val == 17) {
+                        NEEDBITS(this.bits + 3);
+                        DROPBITS(this.bits);
+                        len = 0;
+                        copy = 3 + BITS(3);
+                        DROPBITS(3);
+                    }
+                    else {
+                        NEEDBITS(this.bits + 7);
+                        DROPBITS(this.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;
+
+            /* build code tables */
+            state->next = state->codes;
+            state->lencode = (code const 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 = (code const 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;
+        case LEN:
+            if (have >= 6 && left >= 258) {
+                RESTORE();
+                inflate_fast(strm, out);
+                LOAD();
+                break;
+            }
+            for (;;) {
+                this = state->lencode[BITS(state->lenbits)];
+                if ((unsigned)(this.bits) <= bits) break;
+                PULLBYTE();
+            }
+            if (this.op && (this.op & 0xf0) == 0) {
+                last = this;
+                for (;;) {
+                    this = state->lencode[last.val +
+                            (BITS(last.bits + last.op) >> last.bits)];
+                    if ((unsigned)(last.bits + this.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                DROPBITS(last.bits);
+            }
+            DROPBITS(this.bits);
+            state->length = (unsigned)this.val;
+            if ((int)(this.op) == 0) {
+                Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
+                        "inflate:         literal '%c'\n" :
+                        "inflate:         literal 0x%02x\n", this.val));
+                state->mode = LIT;
+                break;
+            }
+            if (this.op & 32) {
+                Tracevv((stderr, "inflate:         end of block\n"));
+                state->mode = TYPE;
+                break;
+            }
+            if (this.op & 64) {
+                strm->msg = (char *)"invalid literal/length code";
+                state->mode = BAD;
+                break;
+            }
+            state->extra = (unsigned)(this.op) & 15;
+            state->mode = LENEXT;
+        case LENEXT:
+            if (state->extra) {
+                NEEDBITS(state->extra);
+                state->length += BITS(state->extra);
+                DROPBITS(state->extra);
+            }
+            Tracevv((stderr, "inflate:         length %u\n", state->length));
+            state->mode = DIST;
+        case DIST:
+            for (;;) {
+                this = state->distcode[BITS(state->distbits)];
+                if ((unsigned)(this.bits) <= bits) break;
+                PULLBYTE();
+            }
+            if ((this.op & 0xf0) == 0) {
+                last = this;
+                for (;;) {
+                    this = state->distcode[last.val +
+                            (BITS(last.bits + last.op) >> last.bits)];
+                    if ((unsigned)(last.bits + this.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                DROPBITS(last.bits);
+            }
+            DROPBITS(this.bits);
+            if (this.op & 64) {
+                strm->msg = (char *)"invalid distance code";
+                state->mode = BAD;
+                break;
+            }
+            state->offset = (unsigned)this.val;
+            state->extra = (unsigned)(this.op) & 15;
+            state->mode = DISTEXT;
+        case DISTEXT:
+            if (state->extra) {
+                NEEDBITS(state->extra);
+                state->offset += BITS(state->extra);
+                DROPBITS(state->extra);
+            }
+#ifdef INFLATE_STRICT
+            if (state->offset > state->dmax) {
+                strm->msg = (char *)"invalid distance too far back";
+                state->mode = BAD;
+                break;
+            }
+#endif
+            if (state->offset > state->whave + out - left) {
+                strm->msg = (char *)"invalid distance too far back";
+                state->mode = BAD;
+                break;
+            }
+            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->write) {
+                    copy -= state->write;
+                    from = state->window + (state->wsize - copy);
+                }
+                else
+                    from = state->window + (state->write - 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 (out)
+                    strm->adler = state->check =
+                        UPDATE(state->check, put - out, out);
+                out = left;
+                if ((
+#ifdef GUNZIP
+                     state->flags ? hold :
+#endif
+                     REVERSE(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 || (state->mode < CHECK && out != strm->avail_out))
+        if (updatewindow(strm, 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 && out)
+        strm->adler = state->check =
+            UPDATE(state->check, strm->next_out - out, out);
+    strm->data_type = state->bits + (state->last ? 64 : 0) +
+                      (state->mode == TYPE ? 128 : 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 (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
+        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 inflateSetDictionary(strm, dictionary, dictLength)
+z_streamp strm;
+const Bytef *dictionary;
+uInt dictLength;
+{
+    struct inflate_state FAR *state;
+    unsigned long id;
+
+    /* check state */
+    if (strm == Z_NULL || strm->state == Z_NULL) 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 id */
+    if (state->mode == DICT) {
+        id = adler32(0L, Z_NULL, 0);
+        id = adler32(id, dictionary, dictLength);
+        if (id != state->check)
+            return Z_DATA_ERROR;
+    }
+
+    /* copy dictionary to window */
+    if (updatewindow(strm, strm->avail_out)) {
+        state->mode = MEM;
+        return Z_MEM_ERROR;
+    }
+    if (dictLength > state->wsize) {
+        zmemcpy(state->window, dictionary + dictLength - state->wsize,
+                state->wsize);
+        state->whave = state->wsize;
+    }
+    else {
+        zmemcpy(state->window + state->wsize - dictLength, dictionary,
+                dictLength);
+        state->whave = dictLength;
+    }
+    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 (strm == Z_NULL || strm->state == Z_NULL) 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;
+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 (strm == Z_NULL || strm->state == Z_NULL) 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 (strm == Z_NULL || strm->state == Z_NULL) 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 (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
+        source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
+        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(dest, source, sizeof(z_stream));
+    zmemcpy(copy, state, sizeof(struct inflate_state));
+    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;
+}
diff --git a/src/engine/external/zlib/inflate.h b/src/engine/external/zlib/inflate.h
new file mode 100644
index 00000000..07bd3e78
--- /dev/null
+++ b/src/engine/external/zlib/inflate.h
@@ -0,0 +1,115 @@
+/* inflate.h -- internal inflate state definition
+ * Copyright (C) 1995-2004 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,       /* 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: 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: waiting for length/lit 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 the BAD or MEM mode -- not shown for clarity)
+
+    Process header:
+        HEAD -> (gzip) or (zlib)
+        (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
+        NAME -> COMMENT -> HCRC -> TYPE
+        (zlib) -> DICTID or TYPE
+        DICTID -> DICT -> TYPE
+    Read deflate blocks:
+            TYPE -> STORED or TABLE or LEN or CHECK
+            STORED -> COPY -> TYPE
+            TABLE -> LENLENS -> CODELENS -> LEN
+    Read deflate codes:
+                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. */
+struct inflate_state {
+    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 */
+    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 write;             /* 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 */
+};
diff --git a/src/engine/external/zlib/inftrees.c b/src/engine/external/zlib/inftrees.c
new file mode 100644
index 00000000..8a9c13ff
--- /dev/null
+++ b/src/engine/external/zlib/inftrees.c
@@ -0,0 +1,329 @@
+/* inftrees.c -- generate Huffman trees for efficient decoding
+ * Copyright (C) 1995-2005 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.3 Copyright 1995-2005 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 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 this;                  /* 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 */
+    int end;                    /* use base and extra for symbol > end */
+    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, 201, 196};
+    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 */
+        this.op = (unsigned char)64;    /* invalid code marker */
+        this.bits = (unsigned char)1;
+        this.val = (unsigned short)0;
+        *(*table)++ = this;             /* make a table to force an error */
+        *(*table)++ = this;
+        *bits = 1;
+        return 0;     /* no symbols, but wait for decoding to report error */
+    }
+    for (min = 1; min <= MAXBITS; 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 when a LENS table is being made
+       against the space in *table, ENOUGH, minus the maximum space needed by
+       the worst case distance code, MAXD.  This should never happen, but the
+       sufficiency of ENOUGH has not been proven exhaustively, hence the check.
+       This assumes that when type == LENS, bits == 9.
+
+       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 */
+        end = 19;
+        break;
+    case LENS:
+        base = lbase;
+        base -= 257;
+        extra = lext;
+        extra -= 257;
+        end = 256;
+        break;
+    default:            /* DISTS */
+        base = dbase;
+        extra = dext;
+        end = -1;
+    }
+
+    /* 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 - MAXD)
+        return 1;
+
+    /* process all codes and make table entries */
+    for (;;) {
+        /* create table entry */
+        this.bits = (unsigned char)(len - drop);
+        if ((int)(work[sym]) < end) {
+            this.op = (unsigned char)0;
+            this.val = work[sym];
+        }
+        else if ((int)(work[sym]) > end) {
+            this.op = (unsigned char)(extra[work[sym]]);
+            this.val = base[work[sym]];
+        }
+        else {
+            this.op = (unsigned char)(32 + 64);         /* end of block */
+            this.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] = this;
+        } 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 - MAXD)
+                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 rest of table for incomplete codes.  This loop is similar to the
+       loop above in incrementing huff for table indices.  It is assumed that
+       len is equal to curr + drop, so there is no loop needed to increment
+       through high index bits.  When the current sub-table is filled, the loop
+       drops back to the root table to fill in any remaining entries there.
+     */
+    this.op = (unsigned char)64;                /* invalid code marker */
+    this.bits = (unsigned char)(len - drop);
+    this.val = (unsigned short)0;
+    while (huff != 0) {
+        /* when done with sub-table, drop back to root table */
+        if (drop != 0 && (huff & mask) != low) {
+            drop = 0;
+            len = root;
+            next = *table;
+            this.bits = (unsigned char)len;
+        }
+
+        /* put invalid code marker in table */
+        next[huff >> drop] = this;
+
+        /* 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;
+    }
+
+    /* set return parameters */
+    *table += used;
+    *bits = root;
+    return 0;
+}
diff --git a/src/engine/external/zlib/inftrees.h b/src/engine/external/zlib/inftrees.h
new file mode 100644
index 00000000..b1104c87
--- /dev/null
+++ b/src/engine/external/zlib/inftrees.h
@@ -0,0 +1,55 @@
+/* inftrees.h -- header to use inftrees.c
+ * Copyright (C) 1995-2005 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 dynamic tree.  The maximum found in a long but non-
+   exhaustive search was 1444 code structures (852 for length/literals
+   and 592 for distances, the latter actually the result of an
+   exhaustive search).  The true maximum is not known, but the value
+   below is more than safe. */
+#define ENOUGH 2048
+#define MAXD 592
+
+/* Type of code to build for inftable() */
+typedef enum {
+    CODES,
+    LENS,
+    DISTS
+} codetype;
+
+extern int inflate_table OF((codetype type, unsigned short FAR *lens,
+                             unsigned codes, code FAR * FAR *table,
+                             unsigned FAR *bits, unsigned short FAR *work));
diff --git a/src/engine/external/zlib/trees.c b/src/engine/external/zlib/trees.c
new file mode 100644
index 00000000..395e4e16
--- /dev/null
+++ b/src/engine/external/zlib/trees.c
@@ -0,0 +1,1219 @@
+/* trees.c -- output deflated data using Huffman coding
+ * Copyright (C) 1995-2005 Jean-loup Gailly
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/*
+ *  ALGORITHM
+ *
+ *      The "deflation" process uses several Huffman trees. The more
+ *      common source values are represented by shorter bit sequences.
+ *
+ *      Each code tree is stored in a compressed form which is itself
+ * a Huffman encoding of the lengths of all the code strings (in
+ * ascending order by source values).  The actual code strings are
+ * reconstructed from the lengths in the inflate process, as described
+ * in the deflate specification.
+ *
+ *  REFERENCES
+ *
+ *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
+ *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
+ *
+ *      Storer, James A.
+ *          Data Compression:  Methods and Theory, pp. 49-50.
+ *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
+ *
+ *      Sedgewick, R.
+ *          Algorithms, p290.
+ *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
+ */
+
+/* @(#) $Id$ */
+
+/* #define GEN_TREES_H */
+
+#include "deflate.h"
+
+#ifdef DEBUG
+#  include <ctype.h>
+#endif
+
+/* ===========================================================================
+ * Constants
+ */
+
+#define MAX_BL_BITS 7
+/* Bit length codes must not exceed MAX_BL_BITS bits */
+
+#define END_BLOCK 256
+/* end of block literal code */
+
+#define REP_3_6      16
+/* repeat previous bit length 3-6 times (2 bits of repeat count) */
+
+#define REPZ_3_10    17
+/* repeat a zero length 3-10 times  (3 bits of repeat count) */
+
+#define REPZ_11_138  18
+/* repeat a zero length 11-138 times  (7 bits of repeat count) */
+
+local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
+   = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
+
+local const int extra_dbits[D_CODES] /* extra bits for each distance code */
+   = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
+
+local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
+   = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
+
+local const uch bl_order[BL_CODES]
+   = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
+/* The lengths of the bit length codes are sent in order of decreasing
+ * probability, to avoid transmitting the lengths for unused bit length codes.
+ */
+
+#define Buf_size (8 * 2*sizeof(char))
+/* Number of bits used within bi_buf. (bi_buf might be implemented on
+ * more than 16 bits on some systems.)
+ */
+
+/* ===========================================================================
+ * Local data. These are initialized only once.
+ */
+
+#define DIST_CODE_LEN  512 /* see definition of array dist_code below */
+
+#if defined(GEN_TREES_H) || !defined(STDC)
+/* non ANSI compilers may not accept trees.h */
+
+local ct_data static_ltree[L_CODES+2];
+/* The static literal tree. Since the bit lengths are imposed, there is no
+ * need for the L_CODES extra codes used during heap construction. However
+ * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
+ * below).
+ */
+
+local ct_data static_dtree[D_CODES];
+/* The static distance tree. (Actually a trivial tree since all codes use
+ * 5 bits.)
+ */
+
+uch _dist_code[DIST_CODE_LEN];
+/* Distance codes. The first 256 values correspond to the distances
+ * 3 .. 258, the last 256 values correspond to the top 8 bits of
+ * the 15 bit distances.
+ */
+
+uch _length_code[MAX_MATCH-MIN_MATCH+1];
+/* length code for each normalized match length (0 == MIN_MATCH) */
+
+local int base_length[LENGTH_CODES];
+/* First normalized length for each code (0 = MIN_MATCH) */
+
+local int base_dist[D_CODES];
+/* First normalized distance for each code (0 = distance of 1) */
+
+#else
+#  include "trees.h"
+#endif /* GEN_TREES_H */
+
+struct static_tree_desc_s {
+    const ct_data *static_tree;  /* static tree or NULL */
+    const intf *extra_bits;      /* extra bits for each code or NULL */
+    int     extra_base;          /* base index for extra_bits */
+    int     elems;               /* max number of elements in the tree */
+    int     max_length;          /* max bit length for the codes */
+};
+
+local static_tree_desc  static_l_desc =
+{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
+
+local static_tree_desc  static_d_desc =
+{static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
+
+local static_tree_desc  static_bl_desc =
+{(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};
+
+/* ===========================================================================
+ * Local (static) routines in this file.
+ */
+
+local void tr_static_init OF((void));
+local void init_block     OF((deflate_state *s));
+local void pqdownheap     OF((deflate_state *s, ct_data *tree, int k));
+local void gen_bitlen     OF((deflate_state *s, tree_desc *desc));
+local void gen_codes      OF((ct_data *tree, int max_code, ushf *bl_count));
+local void build_tree     OF((deflate_state *s, tree_desc *desc));
+local void scan_tree      OF((deflate_state *s, ct_data *tree, int max_code));
+local void send_tree      OF((deflate_state *s, ct_data *tree, int max_code));
+local int  build_bl_tree  OF((deflate_state *s));
+local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
+                              int blcodes));
+local void compress_block OF((deflate_state *s, ct_data *ltree,
+                              ct_data *dtree));
+local void set_data_type  OF((deflate_state *s));
+local unsigned bi_reverse OF((unsigned value, int length));
+local void bi_windup      OF((deflate_state *s));
+local void bi_flush       OF((deflate_state *s));
+local void copy_block     OF((deflate_state *s, charf *buf, unsigned len,
+                              int header));
+
+#ifdef GEN_TREES_H
+local void gen_trees_header OF((void));
+#endif
+
+#ifndef DEBUG
+#  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
+   /* Send a code of the given tree. c and tree must not have side effects */
+
+#else /* DEBUG */
+#  define send_code(s, c, tree) \
+     { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
+       send_bits(s, tree[c].Code, tree[c].Len); }
+#endif
+
+/* ===========================================================================
+ * Output a short LSB first on the stream.
+ * IN assertion: there is enough room in pendingBuf.
+ */
+#define put_short(s, w) { \
+    put_byte(s, (uch)((w) & 0xff)); \
+    put_byte(s, (uch)((ush)(w) >> 8)); \
+}
+
+/* ===========================================================================
+ * Send a value on a given number of bits.
+ * IN assertion: length <= 16 and value fits in length bits.
+ */
+#ifdef DEBUG
+local void send_bits      OF((deflate_state *s, int value, int length));
+
+local void send_bits(s, value, length)
+    deflate_state *s;
+    int value;  /* value to send */
+    int length; /* number of bits */
+{
+    Tracevv((stderr," l %2d v %4x ", length, value));
+    Assert(length > 0 && length <= 15, "invalid length");
+    s->bits_sent += (ulg)length;
+
+    /* If not enough room in bi_buf, use (valid) bits from bi_buf and
+     * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
+     * unused bits in value.
+     */
+    if (s->bi_valid > (int)Buf_size - length) {
+        s->bi_buf |= (value << s->bi_valid);
+        put_short(s, s->bi_buf);
+        s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
+        s->bi_valid += length - Buf_size;
+    } else {
+        s->bi_buf |= value << s->bi_valid;
+        s->bi_valid += length;
+    }
+}
+#else /* !DEBUG */
+
+#define send_bits(s, value, length) \
+{ int len = length;\
+  if (s->bi_valid > (int)Buf_size - len) {\
+    int val = value;\
+    s->bi_buf |= (val << s->bi_valid);\
+    put_short(s, s->bi_buf);\
+    s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
+    s->bi_valid += len - Buf_size;\
+  } else {\
+    s->bi_buf |= (value) << s->bi_valid;\
+    s->bi_valid += len;\
+  }\
+}
+#endif /* DEBUG */
+
+
+/* the arguments must not have side effects */
+
+/* ===========================================================================
+ * Initialize the various 'constant' tables.
+ */
+local void tr_static_init()
+{
+#if defined(GEN_TREES_H) || !defined(STDC)
+    static int static_init_done = 0;
+    int n;        /* iterates over tree elements */
+    int bits;     /* bit counter */
+    int length;   /* length value */
+    int code;     /* code value */
+    int dist;     /* distance index */
+    ush bl_count[MAX_BITS+1];
+    /* number of codes at each bit length for an optimal tree */
+
+    if (static_init_done) return;
+
+    /* For some embedded targets, global variables are not initialized: */
+    static_l_desc.static_tree = static_ltree;
+    static_l_desc.extra_bits = extra_lbits;
+    static_d_desc.static_tree = static_dtree;
+    static_d_desc.extra_bits = extra_dbits;
+    static_bl_desc.extra_bits = extra_blbits;
+
+    /* Initialize the mapping length (0..255) -> length code (0..28) */
+    length = 0;
+    for (code = 0; code < LENGTH_CODES-1; code++) {
+        base_length[code] = length;
+        for (n = 0; n < (1<<extra_lbits[code]); n++) {
+            _length_code[length++] = (uch)code;
+        }
+    }
+    Assert (length == 256, "tr_static_init: length != 256");
+    /* Note that the length 255 (match length 258) can be represented
+     * in two different ways: code 284 + 5 bits or code 285, so we
+     * overwrite length_code[255] to use the best encoding:
+     */
+    _length_code[length-1] = (uch)code;
+
+    /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
+    dist = 0;
+    for (code = 0 ; code < 16; code++) {
+        base_dist[code] = dist;
+        for (n = 0; n < (1<<extra_dbits[code]); n++) {
+            _dist_code[dist++] = (uch)code;
+        }
+    }
+    Assert (dist == 256, "tr_static_init: dist != 256");
+    dist >>= 7; /* from now on, all distances are divided by 128 */
+    for ( ; code < D_CODES; code++) {
+        base_dist[code] = dist << 7;
+        for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
+            _dist_code[256 + dist++] = (uch)code;
+        }
+    }
+    Assert (dist == 256, "tr_static_init: 256+dist != 512");
+
+    /* Construct the codes of the static literal tree */
+    for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
+    n = 0;
+    while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
+    while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
+    while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
+    while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
+    /* Codes 286 and 287 do not exist, but we must include them in the
+     * tree construction to get a canonical Huffman tree (longest code
+     * all ones)
+     */
+    gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
+
+    /* The static distance tree is trivial: */
+    for (n = 0; n < D_CODES; n++) {
+        static_dtree[n].Len = 5;
+        static_dtree[n].Code = bi_reverse((unsigned)n, 5);
+    }
+    static_init_done = 1;
+
+#  ifdef GEN_TREES_H
+    gen_trees_header();
+#  endif
+#endif /* defined(GEN_TREES_H) || !defined(STDC) */
+}
+
+/* ===========================================================================
+ * Genererate the file trees.h describing the static trees.
+ */
+#ifdef GEN_TREES_H
+#  ifndef DEBUG
+#    include <stdio.h>
+#  endif
+
+#  define SEPARATOR(i, last, width) \
+      ((i) == (last)? "\n};\n\n" :    \
+       ((i) % (width) == (width)-1 ? ",\n" : ", "))
+
+void gen_trees_header()
+{
+    FILE *header = fopen("trees.h", "w");
+    int i;
+
+    Assert (header != NULL, "Can't open trees.h");
+    fprintf(header,
+            "/* header created automatically with -DGEN_TREES_H */\n\n");
+
+    fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
+    for (i = 0; i < L_CODES+2; i++) {
+        fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
+                static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
+    }
+
+    fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
+    for (i = 0; i < D_CODES; i++) {
+        fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
+                static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
+    }
+
+    fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
+    for (i = 0; i < DIST_CODE_LEN; i++) {
+        fprintf(header, "%2u%s", _dist_code[i],
+                SEPARATOR(i, DIST_CODE_LEN-1, 20));
+    }
+
+    fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
+    for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
+        fprintf(header, "%2u%s", _length_code[i],
+                SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
+    }
+
+    fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
+    for (i = 0; i < LENGTH_CODES; i++) {
+        fprintf(header, "%1u%s", base_length[i],
+                SEPARATOR(i, LENGTH_CODES-1, 20));
+    }
+
+    fprintf(header, "local const int base_dist[D_CODES] = {\n");
+    for (i = 0; i < D_CODES; i++) {
+        fprintf(header, "%5u%s", base_dist[i],
+                SEPARATOR(i, D_CODES-1, 10));
+    }
+
+    fclose(header);
+}
+#endif /* GEN_TREES_H */
+
+/* ===========================================================================
+ * Initialize the tree data structures for a new zlib stream.
+ */
+void _tr_init(s)
+    deflate_state *s;
+{
+    tr_static_init();
+
+    s->l_desc.dyn_tree = s->dyn_ltree;
+    s->l_desc.stat_desc = &static_l_desc;
+
+    s->d_desc.dyn_tree = s->dyn_dtree;
+    s->d_desc.stat_desc = &static_d_desc;
+
+    s->bl_desc.dyn_tree = s->bl_tree;
+    s->bl_desc.stat_desc = &static_bl_desc;
+
+    s->bi_buf = 0;
+    s->bi_valid = 0;
+    s->last_eob_len = 8; /* enough lookahead for inflate */
+#ifdef DEBUG
+    s->compressed_len = 0L;
+    s->bits_sent = 0L;
+#endif
+
+    /* Initialize the first block of the first file: */
+    init_block(s);
+}
+
+/* ===========================================================================
+ * Initialize a new block.
+ */
+local void init_block(s)
+    deflate_state *s;
+{
+    int n; /* iterates over tree elements */
+
+    /* Initialize the trees. */
+    for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
+    for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
+    for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
+
+    s->dyn_ltree[END_BLOCK].Freq = 1;
+    s->opt_len = s->static_len = 0L;
+    s->last_lit = s->matches = 0;
+}
+
+#define SMALLEST 1
+/* Index within the heap array of least frequent node in the Huffman tree */
+
+
+/* ===========================================================================
+ * Remove the smallest element from the heap and recreate the heap with
+ * one less element. Updates heap and heap_len.
+ */
+#define pqremove(s, tree, top) \
+{\
+    top = s->heap[SMALLEST]; \
+    s->heap[SMALLEST] = s->heap[s->heap_len--]; \
+    pqdownheap(s, tree, SMALLEST); \
+}
+
+/* ===========================================================================
+ * Compares to subtrees, using the tree depth as tie breaker when
+ * the subtrees have equal frequency. This minimizes the worst case length.
+ */
+#define smaller(tree, n, m, depth) \
+   (tree[n].Freq < tree[m].Freq || \
+   (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
+
+/* ===========================================================================
+ * Restore the heap property by moving down the tree starting at node k,
+ * exchanging a node with the smallest of its two sons if necessary, stopping
+ * when the heap property is re-established (each father smaller than its
+ * two sons).
+ */
+local void pqdownheap(s, tree, k)
+    deflate_state *s;
+    ct_data *tree;  /* the tree to restore */
+    int k;               /* node to move down */
+{
+    int v = s->heap[k];
+    int j = k << 1;  /* left son of k */
+    while (j <= s->heap_len) {
+        /* Set j to the smallest of the two sons: */
+        if (j < s->heap_len &&
+            smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
+            j++;
+        }
+        /* Exit if v is smaller than both sons */
+        if (smaller(tree, v, s->heap[j], s->depth)) break;
+
+        /* Exchange v with the smallest son */
+        s->heap[k] = s->heap[j];  k = j;
+
+        /* And continue down the tree, setting j to the left son of k */
+        j <<= 1;
+    }
+    s->heap[k] = v;
+}
+
+/* ===========================================================================
+ * Compute the optimal bit lengths for a tree and update the total bit length
+ * for the current block.
+ * IN assertion: the fields freq and dad are set, heap[heap_max] and
+ *    above are the tree nodes sorted by increasing frequency.
+ * OUT assertions: the field len is set to the optimal bit length, the
+ *     array bl_count contains the frequencies for each bit length.
+ *     The length opt_len is updated; static_len is also updated if stree is
+ *     not null.
+ */
+local void gen_bitlen(s, desc)
+    deflate_state *s;
+    tree_desc *desc;    /* the tree descriptor */
+{
+    ct_data *tree        = desc->dyn_tree;
+    int max_code         = desc->max_code;
+    const ct_data *stree = desc->stat_desc->static_tree;
+    const intf *extra    = desc->stat_desc->extra_bits;
+    int base             = desc->stat_desc->extra_base;
+    int max_length       = desc->stat_desc->max_length;
+    int h;              /* heap index */
+    int n, m;           /* iterate over the tree elements */
+    int bits;           /* bit length */
+    int xbits;          /* extra bits */
+    ush f;              /* frequency */
+    int overflow = 0;   /* number of elements with bit length too large */
+
+    for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
+
+    /* In a first pass, compute the optimal bit lengths (which may
+     * overflow in the case of the bit length tree).
+     */
+    tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
+
+    for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
+        n = s->heap[h];
+        bits = tree[tree[n].Dad].Len + 1;
+        if (bits > max_length) bits = max_length, overflow++;
+        tree[n].Len = (ush)bits;
+        /* We overwrite tree[n].Dad which is no longer needed */
+
+        if (n > max_code) continue; /* not a leaf node */
+
+        s->bl_count[bits]++;
+        xbits = 0;
+        if (n >= base) xbits = extra[n-base];
+        f = tree[n].Freq;
+        s->opt_len += (ulg)f * (bits + xbits);
+        if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
+    }
+    if (overflow == 0) return;
+
+    Trace((stderr,"\nbit length overflow\n"));
+    /* This happens for example on obj2 and pic of the Calgary corpus */
+
+    /* Find the first bit length which could increase: */
+    do {
+        bits = max_length-1;
+        while (s->bl_count[bits] == 0) bits--;
+        s->bl_count[bits]--;      /* move one leaf down the tree */
+        s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
+        s->bl_count[max_length]--;
+        /* The brother of the overflow item also moves one step up,
+         * but this does not affect bl_count[max_length]
+         */
+        overflow -= 2;
+    } while (overflow > 0);
+
+    /* Now recompute all bit lengths, scanning in increasing frequency.
+     * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
+     * lengths instead of fixing only the wrong ones. This idea is taken
+     * from 'ar' written by Haruhiko Okumura.)
+     */
+    for (bits = max_length; bits != 0; bits--) {
+        n = s->bl_count[bits];
+        while (n != 0) {
+            m = s->heap[--h];
+            if (m > max_code) continue;
+            if ((unsigned) tree[m].Len != (unsigned) bits) {
+                Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
+                s->opt_len += ((long)bits - (long)tree[m].Len)
+                              *(long)tree[m].Freq;
+                tree[m].Len = (ush)bits;
+            }
+            n--;
+        }
+    }
+}
+
+/* ===========================================================================
+ * Generate the codes for a given tree and bit counts (which need not be
+ * optimal).
+ * IN assertion: the array bl_count contains the bit length statistics for
+ * the given tree and the field len is set for all tree elements.
+ * OUT assertion: the field code is set for all tree elements of non
+ *     zero code length.
+ */
+local void gen_codes (tree, max_code, bl_count)
+    ct_data *tree;             /* the tree to decorate */
+    int max_code;              /* largest code with non zero frequency */
+    ushf *bl_count;            /* number of codes at each bit length */
+{
+    ush next_code[MAX_BITS+1]; /* next code value for each bit length */
+    ush code = 0;              /* running code value */
+    int bits;                  /* bit index */
+    int n;                     /* code index */
+
+    /* The distribution counts are first used to generate the code values
+     * without bit reversal.
+     */
+    for (bits = 1; bits <= MAX_BITS; bits++) {
+        next_code[bits] = code = (code + bl_count[bits-1]) << 1;
+    }
+    /* Check that the bit counts in bl_count are consistent. The last code
+     * must be all ones.
+     */
+    Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
+            "inconsistent bit counts");
+    Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
+
+    for (n = 0;  n <= max_code; n++) {
+        int len = tree[n].Len;
+        if (len == 0) continue;
+        /* Now reverse the bits */
+        tree[n].Code = bi_reverse(next_code[len]++, len);
+
+        Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
+             n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
+    }
+}
+
+/* ===========================================================================
+ * Construct one Huffman tree and assigns the code bit strings and lengths.
+ * Update the total bit length for the current block.
+ * IN assertion: the field freq is set for all tree elements.
+ * OUT assertions: the fields len and code are set to the optimal bit length
+ *     and corresponding code. The length opt_len is updated; static_len is
+ *     also updated if stree is not null. The field max_code is set.
+ */
+local void build_tree(s, desc)
+    deflate_state *s;
+    tree_desc *desc; /* the tree descriptor */
+{
+    ct_data *tree         = desc->dyn_tree;
+    const ct_data *stree  = desc->stat_desc->static_tree;
+    int elems             = desc->stat_desc->elems;
+    int n, m;          /* iterate over heap elements */
+    int max_code = -1; /* largest code with non zero frequency */
+    int node;          /* new node being created */
+
+    /* Construct the initial heap, with least frequent element in
+     * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
+     * heap[0] is not used.
+     */
+    s->heap_len = 0, s->heap_max = HEAP_SIZE;
+
+    for (n = 0; n < elems; n++) {
+        if (tree[n].Freq != 0) {
+            s->heap[++(s->heap_len)] = max_code = n;
+            s->depth[n] = 0;
+        } else {
+            tree[n].Len = 0;
+        }
+    }
+
+    /* The pkzip format requires that at least one distance code exists,
+     * and that at least one bit should be sent even if there is only one
+     * possible code. So to avoid special checks later on we force at least
+     * two codes of non zero frequency.
+     */
+    while (s->heap_len < 2) {
+        node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
+        tree[node].Freq = 1;
+        s->depth[node] = 0;
+        s->opt_len--; if (stree) s->static_len -= stree[node].Len;
+        /* node is 0 or 1 so it does not have extra bits */
+    }
+    desc->max_code = max_code;
+
+    /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
+     * establish sub-heaps of increasing lengths:
+     */
+    for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
+
+    /* Construct the Huffman tree by repeatedly combining the least two
+     * frequent nodes.
+     */
+    node = elems;              /* next internal node of the tree */
+    do {
+        pqremove(s, tree, n);  /* n = node of least frequency */
+        m = s->heap[SMALLEST]; /* m = node of next least frequency */
+
+        s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
+        s->heap[--(s->heap_max)] = m;
+
+        /* Create a new node father of n and m */
+        tree[node].Freq = tree[n].Freq + tree[m].Freq;
+        s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
+                                s->depth[n] : s->depth[m]) + 1);
+        tree[n].Dad = tree[m].Dad = (ush)node;
+#ifdef DUMP_BL_TREE
+        if (tree == s->bl_tree) {
+            fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
+                    node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
+        }
+#endif
+        /* and insert the new node in the heap */
+        s->heap[SMALLEST] = node++;
+        pqdownheap(s, tree, SMALLEST);
+
+    } while (s->heap_len >= 2);
+
+    s->heap[--(s->heap_max)] = s->heap[SMALLEST];
+
+    /* At this point, the fields freq and dad are set. We can now
+     * generate the bit lengths.
+     */
+    gen_bitlen(s, (tree_desc *)desc);
+
+    /* The field len is now set, we can generate the bit codes */
+    gen_codes ((ct_data *)tree, max_code, s->bl_count);
+}
+
+/* ===========================================================================
+ * Scan a literal or distance tree to determine the frequencies of the codes
+ * in the bit length tree.
+ */
+local void scan_tree (s, tree, max_code)
+    deflate_state *s;
+    ct_data *tree;   /* the tree to be scanned */
+    int max_code;    /* and its largest code of non zero frequency */
+{
+    int n;                     /* iterates over all tree elements */
+    int prevlen = -1;          /* last emitted length */
+    int curlen;                /* length of current code */
+    int nextlen = tree[0].Len; /* length of next code */
+    int count = 0;             /* repeat count of the current code */
+    int max_count = 7;         /* max repeat count */
+    int min_count = 4;         /* min repeat count */
+
+    if (nextlen == 0) max_count = 138, min_count = 3;
+    tree[max_code+1].Len = (ush)0xffff; /* guard */
+
+    for (n = 0; n <= max_code; n++) {
+        curlen = nextlen; nextlen = tree[n+1].Len;
+        if (++count < max_count && curlen == nextlen) {
+            continue;
+        } else if (count < min_count) {
+            s->bl_tree[curlen].Freq += count;
+        } else if (curlen != 0) {
+            if (curlen != prevlen) s->bl_tree[curlen].Freq++;
+            s->bl_tree[REP_3_6].Freq++;
+        } else if (count <= 10) {
+            s->bl_tree[REPZ_3_10].Freq++;
+        } else {
+            s->bl_tree[REPZ_11_138].Freq++;
+        }
+        count = 0; prevlen = curlen;
+        if (nextlen == 0) {
+            max_count = 138, min_count = 3;
+        } else if (curlen == nextlen) {
+            max_count = 6, min_count = 3;
+        } else {
+            max_count = 7, min_count = 4;
+        }
+    }
+}
+
+/* ===========================================================================
+ * Send a literal or distance tree in compressed form, using the codes in
+ * bl_tree.
+ */
+local void send_tree (s, tree, max_code)
+    deflate_state *s;
+    ct_data *tree; /* the tree to be scanned */
+    int max_code;       /* and its largest code of non zero frequency */
+{
+    int n;                     /* iterates over all tree elements */
+    int prevlen = -1;          /* last emitted length */
+    int curlen;                /* length of current code */
+    int nextlen = tree[0].Len; /* length of next code */
+    int count = 0;             /* repeat count of the current code */
+    int max_count = 7;         /* max repeat count */
+    int min_count = 4;         /* min repeat count */
+
+    /* tree[max_code+1].Len = -1; */  /* guard already set */
+    if (nextlen == 0) max_count = 138, min_count = 3;
+
+    for (n = 0; n <= max_code; n++) {
+        curlen = nextlen; nextlen = tree[n+1].Len;
+        if (++count < max_count && curlen == nextlen) {
+            continue;
+        } else if (count < min_count) {
+            do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
+
+        } else if (curlen != 0) {
+            if (curlen != prevlen) {
+                send_code(s, curlen, s->bl_tree); count--;
+            }
+            Assert(count >= 3 && count <= 6, " 3_6?");
+            send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
+
+        } else if (count <= 10) {
+            send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
+
+        } else {
+            send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
+        }
+        count = 0; prevlen = curlen;
+        if (nextlen == 0) {
+            max_count = 138, min_count = 3;
+        } else if (curlen == nextlen) {
+            max_count = 6, min_count = 3;
+        } else {
+            max_count = 7, min_count = 4;
+        }
+    }
+}
+
+/* ===========================================================================
+ * Construct the Huffman tree for the bit lengths and return the index in
+ * bl_order of the last bit length code to send.
+ */
+local int build_bl_tree(s)
+    deflate_state *s;
+{
+    int max_blindex;  /* index of last bit length code of non zero freq */
+
+    /* Determine the bit length frequencies for literal and distance trees */
+    scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
+    scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
+
+    /* Build the bit length tree: */
+    build_tree(s, (tree_desc *)(&(s->bl_desc)));
+    /* opt_len now includes the length of the tree representations, except
+     * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
+     */
+
+    /* Determine the number of bit length codes to send. The pkzip format
+     * requires that at least 4 bit length codes be sent. (appnote.txt says
+     * 3 but the actual value used is 4.)
+     */
+    for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
+        if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
+    }
+    /* Update opt_len to include the bit length tree and counts */
+    s->opt_len += 3*(max_blindex+1) + 5+5+4;
+    Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
+            s->opt_len, s->static_len));
+
+    return max_blindex;
+}
+
+/* ===========================================================================
+ * Send the header for a block using dynamic Huffman trees: the counts, the
+ * lengths of the bit length codes, the literal tree and the distance tree.
+ * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
+ */
+local void send_all_trees(s, lcodes, dcodes, blcodes)
+    deflate_state *s;
+    int lcodes, dcodes, blcodes; /* number of codes for each tree */
+{
+    int rank;                    /* index in bl_order */
+
+    Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
+    Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
+            "too many codes");
+    Tracev((stderr, "\nbl counts: "));
+    send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
+    send_bits(s, dcodes-1,   5);
+    send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */
+    for (rank = 0; rank < blcodes; rank++) {
+        Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
+        send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
+    }
+    Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
+
+    send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
+    Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
+
+    send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
+    Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
+}
+
+/* ===========================================================================
+ * Send a stored block
+ */
+void _tr_stored_block(s, buf, stored_len, eof)
+    deflate_state *s;
+    charf *buf;       /* input block */
+    ulg stored_len;   /* length of input block */
+    int eof;          /* true if this is the last block for a file */
+{
+    send_bits(s, (STORED_BLOCK<<1)+eof, 3);  /* send block type */
+#ifdef DEBUG
+    s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
+    s->compressed_len += (stored_len + 4) << 3;
+#endif
+    copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
+}
+
+/* ===========================================================================
+ * Send one empty static block to give enough lookahead for inflate.
+ * This takes 10 bits, of which 7 may remain in the bit buffer.
+ * The current inflate code requires 9 bits of lookahead. If the
+ * last two codes for the previous block (real code plus EOB) were coded
+ * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
+ * the last real code. In this case we send two empty static blocks instead
+ * of one. (There are no problems if the previous block is stored or fixed.)
+ * To simplify the code, we assume the worst case of last real code encoded
+ * on one bit only.
+ */
+void _tr_align(s)
+    deflate_state *s;
+{
+    send_bits(s, STATIC_TREES<<1, 3);
+    send_code(s, END_BLOCK, static_ltree);
+#ifdef DEBUG
+    s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
+#endif
+    bi_flush(s);
+    /* Of the 10 bits for the empty block, we have already sent
+     * (10 - bi_valid) bits. The lookahead for the last real code (before
+     * the EOB of the previous block) was thus at least one plus the length
+     * of the EOB plus what we have just sent of the empty static block.
+     */
+    if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
+        send_bits(s, STATIC_TREES<<1, 3);
+        send_code(s, END_BLOCK, static_ltree);
+#ifdef DEBUG
+        s->compressed_len += 10L;
+#endif
+        bi_flush(s);
+    }
+    s->last_eob_len = 7;
+}
+
+/* ===========================================================================
+ * Determine the best encoding for the current block: dynamic trees, static
+ * trees or store, and output the encoded block to the zip file.
+ */
+void _tr_flush_block(s, buf, stored_len, eof)
+    deflate_state *s;
+    charf *buf;       /* input block, or NULL if too old */
+    ulg stored_len;   /* length of input block */
+    int eof;          /* true if this is the last block for a file */
+{
+    ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
+    int max_blindex = 0;  /* index of last bit length code of non zero freq */
+
+    /* Build the Huffman trees unless a stored block is forced */
+    if (s->level > 0) {
+
+        /* Check if the file is binary or text */
+        if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
+            set_data_type(s);
+
+        /* Construct the literal and distance trees */
+        build_tree(s, (tree_desc *)(&(s->l_desc)));
+        Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
+                s->static_len));
+
+        build_tree(s, (tree_desc *)(&(s->d_desc)));
+        Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
+                s->static_len));
+        /* At this point, opt_len and static_len are the total bit lengths of
+         * the compressed block data, excluding the tree representations.
+         */
+
+        /* Build the bit length tree for the above two trees, and get the index
+         * in bl_order of the last bit length code to send.
+         */
+        max_blindex = build_bl_tree(s);
+
+        /* Determine the best encoding. Compute the block lengths in bytes. */
+        opt_lenb = (s->opt_len+3+7)>>3;
+        static_lenb = (s->static_len+3+7)>>3;
+
+        Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
+                opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
+                s->last_lit));
+
+        if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
+
+    } else {
+        Assert(buf != (char*)0, "lost buf");
+        opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
+    }
+
+#ifdef FORCE_STORED
+    if (buf != (char*)0) { /* force stored block */
+#else
+    if (stored_len+4 <= opt_lenb && buf != (char*)0) {
+                       /* 4: two words for the lengths */
+#endif
+        /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
+         * Otherwise we can't have processed more than WSIZE input bytes since
+         * the last block flush, because compression would have been
+         * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
+         * transform a block into a stored block.
+         */
+        _tr_stored_block(s, buf, stored_len, eof);
+
+#ifdef FORCE_STATIC
+    } else if (static_lenb >= 0) { /* force static trees */
+#else
+    } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
+#endif
+        send_bits(s, (STATIC_TREES<<1)+eof, 3);
+        compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
+#ifdef DEBUG
+        s->compressed_len += 3 + s->static_len;
+#endif
+    } else {
+        send_bits(s, (DYN_TREES<<1)+eof, 3);
+        send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
+                       max_blindex+1);
+        compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
+#ifdef DEBUG
+        s->compressed_len += 3 + s->opt_len;
+#endif
+    }
+    Assert (s->compressed_len == s->bits_sent, "bad compressed size");
+    /* The above check is made mod 2^32, for files larger than 512 MB
+     * and uLong implemented on 32 bits.
+     */
+    init_block(s);
+
+    if (eof) {
+        bi_windup(s);
+#ifdef DEBUG
+        s->compressed_len += 7;  /* align on byte boundary */
+#endif
+    }
+    Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
+           s->compressed_len-7*eof));
+}
+
+/* ===========================================================================
+ * Save the match info and tally the frequency counts. Return true if
+ * the current block must be flushed.
+ */
+int _tr_tally (s, dist, lc)
+    deflate_state *s;
+    unsigned dist;  /* distance of matched string */
+    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
+{
+    s->d_buf[s->last_lit] = (ush)dist;
+    s->l_buf[s->last_lit++] = (uch)lc;
+    if (dist == 0) {
+        /* lc is the unmatched char */
+        s->dyn_ltree[lc].Freq++;
+    } else {
+        s->matches++;
+        /* Here, lc is the match length - MIN_MATCH */
+        dist--;             /* dist = match distance - 1 */
+        Assert((ush)dist < (ush)MAX_DIST(s) &&
+               (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
+               (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
+
+        s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
+        s->dyn_dtree[d_code(dist)].Freq++;
+    }
+
+#ifdef TRUNCATE_BLOCK
+    /* Try to guess if it is profitable to stop the current block here */
+    if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
+        /* Compute an upper bound for the compressed length */
+        ulg out_length = (ulg)s->last_lit*8L;
+        ulg in_length = (ulg)((long)s->strstart - s->block_start);
+        int dcode;
+        for (dcode = 0; dcode < D_CODES; dcode++) {
+            out_length += (ulg)s->dyn_dtree[dcode].Freq *
+                (5L+extra_dbits[dcode]);
+        }
+        out_length >>= 3;
+        Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
+               s->last_lit, in_length, out_length,
+               100L - out_length*100L/in_length));
+        if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
+    }
+#endif
+    return (s->last_lit == s->lit_bufsize-1);
+    /* We avoid equality with lit_bufsize because of wraparound at 64K
+     * on 16 bit machines and because stored blocks are restricted to
+     * 64K-1 bytes.
+     */
+}
+
+/* ===========================================================================
+ * Send the block data compressed using the given Huffman trees
+ */
+local void compress_block(s, ltree, dtree)
+    deflate_state *s;
+    ct_data *ltree; /* literal tree */
+    ct_data *dtree; /* distance tree */
+{
+    unsigned dist;      /* distance of matched string */
+    int lc;             /* match length or unmatched char (if dist == 0) */
+    unsigned lx = 0;    /* running index in l_buf */
+    unsigned code;      /* the code to send */
+    int extra;          /* number of extra bits to send */
+
+    if (s->last_lit != 0) do {
+        dist = s->d_buf[lx];
+        lc = s->l_buf[lx++];
+        if (dist == 0) {
+            send_code(s, lc, ltree); /* send a literal byte */
+            Tracecv(isgraph(lc), (stderr," '%c' ", lc));
+        } else {
+            /* Here, lc is the match length - MIN_MATCH */
+            code = _length_code[lc];
+            send_code(s, code+LITERALS+1, ltree); /* send the length code */
+            extra = extra_lbits[code];
+            if (extra != 0) {
+                lc -= base_length[code];
+                send_bits(s, lc, extra);       /* send the extra length bits */
+            }
+            dist--; /* dist is now the match distance - 1 */
+            code = d_code(dist);
+            Assert (code < D_CODES, "bad d_code");
+
+            send_code(s, code, dtree);       /* send the distance code */
+            extra = extra_dbits[code];
+            if (extra != 0) {
+                dist -= base_dist[code];
+                send_bits(s, dist, extra);   /* send the extra distance bits */
+            }
+        } /* literal or match pair ? */
+
+        /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
+        Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
+               "pendingBuf overflow");
+
+    } while (lx < s->last_lit);
+
+    send_code(s, END_BLOCK, ltree);
+    s->last_eob_len = ltree[END_BLOCK].Len;
+}
+
+/* ===========================================================================
+ * Set the data type to BINARY or TEXT, using a crude approximation:
+ * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
+ * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
+ * IN assertion: the fields Freq of dyn_ltree are set.
+ */
+local void set_data_type(s)
+    deflate_state *s;
+{
+    int n;
+
+    for (n = 0; n < 9; n++)
+        if (s->dyn_ltree[n].Freq != 0)
+            break;
+    if (n == 9)
+        for (n = 14; n < 32; n++)
+            if (s->dyn_ltree[n].Freq != 0)
+                break;
+    s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
+}
+
+/* ===========================================================================
+ * Reverse the first len bits of a code, using straightforward code (a faster
+ * method would use a table)
+ * IN assertion: 1 <= len <= 15
+ */
+local unsigned bi_reverse(code, len)
+    unsigned code; /* the value to invert */
+    int len;       /* its bit length */
+{
+    register unsigned res = 0;
+    do {
+        res |= code & 1;
+        code >>= 1, res <<= 1;
+    } while (--len > 0);
+    return res >> 1;
+}
+
+/* ===========================================================================
+ * Flush the bit buffer, keeping at most 7 bits in it.
+ */
+local void bi_flush(s)
+    deflate_state *s;
+{
+    if (s->bi_valid == 16) {
+        put_short(s, s->bi_buf);
+        s->bi_buf = 0;
+        s->bi_valid = 0;
+    } else if (s->bi_valid >= 8) {
+        put_byte(s, (Byte)s->bi_buf);
+        s->bi_buf >>= 8;
+        s->bi_valid -= 8;
+    }
+}
+
+/* ===========================================================================
+ * Flush the bit buffer and align the output on a byte boundary
+ */
+local void bi_windup(s)
+    deflate_state *s;
+{
+    if (s->bi_valid > 8) {
+        put_short(s, s->bi_buf);
+    } else if (s->bi_valid > 0) {
+        put_byte(s, (Byte)s->bi_buf);
+    }
+    s->bi_buf = 0;
+    s->bi_valid = 0;
+#ifdef DEBUG
+    s->bits_sent = (s->bits_sent+7) & ~7;
+#endif
+}
+
+/* ===========================================================================
+ * Copy a stored block, storing first the length and its
+ * one's complement if requested.
+ */
+local void copy_block(s, buf, len, header)
+    deflate_state *s;
+    charf    *buf;    /* the input data */
+    unsigned len;     /* its length */
+    int      header;  /* true if block header must be written */
+{
+    bi_windup(s);        /* align on byte boundary */
+    s->last_eob_len = 8; /* enough lookahead for inflate */
+
+    if (header) {
+        put_short(s, (ush)len);
+        put_short(s, (ush)~len);
+#ifdef DEBUG
+        s->bits_sent += 2*16;
+#endif
+    }
+#ifdef DEBUG
+    s->bits_sent += (ulg)len<<3;
+#endif
+    while (len--) {
+        put_byte(s, *buf++);
+    }
+}
diff --git a/src/engine/external/zlib/trees.h b/src/engine/external/zlib/trees.h
new file mode 100644
index 00000000..72facf90
--- /dev/null
+++ b/src/engine/external/zlib/trees.h
@@ -0,0 +1,128 @@
+/* header created automatically with -DGEN_TREES_H */
+
+local const ct_data static_ltree[L_CODES+2] = {
+{{ 12},{  8}}, {{140},{  8}}, {{ 76},{  8}}, {{204},{  8}}, {{ 44},{  8}},
+{{172},{  8}}, {{108},{  8}}, {{236},{  8}}, {{ 28},{  8}}, {{156},{  8}},
+{{ 92},{  8}}, {{220},{  8}}, {{ 60},{  8}}, {{188},{  8}}, {{124},{  8}},
+{{252},{  8}}, {{  2},{  8}}, {{130},{  8}}, {{ 66},{  8}}, {{194},{  8}},
+{{ 34},{  8}}, {{162},{  8}}, {{ 98},{  8}}, {{226},{  8}}, {{ 18},{  8}},
+{{146},{  8}}, {{ 82},{  8}}, {{210},{  8}}, {{ 50},{  8}}, {{178},{  8}},
+{{114},{  8}}, {{242},{  8}}, {{ 10},{  8}}, {{138},{  8}}, {{ 74},{  8}},
+{{202},{  8}}, {{ 42},{  8}}, {{170},{  8}}, {{106},{  8}}, {{234},{  8}},
+{{ 26},{  8}}, {{154},{  8}}, {{ 90},{  8}}, {{218},{  8}}, {{ 58},{  8}},
+{{186},{  8}}, {{122},{  8}}, {{250},{  8}}, {{  6},{  8}}, {{134},{  8}},
+{{ 70},{  8}}, {{198},{  8}}, {{ 38},{  8}}, {{166},{  8}}, {{102},{  8}},
+{{230},{  8}}, {{ 22},{  8}}, {{150},{  8}}, {{ 86},{  8}}, {{214},{  8}},
+{{ 54},{  8}}, {{182},{  8}}, {{118},{  8}}, {{246},{  8}}, {{ 14},{  8}},
+{{142},{  8}}, {{ 78},{  8}}, {{206},{  8}}, {{ 46},{  8}}, {{174},{  8}},
+{{110},{  8}}, {{238},{  8}}, {{ 30},{  8}}, {{158},{  8}}, {{ 94},{  8}},
+{{222},{  8}}, {{ 62},{  8}}, {{190},{  8}}, {{126},{  8}}, {{254},{  8}},
+{{  1},{  8}}, {{129},{  8}}, {{ 65},{  8}}, {{193},{  8}}, {{ 33},{  8}},
+{{161},{  8}}, {{ 97},{  8}}, {{225},{  8}}, {{ 17},{  8}}, {{145},{  8}},
+{{ 81},{  8}}, {{209},{  8}}, {{ 49},{  8}}, {{177},{  8}}, {{113},{  8}},
+{{241},{  8}}, {{  9},{  8}}, {{137},{  8}}, {{ 73},{  8}}, {{201},{  8}},
+{{ 41},{  8}}, {{169},{  8}}, {{105},{  8}}, {{233},{  8}}, {{ 25},{  8}},
+{{153},{  8}}, {{ 89},{  8}}, {{217},{  8}}, {{ 57},{  8}}, {{185},{  8}},
+{{121},{  8}}, {{249},{  8}}, {{  5},{  8}}, {{133},{  8}}, {{ 69},{  8}},
+{{197},{  8}}, {{ 37},{  8}}, {{165},{  8}}, {{101},{  8}}, {{229},{  8}},
+{{ 21},{  8}}, {{149},{  8}}, {{ 85},{  8}}, {{213},{  8}}, {{ 53},{  8}},
+{{181},{  8}}, {{117},{  8}}, {{245},{  8}}, {{ 13},{  8}}, {{141},{  8}},
+{{ 77},{  8}}, {{205},{  8}}, {{ 45},{  8}}, {{173},{  8}}, {{109},{  8}},
+{{237},{  8}}, {{ 29},{  8}}, {{157},{  8}}, {{ 93},{  8}}, {{221},{  8}},
+{{ 61},{  8}}, {{189},{  8}}, {{125},{  8}}, {{253},{  8}}, {{ 19},{  9}},
+{{275},{  9}}, {{147},{  9}}, {{403},{  9}}, {{ 83},{  9}}, {{339},{  9}},
+{{211},{  9}}, {{467},{  9}}, {{ 51},{  9}}, {{307},{  9}}, {{179},{  9}},
+{{435},{  9}}, {{115},{  9}}, {{371},{  9}}, {{243},{  9}}, {{499},{  9}},
+{{ 11},{  9}}, {{267},{  9}}, {{139},{  9}}, {{395},{  9}}, {{ 75},{  9}},
+{{331},{  9}}, {{203},{  9}}, {{459},{  9}}, {{ 43},{  9}}, {{299},{  9}},
+{{171},{  9}}, {{427},{  9}}, {{107},{  9}}, {{363},{  9}}, {{235},{  9}},
+{{491},{  9}}, {{ 27},{  9}}, {{283},{  9}}, {{155},{  9}}, {{411},{  9}},
+{{ 91},{  9}}, {{347},{  9}}, {{219},{  9}}, {{475},{  9}}, {{ 59},{  9}},
+{{315},{  9}}, {{187},{  9}}, {{443},{  9}}, {{123},{  9}}, {{379},{  9}},
+{{251},{  9}}, {{507},{  9}}, {{  7},{  9}}, {{263},{  9}}, {{135},{  9}},
+{{391},{  9}}, {{ 71},{  9}}, {{327},{  9}}, {{199},{  9}}, {{455},{  9}},
+{{ 39},{  9}}, {{295},{  9}}, {{167},{  9}}, {{423},{  9}}, {{103},{  9}},
+{{359},{  9}}, {{231},{  9}}, {{487},{  9}}, {{ 23},{  9}}, {{279},{  9}},
+{{151},{  9}}, {{407},{  9}}, {{ 87},{  9}}, {{343},{  9}}, {{215},{  9}},
+{{471},{  9}}, {{ 55},{  9}}, {{311},{  9}}, {{183},{  9}}, {{439},{  9}},
+{{119},{  9}}, {{375},{  9}}, {{247},{  9}}, {{503},{  9}}, {{ 15},{  9}},
+{{271},{  9}}, {{143},{  9}}, {{399},{  9}}, {{ 79},{  9}}, {{335},{  9}},
+{{207},{  9}}, {{463},{  9}}, {{ 47},{  9}}, {{303},{  9}}, {{175},{  9}},
+{{431},{  9}}, {{111},{  9}}, {{367},{  9}}, {{239},{  9}}, {{495},{  9}},
+{{ 31},{  9}}, {{287},{  9}}, {{159},{  9}}, {{415},{  9}}, {{ 95},{  9}},
+{{351},{  9}}, {{223},{  9}}, {{479},{  9}}, {{ 63},{  9}}, {{319},{  9}},
+{{191},{  9}}, {{447},{  9}}, {{127},{  9}}, {{383},{  9}}, {{255},{  9}},
+{{511},{  9}}, {{  0},{  7}}, {{ 64},{  7}}, {{ 32},{  7}}, {{ 96},{  7}},
+{{ 16},{  7}}, {{ 80},{  7}}, {{ 48},{  7}}, {{112},{  7}}, {{  8},{  7}},
+{{ 72},{  7}}, {{ 40},{  7}}, {{104},{  7}}, {{ 24},{  7}}, {{ 88},{  7}},
+{{ 56},{  7}}, {{120},{  7}}, {{  4},{  7}}, {{ 68},{  7}}, {{ 36},{  7}},
+{{100},{  7}}, {{ 20},{  7}}, {{ 84},{  7}}, {{ 52},{  7}}, {{116},{  7}},
+{{  3},{  8}}, {{131},{  8}}, {{ 67},{  8}}, {{195},{  8}}, {{ 35},{  8}},
+{{163},{  8}}, {{ 99},{  8}}, {{227},{  8}}
+};
+
+local const ct_data static_dtree[D_CODES] = {
+{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
+{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
+{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
+{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
+{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
+{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
+};
+
+const uch _dist_code[DIST_CODE_LEN] = {
+ 0,  1,  2,  3,  4,  4,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  8,
+ 8,  8,  8,  8,  9,  9,  9,  9,  9,  9,  9,  9, 10, 10, 10, 10, 10, 10, 10, 10,
+10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
+13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
+15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,  0,  0, 16, 17,
+18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
+23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
+26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
+27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
+27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
+28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
+28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
+28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
+29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
+29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
+29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
+};
+
+const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
+ 0,  1,  2,  3,  4,  5,  6,  7,  8,  8,  9,  9, 10, 10, 11, 11, 12, 12, 12, 12,
+13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
+17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
+19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
+22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
+23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
+26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
+26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
+27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
+};
+
+local const int base_length[LENGTH_CODES] = {
+0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
+64, 80, 96, 112, 128, 160, 192, 224, 0
+};
+
+local const int base_dist[D_CODES] = {
+    0,     1,     2,     3,     4,     6,     8,    12,    16,    24,
+   32,    48,    64,    96,   128,   192,   256,   384,   512,   768,
+ 1024,  1536,  2048,  3072,  4096,  6144,  8192, 12288, 16384, 24576
+};
+
diff --git a/src/engine/external/zlib/uncompr.c b/src/engine/external/zlib/uncompr.c
new file mode 100644
index 00000000..b59e3d0d
--- /dev/null
+++ b/src/engine/external/zlib/uncompr.c
@@ -0,0 +1,61 @@
+/* uncompr.c -- decompress a memory buffer
+ * Copyright (C) 1995-2003 Jean-loup Gailly.
+ * 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 actual size of the compressed buffer.
+     This function can be used to decompress a whole file at once if the
+   input file is mmap'ed.
+
+     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.
+*/
+int ZEXPORT uncompress (dest, destLen, source, sourceLen)
+    Bytef *dest;
+    uLongf *destLen;
+    const Bytef *source;
+    uLong sourceLen;
+{
+    z_stream stream;
+    int err;
+
+    stream.next_in = (Bytef*)source;
+    stream.avail_in = (uInt)sourceLen;
+    /* Check for source > 64K on 16-bit machine: */
+    if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
+
+    stream.next_out = dest;
+    stream.avail_out = (uInt)*destLen;
+    if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
+
+    stream.zalloc = (alloc_func)0;
+    stream.zfree = (free_func)0;
+
+    err = inflateInit(&stream);
+    if (err != Z_OK) return err;
+
+    err = inflate(&stream, Z_FINISH);
+    if (err != Z_STREAM_END) {
+        inflateEnd(&stream);
+        if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0))
+            return Z_DATA_ERROR;
+        return err;
+    }
+    *destLen = stream.total_out;
+
+    err = inflateEnd(&stream);
+    return err;
+}
diff --git a/src/engine/external/zlib/zconf.h b/src/engine/external/zlib/zconf.h
new file mode 100644
index 00000000..03a9431c
--- /dev/null
+++ b/src/engine/external/zlib/zconf.h
@@ -0,0 +1,332 @@
+/* zconf.h -- configuration of the zlib compression library
+ * Copyright (C) 1995-2005 Jean-loup Gailly.
+ * 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.
+ */
+#ifdef Z_PREFIX
+#  define deflateInit_          z_deflateInit_
+#  define deflate               z_deflate
+#  define deflateEnd            z_deflateEnd
+#  define inflateInit_          z_inflateInit_
+#  define inflate               z_inflate
+#  define inflateEnd            z_inflateEnd
+#  define deflateInit2_         z_deflateInit2_
+#  define deflateSetDictionary  z_deflateSetDictionary
+#  define deflateCopy           z_deflateCopy
+#  define deflateReset          z_deflateReset
+#  define deflateParams         z_deflateParams
+#  define deflateBound          z_deflateBound
+#  define deflatePrime          z_deflatePrime
+#  define inflateInit2_         z_inflateInit2_
+#  define inflateSetDictionary  z_inflateSetDictionary
+#  define inflateSync           z_inflateSync
+#  define inflateSyncPoint      z_inflateSyncPoint
+#  define inflateCopy           z_inflateCopy
+#  define inflateReset          z_inflateReset
+#  define inflateBack           z_inflateBack
+#  define inflateBackEnd        z_inflateBackEnd
+#  define compress              z_compress
+#  define compress2             z_compress2
+#  define compressBound         z_compressBound
+#  define uncompress            z_uncompress
+#  define adler32               z_adler32
+#  define crc32                 z_crc32
+#  define get_crc_table         z_get_crc_table
+#  define zError                z_zError
+
+#  define alloc_func            z_alloc_func
+#  define free_func             z_free_func
+#  define in_func               z_in_func
+#  define out_func              z_out_func
+#  define Byte                  z_Byte
+#  define uInt                  z_uInt
+#  define uLong                 z_uLong
+#  define Bytef                 z_Bytef
+#  define charf                 z_charf
+#  define intf                  z_intf
+#  define uIntf                 z_uIntf
+#  define uLongf                z_uLongf
+#  define voidpf                z_voidpf
+#  define voidp                 z_voidp
+#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
+
+/* Some Mac compilers merge all .h files incorrectly: */
+#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
+#  define NO_DUMMY_DECL
+#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 a few kilobytes
+ for small objects.
+*/
+
+                        /* Type declarations */
+
+#ifndef OF /* function prototypes */
+#  ifdef STDC
+#    define OF(args)  args
+#  else
+#    define OF(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 0           /* HAVE_UNISTD_H -- this line is updated by ./configure */
+#  include <sys/types.h> /* for off_t */
+#  include <unistd.h>    /* for SEEK_* and off_t */
+#  ifdef VMS
+#    include <unixio.h>   /* for off_t */
+#  endif
+#  define z_off_t off_t
+#endif
+#ifndef SEEK_SET
+#  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(__OS400__)
+#  define NO_vsnprintf
+#endif
+
+#if defined(__MVS__)
+#  define NO_vsnprintf
+#  ifdef FAR
+#    undef FAR
+#  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 */
diff --git a/src/engine/external/zlib/zconf.in.h b/src/engine/external/zlib/zconf.in.h
new file mode 100644
index 00000000..03a9431c
--- /dev/null
+++ b/src/engine/external/zlib/zconf.in.h
@@ -0,0 +1,332 @@
+/* zconf.h -- configuration of the zlib compression library
+ * Copyright (C) 1995-2005 Jean-loup Gailly.
+ * 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.
+ */
+#ifdef Z_PREFIX
+#  define deflateInit_          z_deflateInit_
+#  define deflate               z_deflate
+#  define deflateEnd            z_deflateEnd
+#  define inflateInit_          z_inflateInit_
+#  define inflate               z_inflate
+#  define inflateEnd            z_inflateEnd
+#  define deflateInit2_         z_deflateInit2_
+#  define deflateSetDictionary  z_deflateSetDictionary
+#  define deflateCopy           z_deflateCopy
+#  define deflateReset          z_deflateReset
+#  define deflateParams         z_deflateParams
+#  define deflateBound          z_deflateBound
+#  define deflatePrime          z_deflatePrime
+#  define inflateInit2_         z_inflateInit2_
+#  define inflateSetDictionary  z_inflateSetDictionary
+#  define inflateSync           z_inflateSync
+#  define inflateSyncPoint      z_inflateSyncPoint
+#  define inflateCopy           z_inflateCopy
+#  define inflateReset          z_inflateReset
+#  define inflateBack           z_inflateBack
+#  define inflateBackEnd        z_inflateBackEnd
+#  define compress              z_compress
+#  define compress2             z_compress2
+#  define compressBound         z_compressBound
+#  define uncompress            z_uncompress
+#  define adler32               z_adler32
+#  define crc32                 z_crc32
+#  define get_crc_table         z_get_crc_table
+#  define zError                z_zError
+
+#  define alloc_func            z_alloc_func
+#  define free_func             z_free_func
+#  define in_func               z_in_func
+#  define out_func              z_out_func
+#  define Byte                  z_Byte
+#  define uInt                  z_uInt
+#  define uLong                 z_uLong
+#  define Bytef                 z_Bytef
+#  define charf                 z_charf
+#  define intf                  z_intf
+#  define uIntf                 z_uIntf
+#  define uLongf                z_uLongf
+#  define voidpf                z_voidpf
+#  define voidp                 z_voidp
+#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
+
+/* Some Mac compilers merge all .h files incorrectly: */
+#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
+#  define NO_DUMMY_DECL
+#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 a few kilobytes
+ for small objects.
+*/
+
+                        /* Type declarations */
+
+#ifndef OF /* function prototypes */
+#  ifdef STDC
+#    define OF(args)  args
+#  else
+#    define OF(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 0           /* HAVE_UNISTD_H -- this line is updated by ./configure */
+#  include <sys/types.h> /* for off_t */
+#  include <unistd.h>    /* for SEEK_* and off_t */
+#  ifdef VMS
+#    include <unixio.h>   /* for off_t */
+#  endif
+#  define z_off_t off_t
+#endif
+#ifndef SEEK_SET
+#  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(__OS400__)
+#  define NO_vsnprintf
+#endif
+
+#if defined(__MVS__)
+#  define NO_vsnprintf
+#  ifdef FAR
+#    undef FAR
+#  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 */
diff --git a/src/engine/external/zlib/zlib.h b/src/engine/external/zlib/zlib.h
new file mode 100644
index 00000000..02281792
--- /dev/null
+++ b/src/engine/external/zlib/zlib.h
@@ -0,0 +1,1357 @@
+/* zlib.h -- interface of the 'zlib' general purpose compression library
+  version 1.2.3, July 18th, 2005
+
+  Copyright (C) 1995-2005 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://www.ietf.org/rfc/rfc1950.txt
+  (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
+*/
+
+#ifndef ZLIB_H
+#define ZLIB_H
+
+#include "zconf.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define ZLIB_VERSION "1.2.3"
+#define ZLIB_VERNUM 0x1230
+
+/*
+     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 (for example if an input file is mmap'ed), 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 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 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 {
+    Bytef    *next_in;  /* next input byte */
+    uInt     avail_in;  /* number of bytes available at next_in */
+    uLong    total_in;  /* total nb of input bytes read so far */
+
+    Bytef    *next_out; /* next output byte should be put there */
+    uInt     avail_out; /* remaining free space at next_out */
+    uLong    total_out; /* total nb of bytes output so far */
+
+    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 */
+    uLong   adler;      /* adler32 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.
+
+   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 in 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 /* will be removed, use Z_SYNC_FLUSH instead */
+#define Z_SYNC_FLUSH    2
+#define Z_FULL_FLUSH    3
+#define Z_FINISH        4
+#define Z_BLOCK         5
+/* 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 (though see inflate()) */
+
+#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,
+   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().
+
+  - Provide 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 (in interactive applications).
+    Some output may be provided even if flush is not set.
+
+  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.
+
+    Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
+  decide how much data to accumualte 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.
+
+    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, 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 immediately after deflateInit if all the compression
+  is to be done in a single step. In this case, avail_out must be at least
+  the value returned by deflateBound (see below). If deflate does not return
+  Z_STREAM_END, then it must be called again as described above.
+
+    deflate() sets strm->adler to the adler32 checksum of all input read
+  so far (that is, total_in bytes).
+
+    deflate() may update strm->data_type if it can make a good guess about
+  the input data type (Z_BINARY or Z_TEXT). 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 NULL), 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. If next_in is not Z_NULL and avail_in is large enough (the exact
+   value depends on the compression method), inflateInit determines the
+   compression method from the zlib header and allocates all data structures
+   accordingly; otherwise the allocation will be deferred to the first call of
+   inflate.  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.  msg is set to null if there is no error
+   message. inflateInit does not perform any decompression apart from reading
+   the zlib header if present: this will be done by inflate().  (So next_in and
+   avail_in may be modified, but next_out and avail_out are unchanged.)
+*/
+
+
+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), next_in is updated and processing
+    will resume at this point for the next call of inflate().
+
+  - Provide 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.
+  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, or Z_BLOCK. 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.
+  Also to assist in this, on return inflate() will set 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.
+
+    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 the
+  uncompressed data. (The size of the uncompressed data may have been saved
+  by the compressor for this purpose.) The next operation on this stream must
+  be inflateEnd to deallocate the decompression state. The use of Z_FINISH
+  is never required, but can be used to inform inflate that a faster approach
+  may be used for the single inflate() call.
+
+     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 only effect of the flush parameter in this implementation
+  is on the return value of inflate(), as noted below, or when it returns early
+  because Z_BLOCK is used.
+
+     If a preset dictionary is needed after this call (see inflateSetDictionary
+  below), inflate sets strm->adler to the adler32 checksum of the dictionary
+  chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
+  strm->adler to the adler32 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 adler32
+  checksum is equal to that saved by the compressor and returns Z_STREAM_END
+  only if the checksum is correct.
+
+    inflate() will decompress and check either zlib-wrapped or gzip-wrapped
+  deflate data.  The header type is detected automatically.  Any information
+  contained in the gzip header is not retained, so applications that need that
+  information should instead use raw inflate, see inflateInit2() below, or
+  inflateBack() and perform their own processing of the gzip header and
+  trailer.
+
+    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), Z_STREAM_ERROR if the stream structure was inconsistent (for example
+  if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
+  Z_BUF_ERROR if no progress is 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 desired.
+*/
+
+
+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, Z_STREAM_ERROR if the stream state
+   was inconsistent. In the error case, msg may be set but then points to a
+   static string (which must not be deallocated).
+*/
+
+                        /* 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.
+
+     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 an adler32 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 255 (unknown).  If a
+   gzip stream is being written, strm->adler is a crc32 instead of an adler32.
+
+     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 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 a parameter is invalid (such as an invalid
+   method). 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. This function must be called
+   immediately after deflateInit, deflateInit2 or deflateReset, before any
+   call of deflate. 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 in
+   deflate or deflate2. 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 adler32 value
+   of the dictionary; the decompressor may later use this value to determine
+   which dictionary has been used by the compressor. (The adler32 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
+   adler32 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 (such as NULL dictionary) or the stream state is
+   inconsistent (for example if deflate has already been called for this stream
+   or if the compression method is bsort). deflateSetDictionary does not
+   perform any compression: this will be done by deflate().
+*/
+
+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 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 all the internal compression state.
+   The stream will keep the same compression level and any other attributes
+   that may have been set by deflateInit2.
+
+      deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent (such as zalloc or state being 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 level is changed, the input available so far
+   is compressed with the old level (and may be flushed); the new level will
+   take effect only at the next call of deflate().
+
+     Before the call of deflateParams, the stream state must be set as for
+   a call of deflate(), since the currently available input may have to
+   be compressed and flushed. In particular, strm->avail_out must be non-zero.
+
+     deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
+   stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
+   if strm->avail_out was zero.
+*/
+
+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().  This would be used to allocate an output buffer
+   for deflation in a single pass, and so would be called before deflate().
+*/
+
+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, 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 -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 adler32 or a crc32 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 crc32 instead of an adler32.
+
+     inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
+   is set to null if there is no error message.  inflateInit2 does not perform
+   any decompression apart from reading the zlib header if present: this will
+   be done by inflate(). (So next_in and avail_in may be modified, but next_out
+   and avail_out are unchanged.)
+*/
+
+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 adler32 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
+   immediately after inflateInit2() or inflateReset() and before any call of
+   inflate() to set the dictionary.  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 (such as NULL dictionary) or the stream state is
+   inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
+   expected one (incorrect adler32 value). inflateSetDictionary does not
+   perform any decompression: this will be done by subsequent calls of
+   inflate().
+*/
+
+ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
+/*
+    Skips invalid compressed data until a full flush point (see above the
+  description of deflate with Z_FULL_FLUSH) can be found, or until all
+  available input is skipped. No output is provided.
+
+    inflateSync returns Z_OK if a 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 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 all 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 NULL).
+*/
+
+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.
+
+      inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the 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 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 paramaters 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 *, 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 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.  This
+   function 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
+   normal behavior of inflate(), which expects either a zlib or gzip 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 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: 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)
+ */
+
+
+                        /* 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 easily 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 buffer.
+     This function can be used to compress a whole file at once if the
+   input file is mmap'ed.
+     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 buffer.
+
+     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 compressed buffer.
+     This function can be used to decompress a whole file at once if the
+   input file is mmap'ed.
+
+     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.
+*/
+
+
+typedef voidp gzFile;
+
+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", or 'R' for run-length encoding
+   as in "wb1R". (See the description of deflateInit2 for more information
+   about the strategy parameter.)
+
+     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.
+
+     gzopen returns NULL if the file could not be opened or if there was
+   insufficient memory to allocate the (de)compression state; errno
+   can be checked to distinguish the two cases (if errno is zero, the
+   zlib error is Z_MEM_ERROR).  */
+
+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 (in 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 gzdopen(dup(fd), mode).
+     gzdopen returns NULL if there was insufficient memory to allocate
+   the (de)compression state.
+*/
+
+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.
+     gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
+   opened for writing.
+*/
+
+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 was not in gzip format, gzread copies the given number
+   of bytes into the buffer.
+     gzread returns the number of uncompressed bytes actually read (0 for
+   end of file, -1 for error). */
+
+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 actually written
+   (0 in case of error).
+*/
+
+ZEXTERN int ZEXPORTVA   gzprintf OF((gzFile file, const char *format, ...));
+/*
+     Converts, formats, and writes the args to the compressed file under
+   control of the format string, as in fprintf. gzprintf returns the number of
+   uncompressed bytes actually written (0 in case of error).  The number of
+   uncompressed bytes written is limited to 4095. The caller should assure that
+   this limit is not exceeded. If it is exceeded, then gzprintf() will return
+   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.
+*/
+
+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.  The string is then terminated with a null
+   character.
+      gzgets returns buf, or Z_NULL in case of error.
+*/
+
+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.
+*/
+
+ZEXTERN int ZEXPORT    gzungetc OF((int c, gzFile file));
+/*
+      Push one character back onto the stream to be read again later.
+   Only one character of push-back is allowed.  gzungetc() returns the
+   character pushed, or -1 on failure.  gzungetc() will fail if a
+   character has been pushed but not read yet, or if c is -1. 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 returns Z_OK if
+   the flush parameter is Z_FINISH and all output could be flushed.
+     gzflush should be called only when strictly necessary because it can
+   degrade compression.
+*/
+
+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.
+
+   gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
+*/
+
+ZEXTERN int ZEXPORT gzeof OF((gzFile file));
+/*
+     Returns 1 when EOF has previously been detected reading the given
+   input stream, otherwise zero.
+*/
+
+ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
+/*
+     Returns 1 if file is being read directly without decompression, otherwise
+   zero.
+*/
+
+ZEXTERN int ZEXPORT    gzclose OF((gzFile file));
+/*
+     Flushes all pending output if necessary, closes the compressed file
+   and deallocates all the (de)compression state. The return value is the zlib
+   error number (see function gzerror below).
+*/
+
+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.
+*/
+
+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.
+*/
+
+                        /* 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 NULL, this function returns
+   the required initial value for the checksum.
+   An Adler-32 checksum is almost as reliable as a CRC32 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_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.
+*/
+
+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 NULL, this function returns the required initial
+   value for the 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_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));
+#define deflateInit(strm, level) \
+        deflateInit_((strm), (level),       ZLIB_VERSION, sizeof(z_stream))
+#define inflateInit(strm) \
+        inflateInit_((strm),                ZLIB_VERSION, sizeof(z_stream))
+#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
+        deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
+                      (strategy),           ZLIB_VERSION, sizeof(z_stream))
+#define inflateInit2(strm, windowBits) \
+        inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
+#define inflateBackInit(strm, windowBits, window) \
+        inflateBackInit_((strm), (windowBits), (window), \
+        ZLIB_VERSION, sizeof(z_stream))
+
+
+#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
+    struct internal_state {int dummy;}; /* hack for buggy compilers */
+#endif
+
+ZEXTERN const char   * ZEXPORT zError           OF((int));
+ZEXTERN int            ZEXPORT inflateSyncPoint OF((z_streamp z));
+ZEXTERN const uLongf * ZEXPORT get_crc_table    OF((void));
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ZLIB_H */
diff --git a/src/engine/external/zlib/zutil.c b/src/engine/external/zlib/zutil.c
new file mode 100644
index 00000000..d55f5948
--- /dev/null
+++ b/src/engine/external/zlib/zutil.c
@@ -0,0 +1,318 @@
+/* zutil.c -- target dependent utility functions for the compression library
+ * Copyright (C) 1995-2005 Jean-loup Gailly.
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* @(#) $Id$ */
+
+#include "zutil.h"
+
+#ifndef NO_DUMMY_DECL
+struct internal_state      {int dummy;}; /* for buggy compilers */
+#endif
+
+const char * const z_errmsg[10] = {
+"need dictionary",     /* Z_NEED_DICT       2  */
+"stream end",          /* Z_STREAM_END      1  */
+"",                    /* Z_OK              0  */
+"file error",          /* Z_ERRNO         (-1) */
+"stream error",        /* Z_STREAM_ERROR  (-2) */
+"data error",          /* Z_DATA_ERROR    (-3) */
+"insufficient memory", /* Z_MEM_ERROR     (-4) */
+"buffer error",        /* Z_BUF_ERROR     (-5) */
+"incompatible version",/* Z_VERSION_ERROR (-6) */
+""};
+
+
+const char * ZEXPORT zlibVersion()
+{
+    return ZLIB_VERSION;
+}
+
+uLong ZEXPORT zlibCompileFlags()
+{
+    uLong flags;
+
+    flags = 0;
+    switch (sizeof(uInt)) {
+    case 2:     break;
+    case 4:     flags += 1;     break;
+    case 8:     flags += 2;     break;
+    default:    flags += 3;
+    }
+    switch (sizeof(uLong)) {
+    case 2:     break;
+    case 4:     flags += 1 << 2;        break;
+    case 8:     flags += 2 << 2;        break;
+    default:    flags += 3 << 2;
+    }
+    switch (sizeof(voidpf)) {
+    case 2:     break;
+    case 4:     flags += 1 << 4;        break;
+    case 8:     flags += 2 << 4;        break;
+    default:    flags += 3 << 4;
+    }
+    switch (sizeof(z_off_t)) {
+    case 2:     break;
+    case 4:     flags += 1 << 6;        break;
+    case 8:     flags += 2 << 6;        break;
+    default:    flags += 3 << 6;
+    }
+#ifdef 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
+#ifdef STDC
+#  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 DEBUG
+
+#  ifndef verbose
+#    define verbose 0
+#  endif
+int z_verbose = verbose;
+
+void 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 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 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 zmemzero(dest, len)
+    Bytef* dest;
+    uInt  len;
+{
+    if (len == 0) return;
+    do {
+        *dest++ = 0;  /* ??? to be unrolled */
+    } while (--len != 0);
+}
+#endif
+
+
+#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 zcalloc (voidpf opaque, unsigned items, unsigned size)
+{
+    voidpf buf = opaque; /* just to make some compilers happy */
+    ulg bsize = (ulg)items*size;
+
+    /* 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  zcfree (voidpf opaque, voidpf ptr)
+{
+    int n;
+    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;
+    }
+    ptr = opaque; /* just to make some compilers happy */
+    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 zcalloc (voidpf opaque, unsigned items, unsigned size)
+{
+    if (opaque) opaque = 0; /* to make compiler happy */
+    return _halloc((long)items, size);
+}
+
+void  zcfree (voidpf opaque, voidpf ptr)
+{
+    if (opaque) opaque = 0; /* to make compiler happy */
+    _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 zcalloc (opaque, items, size)
+    voidpf opaque;
+    unsigned items;
+    unsigned size;
+{
+    if (opaque) items += size - size; /* make compiler happy */
+    return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
+                              (voidpf)calloc(items, size);
+}
+
+void  zcfree (opaque, ptr)
+    voidpf opaque;
+    voidpf ptr;
+{
+    free(ptr);
+    if (opaque) return; /* make compiler happy */
+}
+
+#endif /* MY_ZCALLOC */
diff --git a/src/engine/external/zlib/zutil.h b/src/engine/external/zlib/zutil.h
new file mode 100644
index 00000000..b7d5eff8
--- /dev/null
+++ b/src/engine/external/zlib/zutil.h
@@ -0,0 +1,269 @@
+/* zutil.h -- internal interface and configuration of the compression library
+ * Copyright (C) 1995-2005 Jean-loup Gailly.
+ * 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
+
+#define ZLIB_INTERNAL
+#include "zlib.h"
+
+#ifdef STDC
+#  ifndef _WIN32_WCE
+#    include <stddef.h>
+#  endif
+#  include <string.h>
+#  include <stdlib.h>
+#endif
+#ifdef NO_ERRNO_H
+#   ifdef _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.  We rename it to
+       * avoid conflict with other libraries that use the same workaround.
+       */
+#     define errno z_errno
+#   endif
+    extern int errno;
+#else
+#  ifndef _WIN32_WCE
+#    include <errno.h>
+#  endif
+#endif
+
+#ifndef local
+#  define local static
+#endif
+/* 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 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 = (char*)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
+#  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
+
+#ifdef AMIGA
+#  define OS_CODE  0x01
+#endif
+
+#if defined(VAXC) || defined(VMS)
+#  define OS_CODE  0x02
+#  define F_OPEN(name, mode) \
+     fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
+#endif
+
+#if defined(ATARI) || defined(atarist)
+#  define OS_CODE  0x05
+#endif
+
+#ifdef OS2
+#  define OS_CODE  0x06
+#  ifdef M_I86
+     #include <malloc.h>
+#  endif
+#endif
+
+#if defined(MACOS) || defined(TARGET_OS_MAC)
+#  define OS_CODE  0x07
+#  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
+
+#ifdef TOPS20
+#  define OS_CODE  0x0a
+#endif
+
+#ifdef WIN32
+#  ifndef __CYGWIN__  /* Cygwin is Unix, not Win32 */
+#    define OS_CODE  0x0b
+#  endif
+#endif
+
+#ifdef __50SERIES /* Prime/PRIMOS */
+#  define OS_CODE  0x0f
+#endif
+
+#if defined(_BEOS_) || defined(RISCOS)
+#  define fdopen(fd,mode) NULL /* No fdopen() */
+#endif
+
+#if (defined(_MSC_VER) && (_MSC_VER > 600))
+#  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
+
+        /* common defaults */
+
+#ifndef OS_CODE
+#  define OS_CODE  0x03  /* assume Unix */
+#endif
+
+#ifndef F_OPEN
+#  define F_OPEN(name, mode) fopen((name), (mode))
+#endif
+
+         /* functions */
+
+#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
+#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)
+#      define vsnprintf _vsnprintf
+#    endif
+#  endif
+#  ifdef __SASC
+#    define NO_vsnprintf
+#  endif
+#endif
+#ifdef VMS
+#  define NO_vsnprintf
+#endif
+
+#if defined(pyr)
+#  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
+   extern void zmemcpy  OF((Bytef* dest, const Bytef* source, uInt len));
+   extern int  zmemcmp  OF((const Bytef* s1, const Bytef* s2, uInt len));
+   extern void zmemzero OF((Bytef* dest, uInt len));
+#endif
+
+/* Diagnostic functions */
+#ifdef DEBUG
+#  include <stdio.h>
+   extern int z_verbose;
+   extern void 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
+
+
+voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
+void   zcfree  OF((voidpf opaque, voidpf ptr));
+
+#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);}
+
+#endif /* ZUTIL_H */
diff --git a/src/engine/interface.h b/src/engine/interface.h
index 31b985b7..1e98f267 100644
--- a/src/engine/interface.h
+++ b/src/engine/interface.h
@@ -1,17 +1,20 @@
-#ifndef FILE_INTERFACE_H
-#define FILE_INTERFACE_H
+#ifndef ENGINE_INTERFACE_H
+#define ENGINE_INTERFACE_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
 
 /*
 	Title: Engine Interface
 */
 
-// TODO: Move the definitions of these keys here
-#include <baselib/input.h>
+#include "keys.h"
 
 enum
 {
 	MAX_CLIENTS=8,
-	SERVER_TICK_SPEED=50,
+	SERVER_TICK_SPEED=50, /* TODO: this should be removed */
 	SNAP_CURRENT=0,
 	SNAP_PREV=1,
 	
@@ -25,51 +28,59 @@ enum
 	CLIENTSTATE_QUITING,
 };
 
-struct snap_item
+typedef struct
 {
 	int type;
 	int id;
-};
+} SNAP_ITEM;
 
-struct client_info
+typedef struct
 {
-public:
 	const char *name;
 	int latency;
-};
+} CLIENT_INFO;
 
-struct image_info
+typedef struct
 {
 	int width, height;
 	int format;
 	void *data;
-};
+} IMAGE_INFO;
 
-struct video_mode
+typedef struct 
 {
 	int width, height;
 	int red, green, blue;
-};
+} VIDEO_MODE;
 
-int gfx_load_tga(image_info *img, const char *filename);
-int gfx_load_png(image_info *img, const char *filename);
+typedef struct
+{
+	int max_players;
+	int num_players;
+	int latency; /* in ms */
+	char name[128];
+	char map[128];
+	char address[128];
+} SERVER_INFO;
+
+/* image loaders */
+int gfx_load_png(IMAGE_INFO *img, const char *filename);
 
 
 /*
 	Group: Graphics
 */
 
-// graphics
-bool gfx_init(); // NOT EXPOSED
-void gfx_shutdown(); // NOT EXPOSED
-void gfx_swap(); // NOT EXPOSED
+int gfx_init();
+void gfx_shutdown();
+void gfx_swap();
 
-int gfx_get_video_modes(video_mode *list, int maxcount);
+int gfx_get_video_modes(VIDEO_MODE *list, int maxcount);
 void gfx_set_vsync(int val);
 
 int gfx_window_active();
 
-// textures
+/* textures */
 /*
 	Function: gfx_load_texture
 		Loads a texture from a file. TGA and PNG supported.
@@ -105,7 +116,7 @@ int gfx_load_texture(const char *filename);
 		<gfx_unload_texture>
 */
 int gfx_load_texture_raw(int w, int h, int format, const void *data);
-//int gfx_load_mip_texture_raw(int w, int h, int format, const void *data);
+/*int gfx_load_mip_texture_raw(int w, int h, int format, const void *data);*/
 
 /*
 	Function: gfx_texture_set
@@ -129,7 +140,7 @@ void gfx_texture_set(int id);
 	Remarks:
 		NOT IMPLEMENTED
 */
-int gfx_unload_texture(int id); // NOT IMPLEMENTED
+int gfx_unload_texture(int id);
 
 void gfx_clear(float r, float g, float b);
 
@@ -318,22 +329,22 @@ void gfx_quads_draw_freeform(
 
 void gfx_quads_text(float x, float y, float size, const char *text);
 
-// sound (client)
+/* sound (client) */
 enum
 {
 	SND_PLAY_ONCE = 0,
 	SND_LOOP
 };
 	
-bool snd_init();
+int snd_init();
 float snd_get_master_volume();
 void snd_set_master_volume(float val);
 int snd_load_wav(const char *filename);
 int snd_load_wv(const char *filename);
-int snd_play(int sound, int loop = SND_PLAY_ONCE, float vol = 1.0f, float pan = 0.0f);
+int snd_play(int sound, int loop, float vol, float pan);
 void snd_stop(int id);
 void snd_set_vol(int id, float vol);
-bool snd_shutdown();
+int snd_shutdown();
 
 /*
 	Group: Input
@@ -362,7 +373,7 @@ int inp_mouse_scroll();
 		Returns 1 if the button is pressed, otherwise 0.
 	
 	Remarks:
-		Check baselib/include/baselib/keys.h for the keys.
+		Check keys.h for the keys.
 */
 int inp_key_pressed(int key);
 
@@ -370,8 +381,8 @@ int inp_key_pressed(int key);
 	Group: Map
 */
 
-int map_load(const char *mapname); // NOT EXPOSED
-void map_unload(); // NOT EXPOSED
+int map_load(const char *mapname);
+void map_unload();
 
 /*
 	Function: map_is_loaded
@@ -497,7 +508,7 @@ int snap_num_items(int snapid);
 	Returns:
 		Returns a pointer to the item if it exists, otherwise NULL.
 */
-const void *snap_get_item(int snapid, int index, snap_item *item);
+const void *snap_get_item(int snapid, int index, SNAP_ITEM *item);
 
 /*
 	Function: snap_find_item
@@ -530,19 +541,6 @@ const void *snap_find_item(int snapid, int type, int id);
 void snap_input(void *data, int size);
 
 /*
-	Function: snap_intratick
-		Returns the intra-tick mixing value.
-
-	Returns:
-		Returns the mixing value between the previous snapshot
-		and the current snapshot. 
-
-	Remarks:
-		DOCTODO: Explain how to use it.
-*/
-//float snap_intratick();
-
-/*
 	Group: Server Callbacks
 */
 /*
@@ -680,8 +678,6 @@ void modc_render();
 */
 void modc_statechange(int new_state, int old_state);
 
-
-
 /*
     Group: Menu Callbacks
 */
@@ -705,27 +701,33 @@ void modmenu_shutdown();
     Function: modmenu_render
         Called every frame to let the menu render it self.
 */
-int modmenu_render(bool ingame);
+int modmenu_render(int ingame);
 
 
+/* undocumented callbacks */
+void modc_message(int msg);
+void mods_message(int msg, int client_id);
 
-
-
-
-//void snap_encode_string(const char *src, int *dst, int length, int max_length);
-//void snap_decode_string(const int *src, char *dst, int length);
-
-int server_getclientinfo(int client_id, client_info *info);
+/* server */
+int server_getclientinfo(int client_id, CLIENT_INFO *info);
 int server_tick();
 int server_tickspeed();
 
+/* input */
 int inp_key_was_pressed(int key);
 int inp_key_down(int key);
+char inp_last_char();
+int inp_last_key();
+void inp_clear();
 void inp_update();
-float client_frametime();
-float client_localtime();
+void inp_init();
+void inp_mouse_mode_absolute();
+void inp_mouse_mode_relative();
+
+const char *inp_key_name(int k);
+int inp_key_code(const char *key_name);
 
-// message packing
+/* message packing */
 enum
 {
 	MSGFLAG_VITAL=1,
@@ -738,60 +740,58 @@ void msg_pack_string(const char *p, int limit);
 void msg_pack_raw(const void *data, int size);
 void msg_pack_end();
 
-struct msg_info
+typedef struct
 {
 	int msg;
 	int flags;
 	const unsigned char *data;
 	int size;
-};
+} MSG_INFO;
 
-const msg_info *msg_get_info();
+const MSG_INFO *msg_get_info();
 
-// message unpacking
+/* message unpacking */
 int msg_unpack_start(const void *data, int data_size, int *system);
 int msg_unpack_int();
 const char *msg_unpack_string();
 const unsigned char *msg_unpack_raw(int size);
 
-// message sending
-int server_send_msg(int client_id); // client_id == -1 == broadcast
+/* message sending */
+int server_send_msg(int client_id); /* client_id == -1 == broadcast */
 int client_send_msg();
 
+/* client */
 int client_tick();
 float client_intratick();
 int client_tickspeed();
+float client_frametime();
+float client_localtime();
+
 int client_state();
 const char *client_error_string();
 
-void gfx_pretty_text(float x, float y, float size, const char *text, int max_width = -1);
-float gfx_pretty_text_width(float size, const char *text, int length = -1);
-
-void gfx_getscreen(float *tl_x, float *tl_y, float *br_x, float *br_y);
-int gfx_memory_usage();
-void gfx_screenshot();
-
-void mods_message(int msg, int client_id);
-void modc_message(int msg);
-
-struct server_info
-{
-	int max_players;
-	int num_players;
-	int latency; // in ms
-	char name[128];
-	char map[128];
-	char address[128];
-};
 
 void client_connect(const char *address);
 void client_disconnect();
 void client_quit();
 
 void client_serverbrowse_refresh(int lan);
-int client_serverbrowse_getlist(server_info **servers);
+int client_serverbrowse_getlist(SERVER_INFO **servers);
 
+/* undocumented graphics stuff */
+void gfx_pretty_text(float x, float y, float size, const char *text, int max_width);
+float gfx_pretty_text_width(float size, const char *text, int length);
+
+void gfx_getscreen(float *tl_x, float *tl_y, float *br_x, float *br_y);
+int gfx_memory_usage();
+void gfx_screenshot();
+
+/* server snap id */
 int snap_new_id();
 void snap_free_id(int id);
 
+#ifdef __cplusplus
+}
+#endif
+
 #endif
diff --git a/src/engine/keynames.c b/src/engine/keynames.c
new file mode 100644
index 00000000..326e2a38
--- /dev/null
+++ b/src/engine/keynames.c
@@ -0,0 +1,523 @@
+/* AUTO GENERATED! DO NOT EDIT MANUALLY! */
+
+#include <string.h>
+
+static const char key_strings[512][16] =
+{
+	"#0",
+	"#1",
+	"#2",
+	"#3",
+	"#4",
+	"#5",
+	"#6",
+	"#7",
+	"#8",
+	"#9",
+	"#10",
+	"#11",
+	"#12",
+	"#13",
+	"#14",
+	"#15",
+	"#16",
+	"#17",
+	"#18",
+	"#19",
+	"#20",
+	"#21",
+	"#22",
+	"#23",
+	"#24",
+	"#25",
+	"#26",
+	"#27",
+	"#28",
+	"#29",
+	"#30",
+	"#31",
+	"space",
+	"#33",
+	"#34",
+	"#35",
+	"#36",
+	"#37",
+	"#38",
+	"#39",
+	"#40",
+	"#41",
+	"#42",
+	"#43",
+	"#44",
+	"#45",
+	"#46",
+	"#47",
+	"0",
+	"1",
+	"2",
+	"3",
+	"4",
+	"5",
+	"6",
+	"7",
+	"8",
+	"9",
+	"#58",
+	"#59",
+	"#60",
+	"#61",
+	"#62",
+	"#63",
+	"#64",
+	"a",
+	"b",
+	"c",
+	"d",
+	"e",
+	"f",
+	"g",
+	"h",
+	"i",
+	"j",
+	"k",
+	"l",
+	"m",
+	"n",
+	"o",
+	"p",
+	"q",
+	"r",
+	"s",
+	"t",
+	"u",
+	"v",
+	"w",
+	"x",
+	"y",
+	"z",
+	"#91",
+	"#92",
+	"#93",
+	"#94",
+	"#95",
+	"#96",
+	"#97",
+	"#98",
+	"#99",
+	"#100",
+	"#101",
+	"#102",
+	"#103",
+	"#104",
+	"#105",
+	"#106",
+	"#107",
+	"#108",
+	"#109",
+	"#110",
+	"#111",
+	"#112",
+	"#113",
+	"#114",
+	"#115",
+	"#116",
+	"#117",
+	"#118",
+	"#119",
+	"#120",
+	"#121",
+	"#122",
+	"#123",
+	"#124",
+	"#125",
+	"#126",
+	"#127",
+	"#128",
+	"#129",
+	"#130",
+	"#131",
+	"#132",
+	"#133",
+	"#134",
+	"#135",
+	"#136",
+	"#137",
+	"#138",
+	"#139",
+	"#140",
+	"#141",
+	"#142",
+	"#143",
+	"#144",
+	"#145",
+	"#146",
+	"#147",
+	"#148",
+	"#149",
+	"#150",
+	"#151",
+	"#152",
+	"#153",
+	"#154",
+	"#155",
+	"#156",
+	"#157",
+	"#158",
+	"#159",
+	"#160",
+	"#161",
+	"#162",
+	"#163",
+	"#164",
+	"#165",
+	"#166",
+	"#167",
+	"#168",
+	"#169",
+	"#170",
+	"#171",
+	"#172",
+	"#173",
+	"#174",
+	"#175",
+	"#176",
+	"#177",
+	"#178",
+	"#179",
+	"#180",
+	"#181",
+	"#182",
+	"#183",
+	"#184",
+	"#185",
+	"#186",
+	"#187",
+	"#188",
+	"#189",
+	"#190",
+	"#191",
+	"#192",
+	"#193",
+	"#194",
+	"#195",
+	"#196",
+	"#197",
+	"#198",
+	"#199",
+	"#200",
+	"#201",
+	"#202",
+	"#203",
+	"#204",
+	"#205",
+	"#206",
+	"#207",
+	"#208",
+	"#209",
+	"#210",
+	"#211",
+	"#212",
+	"#213",
+	"#214",
+	"#215",
+	"#216",
+	"#217",
+	"#218",
+	"#219",
+	"#220",
+	"#221",
+	"#222",
+	"#223",
+	"#224",
+	"#225",
+	"#226",
+	"#227",
+	"#228",
+	"#229",
+	"#230",
+	"#231",
+	"#232",
+	"#233",
+	"#234",
+	"#235",
+	"#236",
+	"#237",
+	"#238",
+	"#239",
+	"#240",
+	"#241",
+	"#242",
+	"#243",
+	"#244",
+	"#245",
+	"#246",
+	"#247",
+	"#248",
+	"#249",
+	"#250",
+	"#251",
+	"#252",
+	"#253",
+	"#254",
+	"#255",
+	"special",
+	"esc",
+	"f1",
+	"f2",
+	"f3",
+	"f4",
+	"f5",
+	"f6",
+	"f7",
+	"f8",
+	"f9",
+	"f10",
+	"f11",
+	"f12",
+	"f13",
+	"f14",
+	"f15",
+	"f16",
+	"f17",
+	"f18",
+	"f19",
+	"f20",
+	"f21",
+	"f22",
+	"f23",
+	"f24",
+	"f25",
+	"up",
+	"down",
+	"left",
+	"right",
+	"lshift",
+	"rshift",
+	"lctrl",
+	"rctrl",
+	"lalt",
+	"ralt",
+	"tab",
+	"enter",
+	"backspace",
+	"insert",
+	"del",
+	"pageup",
+	"pagedown",
+	"home",
+	"end",
+	"kp0",
+	"kp1",
+	"kp2",
+	"kp3",
+	"kp4",
+	"kp5",
+	"kp6",
+	"kp7",
+	"kp8",
+	"kp9",
+	"kpdivide",
+	"kpmultiply",
+	"kpsubtract",
+	"kpadd",
+	"kpdecimal",
+	"kpequal",
+	"kpenter",
+	"#319",
+	"#320",
+	"#321",
+	"#322",
+	"#323",
+	"#324",
+	"#325",
+	"#326",
+	"#327",
+	"#328",
+	"#329",
+	"#330",
+	"#331",
+	"#332",
+	"#333",
+	"#334",
+	"#335",
+	"#336",
+	"#337",
+	"#338",
+	"#339",
+	"#340",
+	"#341",
+	"#342",
+	"#343",
+	"#344",
+	"#345",
+	"#346",
+	"#347",
+	"#348",
+	"#349",
+	"#350",
+	"#351",
+	"#352",
+	"#353",
+	"#354",
+	"#355",
+	"#356",
+	"#357",
+	"#358",
+	"#359",
+	"#360",
+	"#361",
+	"#362",
+	"#363",
+	"#364",
+	"#365",
+	"#366",
+	"#367",
+	"#368",
+	"#369",
+	"#370",
+	"#371",
+	"#372",
+	"#373",
+	"#374",
+	"#375",
+	"#376",
+	"#377",
+	"#378",
+	"#379",
+	"#380",
+	"#381",
+	"#382",
+	"#383",
+	"mouse1",
+	"mouse2",
+	"mouse3",
+	"mouse4",
+	"mouse5",
+	"mouse6",
+	"mouse7",
+	"mouse8",
+	"#392",
+	"#393",
+	"#394",
+	"#395",
+	"#396",
+	"#397",
+	"#398",
+	"#399",
+	"#400",
+	"#401",
+	"#402",
+	"#403",
+	"#404",
+	"#405",
+	"#406",
+	"#407",
+	"#408",
+	"#409",
+	"#410",
+	"#411",
+	"#412",
+	"#413",
+	"#414",
+	"#415",
+	"#416",
+	"#417",
+	"#418",
+	"#419",
+	"#420",
+	"#421",
+	"#422",
+	"#423",
+	"#424",
+	"#425",
+	"#426",
+	"#427",
+	"#428",
+	"#429",
+	"#430",
+	"#431",
+	"#432",
+	"#433",
+	"#434",
+	"#435",
+	"#436",
+	"#437",
+	"#438",
+	"#439",
+	"#440",
+	"#441",
+	"#442",
+	"#443",
+	"#444",
+	"#445",
+	"#446",
+	"#447",
+	"#448",
+	"#449",
+	"#450",
+	"#451",
+	"#452",
+	"#453",
+	"#454",
+	"#455",
+	"#456",
+	"#457",
+	"#458",
+	"#459",
+	"#460",
+	"#461",
+	"#462",
+	"#463",
+	"#464",
+	"#465",
+	"#466",
+	"#467",
+	"#468",
+	"#469",
+	"#470",
+	"#471",
+	"#472",
+	"#473",
+	"#474",
+	"#475",
+	"#476",
+	"#477",
+	"#478",
+	"#479",
+	"#480",
+	"#481",
+	"#482",
+	"#483",
+	"#484",
+	"#485",
+	"#486",
+	"#487",
+	"#488",
+	"#489",
+	"#490",
+	"#491",
+	"#492",
+	"#493",
+	"#494",
+	"#495",
+	"#496",
+	"#497",
+	"#498",
+	"#499",
+	"#500",
+	"#501",
+	"#502",
+	"#503",
+	"#504",
+	"#505",
+	"#506",
+	"#507",
+	"#508",
+	"#509",
+	"#510",
+	"#511",
+};
+
+const char *inp_key_name(int k) { if (k >= 0 && k < 512) return key_strings[k]; else return key_strings[0]; }
+int inp_key_code(const char *key_name) { int i; if (!strcmp(key_name, "-?-")) return -1; else for (i = 0; i < 512; i++) if (!strcmp(key_strings[i], key_name)) return i; return -1; }
+
diff --git a/src/engine/keys.h b/src/engine/keys.h
new file mode 100644
index 00000000..fd8d9cbf
--- /dev/null
+++ b/src/engine/keys.h
@@ -0,0 +1,85 @@
+#ifndef ENGINE_KEYS_H
+#define ENGINE_KEYS_H
+/* AUTO GENERATED! DO NOT EDIT MANUALLY! */
+
+enum
+{
+	KEY_UNKNOWN = -1,
+	KEY_SPACE = 32,
+	KEY_SPECIAL = 256,
+	KEY_ESC = (KEY_SPECIAL+1),
+	KEY_F1 = (KEY_SPECIAL+2),
+	KEY_F2 = (KEY_SPECIAL+3),
+	KEY_F3 = (KEY_SPECIAL+4),
+	KEY_F4 = (KEY_SPECIAL+5),
+	KEY_F5 = (KEY_SPECIAL+6),
+	KEY_F6 = (KEY_SPECIAL+7),
+	KEY_F7 = (KEY_SPECIAL+8),
+	KEY_F8 = (KEY_SPECIAL+9),
+	KEY_F9 = (KEY_SPECIAL+10),
+	KEY_F10 = (KEY_SPECIAL+11),
+	KEY_F11 = (KEY_SPECIAL+12),
+	KEY_F12 = (KEY_SPECIAL+13),
+	KEY_F13 = (KEY_SPECIAL+14),
+	KEY_F14 = (KEY_SPECIAL+15),
+	KEY_F15 = (KEY_SPECIAL+16),
+	KEY_F16 = (KEY_SPECIAL+17),
+	KEY_F17 = (KEY_SPECIAL+18),
+	KEY_F18 = (KEY_SPECIAL+19),
+	KEY_F19 = (KEY_SPECIAL+20),
+	KEY_F20 = (KEY_SPECIAL+21),
+	KEY_F21 = (KEY_SPECIAL+22),
+	KEY_F22 = (KEY_SPECIAL+23),
+	KEY_F23 = (KEY_SPECIAL+24),
+	KEY_F24 = (KEY_SPECIAL+25),
+	KEY_F25 = (KEY_SPECIAL+26),
+	KEY_UP = (KEY_SPECIAL+27),
+	KEY_DOWN = (KEY_SPECIAL+28),
+	KEY_LEFT = (KEY_SPECIAL+29),
+	KEY_RIGHT = (KEY_SPECIAL+30),
+	KEY_LSHIFT = (KEY_SPECIAL+31),
+	KEY_RSHIFT = (KEY_SPECIAL+32),
+	KEY_LCTRL = (KEY_SPECIAL+33),
+	KEY_RCTRL = (KEY_SPECIAL+34),
+	KEY_LALT = (KEY_SPECIAL+35),
+	KEY_RALT = (KEY_SPECIAL+36),
+	KEY_TAB = (KEY_SPECIAL+37),
+	KEY_ENTER = (KEY_SPECIAL+38),
+	KEY_BACKSPACE = (KEY_SPECIAL+39),
+	KEY_INSERT = (KEY_SPECIAL+40),
+	KEY_DEL = (KEY_SPECIAL+41),
+	KEY_PAGEUP = (KEY_SPECIAL+42),
+	KEY_PAGEDOWN = (KEY_SPECIAL+43),
+	KEY_HOME = (KEY_SPECIAL+44),
+	KEY_END = (KEY_SPECIAL+45),
+	KEY_KP_0 = (KEY_SPECIAL+46),
+	KEY_KP_1 = (KEY_SPECIAL+47),
+	KEY_KP_2 = (KEY_SPECIAL+48),
+	KEY_KP_3 = (KEY_SPECIAL+49),
+	KEY_KP_4 = (KEY_SPECIAL+50),
+	KEY_KP_5 = (KEY_SPECIAL+51),
+	KEY_KP_6 = (KEY_SPECIAL+52),
+	KEY_KP_7 = (KEY_SPECIAL+53),
+	KEY_KP_8 = (KEY_SPECIAL+54),
+	KEY_KP_9 = (KEY_SPECIAL+55),
+	KEY_KP_DIVIDE = (KEY_SPECIAL+56),
+	KEY_KP_MULTIPLY = (KEY_SPECIAL+57),
+	KEY_KP_SUBTRACT = (KEY_SPECIAL+58),
+	KEY_KP_ADD = (KEY_SPECIAL+59),
+	KEY_KP_DECIMAL = (KEY_SPECIAL+60),
+	KEY_KP_EQUAL = (KEY_SPECIAL+61),
+	KEY_KP_ENTER = (KEY_SPECIAL+62),
+	KEY_REPEAT = 0x00030005,
+	KEY_MOUSE_FIRST = 384,
+	KEY_MOUSE_1 = KEY_MOUSE_FIRST+0,
+	KEY_MOUSE_2 = KEY_MOUSE_FIRST+1,
+	KEY_MOUSE_3 = KEY_MOUSE_FIRST+2,
+	KEY_MOUSE_4 = KEY_MOUSE_FIRST+3,
+	KEY_MOUSE_5 = KEY_MOUSE_FIRST+4,
+	KEY_MOUSE_6 = KEY_MOUSE_FIRST+5,
+	KEY_MOUSE_7 = KEY_MOUSE_FIRST+6,
+	KEY_MOUSE_8 = KEY_MOUSE_FIRST+7,
+	KEY_LAST
+};
+
+#endif
diff --git a/src/engine/map.cpp b/src/engine/map.c
index f8c24a7d..45aff7a1 100644
--- a/src/engine/map.cpp
+++ b/src/engine/map.c
@@ -1,10 +1,7 @@
 #include <stdio.h>
-#include <baselib/system.h>
-#include <baselib/stream/file.h>
-
 #include "datafile.h"
 
-static datafile *map;
+static DATAFILE *map;
 
 void *map_get_data(int index)
 {
diff --git a/src/engine/msg.c b/src/engine/msg.c
new file mode 100644
index 00000000..d53c9008
--- /dev/null
+++ b/src/engine/msg.c
@@ -0,0 +1,53 @@
+#include "interface.h"
+#include "packer.h"
+
+/* message packing */
+static PACKER msg_packer;
+static MSG_INFO pack_info;
+
+void msg_pack_int(int i) { packer_add_int(&msg_packer, i); }
+void msg_pack_string(const char *p, int limit) { packer_add_string(&msg_packer, p, limit); }
+void msg_pack_raw(const void *data, int size) { packer_add_raw(&msg_packer, (const unsigned char *)data, size); }
+
+void msg_pack_start_system(int msg, int flags)
+{
+	packer_reset(&msg_packer);
+	pack_info.msg = (msg<<1)|1;
+	pack_info.flags = flags;
+	
+	msg_pack_int(pack_info.msg);
+}
+
+void msg_pack_start(int msg, int flags)
+{
+	packer_reset(&msg_packer);
+	pack_info.msg = msg<<1;
+	pack_info.flags = flags;
+	
+	msg_pack_int(pack_info.msg);
+}
+
+void msg_pack_end()
+{
+	pack_info.size = packer_size(&msg_packer);
+	pack_info.data = packer_data(&msg_packer);
+}
+
+const MSG_INFO *msg_get_info()
+{
+	return &pack_info;
+}
+
+/* message unpacking */
+static UNPACKER msg_unpacker;
+int msg_unpack_start(const void *data, int data_size, int *system)
+{
+	unpacker_reset(&msg_unpacker, (const unsigned char *)data, data_size);
+	int msg = msg_unpack_int();
+	*system = msg&1;
+	return msg>>1;
+}
+
+int msg_unpack_int() { return unpacker_get_int(&msg_unpacker); }
+const char *msg_unpack_string() { return unpacker_get_string(&msg_unpacker); }
+const unsigned char *msg_unpack_raw(int size)  { return unpacker_get_raw(&msg_unpacker, size); }
diff --git a/src/engine/msg.cpp b/src/engine/msg.cpp
deleted file mode 100644
index fa2dab34..00000000
--- a/src/engine/msg.cpp
+++ /dev/null
@@ -1,54 +0,0 @@
-
-#include "interface.h"
-#include "packet.h"
-
-// message packing
-static data_packer packer;
-static msg_info pack_info;
-
-void msg_pack_int(int i) { packer.add_int(i); }
-void msg_pack_string(const char *p, int limit) { packer.add_string(p, limit); }
-void msg_pack_raw(const void *data, int size) { packer.add_raw((const unsigned char *)data, size); }
-
-void msg_pack_start_system(int msg, int flags)
-{
-	packer.reset();
-	pack_info.msg = (msg<<1)|1;
-	pack_info.flags = flags;
-	
-	msg_pack_int(pack_info.msg);
-}
-
-void msg_pack_start(int msg, int flags)
-{
-	packer.reset();
-	pack_info.msg = msg<<1;
-	pack_info.flags = flags;
-	
-	msg_pack_int(pack_info.msg);
-}
-
-void msg_pack_end()
-{
-	pack_info.size = packer.size();
-	pack_info.data = packer.data();
-}
-
-const msg_info *msg_get_info()
-{
-	return &pack_info;
-}
-
-// message unpacking
-static data_unpacker unpacker;
-int msg_unpack_start(const void *data, int data_size, int *system)
-{
-	unpacker.reset((const unsigned char *)data, data_size);
-	int msg = msg_unpack_int();
-	*system = msg&1;
-	return msg>>1;
-}
-
-int msg_unpack_int() { return unpacker.get_int(); }
-const char *msg_unpack_string() { return unpacker.get_string(); }
-const unsigned char *msg_unpack_raw(int size)  { return unpacker.get_raw(size); }
diff --git a/src/engine/network.cpp b/src/engine/network.c
index ac28002e..7f54fc23 100644
--- a/src/engine/network.cpp
+++ b/src/engine/network.c
@@ -1,21 +1,12 @@
-#include <baselib/system.h>
 #include <string.h>
 #include <stdio.h>
 
+#include "system.h"
 #include "config.h"
 #include "network.h"
-#include "ringbuffer.h"
 
 /*
-	header:
-		unsigned char ID[2]; 2 'T' 'W'
-		unsigned char version; 3 
-		unsigned char flags; 4 
-		unsigned short seq;  6
-		unsigned short ack;  8
-		unsigned crc;       12 bytes
-
-	header v2:
+	header (6 bytes)
 		unsigned char flags;		1
 		unsigned char seq_ack[3];	4
 		unsigned char token[2];		6
@@ -47,7 +38,7 @@ enum
 
 static int current_token = 1;
 
-struct NETPACKETDATA
+typedef struct
 {
 	unsigned char ID[2];
 	unsigned char version;
@@ -59,7 +50,7 @@ struct NETPACKETDATA
 	unsigned data_size;
 	int64 first_send_time;
 	unsigned char *data;
-};
+} NETPACKETDATA;
 
 
 static void send_packet(NETSOCKET socket, NETADDR4 *addr, NETPACKETDATA *packet)
@@ -73,11 +64,75 @@ static void send_packet(NETSOCKET socket, NETADDR4 *addr, NETPACKETDATA *packet)
 	buffer[5] = packet->token&0xff;
 	mem_copy(buffer+NETWORK_HEADER_SIZE, packet->data, packet->data_size);
 	int send_size = NETWORK_HEADER_SIZE+packet->data_size;
-	//dbg_msg("network", "sending packet, size=%d (%d + %d)", send_size, NETWORK_HEADER_SIZE, packet->data_size);
 	net_udp4_send(socket, addr, buffer, send_size);
 }
 
-struct NETCONNECTION
+typedef struct RINGBUFFER_ITEM_t
+{
+	struct RINGBUFFER_ITEM_t *next;
+	struct RINGBUFFER_ITEM_t *prev;
+	int size;
+} RINGBUFFER_ITEM;
+
+typedef struct
+{
+	RINGBUFFER_ITEM *first;
+	RINGBUFFER_ITEM *last;
+	unsigned buffer_size;
+} RINGBUFFER;
+
+static void rb_init(RINGBUFFER *rb)
+{
+	rb->first = 0;
+	rb->last = 0;
+	rb->buffer_size = 0;
+}
+
+static void *rb_item_data(RINGBUFFER_ITEM *item)
+{
+	return (void*)(item+1);
+}
+
+static void *rb_alloc(RINGBUFFER *rb, int size)
+{
+	RINGBUFFER_ITEM *item = (RINGBUFFER_ITEM*)mem_alloc(sizeof(RINGBUFFER_ITEM)+size, 1);
+	item->size = size;
+	
+	item->prev = rb->last;
+	item->next = 0;
+	if(rb->last)
+		rb->last->next = item;
+	else
+		rb->first = item;
+	rb->last = item;
+	
+	rb->buffer_size += size;
+	return rb_item_data(item);
+}
+
+static void rb_pop_first(RINGBUFFER *rb)
+{
+	if(rb->first)
+	{
+		RINGBUFFER_ITEM *next = rb->first->next;
+		rb->buffer_size -= rb->first->size;
+		mem_free(rb->first);
+		rb->first = next;
+		if(rb->first)
+			rb->first->prev = NULL;
+		else
+			rb->last = NULL;
+	}
+}
+
+static void rb_clear(RINGBUFFER *rb)
+{
+	while(rb->first)
+		rb_pop_first(rb);
+}
+
+
+typedef struct
 {
 	unsigned short seq;
 	unsigned short ack;
@@ -90,7 +145,7 @@ struct NETCONNECTION
 	int connected;
 	int disconnected;
 	
-	ring_buffer buffer;
+	RINGBUFFER buffer;
 	
 	int64 last_update_time;
 	int64 last_recv_time;
@@ -101,14 +156,14 @@ struct NETCONNECTION
 	NETADDR4 peeraddr;
 	NETSOCKET socket;
 	NETSTATS stats;
-};
+} NETCONNECTION;
 
-struct NETSLOT
+typedef struct
 {
 	NETCONNECTION conn;
-};
+} NETSLOT;
 
-struct NETSERVER
+struct NETSERVER_t
 {
 	NETSOCKET socket;
 	NETSLOT slots[NETWORK_MAX_CLIENTS];
@@ -117,9 +172,9 @@ struct NETSERVER
 	NETFUNC_NEWCLIENT del_client;
 	void *user_ptr;
 	unsigned char recv_buffer[NETWORK_MAX_PACKET_SIZE];
-};
+} ;
 
-struct NETCLIENT
+struct NETCLIENT_t
 {
 	NETADDR4 server_addr;
 	NETSOCKET socket;
@@ -138,7 +193,6 @@ static void conn_reset(NETCONNECTION *conn)
 	conn->seq = 0;
 	conn->ack = 0;
 	conn->remote_closed = 0;
-	//dbg_msg("connection", "state = %d->%d", conn->state, NETWORK_CONNSTATE_OFFLINE);
 	
 	if(conn->state == NETWORK_CONNSTATE_ONLINE ||
 		conn->state == NETWORK_CONNSTATE_ERROR)
@@ -151,7 +205,8 @@ static void conn_reset(NETCONNECTION *conn)
 	conn->last_recv_time = 0;
 	conn->last_update_time = 0;
 	conn->token = -1;
-	conn->buffer.reset();
+	
+	rb_clear(&conn->buffer);
 }
 
 
@@ -178,6 +233,7 @@ static void conn_init(NETCONNECTION *conn, NETSOCKET socket)
 	conn->socket = socket;
 	conn->connected = 0;
 	conn->disconnected = 0;
+	rb_init(&conn->buffer);
 	mem_zero(conn->error_string, sizeof(conn->error_string));
 }
 
@@ -185,13 +241,13 @@ static void conn_ack(NETCONNECTION *conn, int ack)
 {
 	while(1)
 	{
-		ring_buffer::item *i = conn->buffer.first();
-		if(!i)
+		RINGBUFFER_ITEM *item = conn->buffer.first;
+		if(!item)
 			break;
 			
-		NETPACKETDATA *resend = (NETPACKETDATA *)i->data();
+		NETPACKETDATA *resend = (NETPACKETDATA *)rb_item_data(item);
 		if(resend->seq <= ack || (ack < NETWORK_MAX_SEQACK/3 && resend->seq > NETWORK_MAX_SEQACK/2))
-			conn->buffer.pop_first();
+			rb_pop_first(&conn->buffer);
 		else
 			break;
 	}
@@ -207,14 +263,14 @@ static void conn_send_raw(NETCONNECTION *conn, NETPACKETDATA *data)
 
 static void conn_resend(NETCONNECTION *conn)
 {
-	ring_buffer::item *i = conn->buffer.first();
-	while(i)
+	RINGBUFFER_ITEM *item = conn->buffer.first;
+	while(item)
 	{
-		NETPACKETDATA *resend = (NETPACKETDATA *)i->data();
+		NETPACKETDATA *resend = (NETPACKETDATA *)rb_item_data(item);
 		conn->stats.resend_packets++;
 		conn->stats.resend_bytes += resend->data_size + NETWORK_HEADER_SIZE;
 		conn_send_raw(conn, resend);
-		i = i->next;
+		item = item->next;
 	}
 }
 
@@ -240,14 +296,14 @@ static void conn_send(NETCONNECTION *conn, int flags, int data_size, const void
 
 	if(flags&NETWORK_PACKETFLAG_VITAL)
 	{
-		// save packet if we need to resend
-		NETPACKETDATA *resend = (NETPACKETDATA *)conn->buffer.alloc(sizeof(NETPACKETDATA)+p.data_size);
+		/* save packet if we need to resend */
+		NETPACKETDATA *resend = (NETPACKETDATA *)rb_alloc(&conn->buffer, sizeof(NETPACKETDATA)+data_size);
 		*resend = p;
 		resend->data = (unsigned char *)(resend+1);
 		mem_copy(resend->data, p.data, p.data_size);
 	}
 	
-	// TODO: calc crc
+	/* TODO: calc crc */
 	conn_send_raw(conn, &p);
 }
 
@@ -256,12 +312,11 @@ static int conn_connect(NETCONNECTION *conn, NETADDR4 *addr)
 	if(conn->state != NETWORK_CONNSTATE_OFFLINE)
 		return -1;
 	
-	// init connection
+	/* init connection */
 	conn_reset(conn);
 	conn->peeraddr = *addr;
 	conn->token = current_token++;
 	mem_zero(conn->error_string, sizeof(conn->error_string));
-	//dbg_msg("connection", "state = %d->%d", conn->state, NETWORK_CONNSTATE_CONNECT);
 	conn->state = NETWORK_CONNSTATE_CONNECT;
 	conn_send(conn, NETWORK_PACKETFLAG_CONNECT, 0, 0);
 	return 0;
@@ -290,7 +345,6 @@ static int conn_feed(NETCONNECTION *conn, NETPACKETDATA *p, NETADDR4 *addr)
 		conn->state = NETWORK_CONNSTATE_ERROR;
 		conn->remote_closed = 1;
 		
-		//conn_reset(conn);
 		if(p->data_size)
 			conn_set_error(conn, (char *)p->data);
 		else
@@ -304,13 +358,11 @@ static int conn_feed(NETCONNECTION *conn, NETPACKETDATA *p, NETADDR4 *addr)
 	{
 		if(p->flags == NETWORK_PACKETFLAG_CONNECT)
 		{
-			// send response and init connection
-			//dbg_msg("connection", "state = %d->%d", conn->state, NETWORK_CONNSTATE_ONLINE);
+			/* send response and init connection */
 			conn->state = NETWORK_CONNSTATE_ONLINE;
 			conn->connected++;
 			conn->peeraddr = *addr;
 			conn->token = p->token;
-			//dbg_msg("connection", "token set to %d", p->token);
 			conn_send(conn, NETWORK_PACKETFLAG_CONNECT|NETWORK_PACKETFLAG_ACCEPT, 0, 0);
 			if(config.debug)
 				dbg_msg("connection", "got connection, sending connect+accept");
@@ -319,17 +371,14 @@ static int conn_feed(NETCONNECTION *conn, NETPACKETDATA *p, NETADDR4 *addr)
 	else if(net_addr4_cmp(&conn->peeraddr, addr) == 0)
 	{
 		if(p->token != conn->token)
-		{
-			//dbg_msg("connection", "wrong token %d, %d", p->token, conn->token);
 			return 0;
-		}
 
 		if(conn->state == NETWORK_CONNSTATE_ONLINE)
 		{
-			// remove packages that are acked
+			/* remove packages that are acked */
 			conn_ack(conn, p->ack);
 			
-			// 
+			/* check if resend is requested */
 			if(p->flags&NETWORK_PACKETFLAG_RESEND)
 				conn_resend(conn);
 				
@@ -337,12 +386,12 @@ static int conn_feed(NETCONNECTION *conn, NETPACKETDATA *p, NETADDR4 *addr)
 			{
 				if(p->seq == (conn->ack+1)%NETWORK_MAX_SEQACK)
 				{
-					// in sequence
+					/* in sequence */
 					conn->ack = (conn->ack+1)%NETWORK_MAX_SEQACK;
 				}
 				else
 				{
-					// out of sequence, request resend
+					/* out of sequence, request resend */
 					dbg_msg("conn", "asking for resend %d %d", p->seq, (conn->ack+1)%NETWORK_MAX_SEQACK);
 					conn_send(conn, NETWORK_PACKETFLAG_RESEND, 0, 0);
 					return 0;
@@ -351,10 +400,7 @@ static int conn_feed(NETCONNECTION *conn, NETPACKETDATA *p, NETADDR4 *addr)
 			else
 			{
 				if(p->seq > conn->ack)
-				{
-					//dbg_msg("conn", "asking for resend");
 					conn_send(conn, NETWORK_PACKETFLAG_RESEND, 0, 0);
-				}
 			}
 			
 			if(p->data_size == 0)
@@ -364,11 +410,10 @@ static int conn_feed(NETCONNECTION *conn, NETPACKETDATA *p, NETADDR4 *addr)
 		}
 		else if(conn->state == NETWORK_CONNSTATE_CONNECT)
 		{
-			// connection made
+			/* connection made */
 			if(p->flags == (NETWORK_PACKETFLAG_CONNECT|NETWORK_PACKETFLAG_ACCEPT))
 			{
 				conn_send(conn, NETWORK_PACKETFLAG_ACCEPT, 0, 0);
-				//dbg_msg("connection", "state = %d->%d", conn->state, NETWORK_CONNSTATE_ONLINE);
 				conn->state = NETWORK_CONNSTATE_ONLINE;
 				conn->connected++;
 				dbg_msg("connection", "got connect+accept, sending accept. connection online");
@@ -386,15 +431,14 @@ static int conn_feed(NETCONNECTION *conn, NETPACKETDATA *p, NETADDR4 *addr)
 		}*/
 		else
 		{
-			//conn_reset(conn);
-			// strange packet, wrong state
+			/* strange packet, wrong state */
 			conn->state = NETWORK_CONNSTATE_ERROR;
 			conn_set_error(conn, "strange state and packet");
 		}
 	}
 	else
 	{
-		// strange packet, not ment for me
+		/* strange packet, not ment for me */
 	}
 	
 	return 0;
@@ -407,7 +451,7 @@ static int conn_update(NETCONNECTION *conn)
 	if(conn->state == NETWORK_CONNSTATE_OFFLINE || conn->state == NETWORK_CONNSTATE_ERROR)
 		return 0;
 
-	// watch out for major hitches		
+	/* watch out for major hitches */
 	int64 now = time_get();
 	int64 delta = now-conn->last_update_time;
 	if(conn->last_update_time && delta > time_freq()/2)
@@ -416,49 +460,46 @@ static int conn_update(NETCONNECTION *conn)
 
 		conn->last_recv_time += delta;
 
-		ring_buffer::item *i = conn->buffer.first();
-		while(i)
+		RINGBUFFER_ITEM *item = conn->buffer.first;
+		while(item)
 		{
-			NETPACKETDATA *resend = (NETPACKETDATA *)i->data();
+			NETPACKETDATA *resend = (NETPACKETDATA *)rb_item_data(item);
 			resend->first_send_time += delta;
-			i = i->next;
+			item = item->next;
 		}
 	}
 		
 	conn->last_update_time = now;
 	
-	// check for timeout
+	/* check for timeout */
 	if(conn->state != NETWORK_CONNSTATE_OFFLINE &&
 		conn->state != NETWORK_CONNSTATE_CONNECT &&
 		(now-conn->last_recv_time) > time_freq()*10)
 	{
-		//dbg_msg("connection", "state = %d->%d", conn->state, NETWORK_CONNSTATE_ERROR);
 		conn->state = NETWORK_CONNSTATE_ERROR;
 		char buf[128];
 		sprintf(buf, "timeout %lld %lld %lld %lld", now-conn->last_recv_time, now, conn->last_recv_time, time_freq()*10);
 		conn_set_error(conn, buf);
 	}
 	
-	// check for large buffer errors
-	if(conn->buffer.size() > 1024*64)
+	/* check for large buffer errors */
+	if(conn->buffer.buffer_size > 1024*64)
 	{
-		//dbg_msg("connection", "state = %d->%d", conn->state, NETWORK_CONNSTATE_ERROR);
 		conn->state = NETWORK_CONNSTATE_ERROR;
 		conn_set_error(conn, "too weak connection (out of buffer)");
 	}
 	
-	if(conn->buffer.first())
+	if(conn->buffer.first)
 	{
-		NETPACKETDATA *resend = (NETPACKETDATA *)conn->buffer.first()->data();
+		NETPACKETDATA *resend = (NETPACKETDATA *)(conn->buffer.first+1);
 		if(now-resend->first_send_time > time_freq()*10)
 		{
-			//dbg_msg("connection", "state = %d->%d", conn->state, NETWORK_CONNSTATE_ERROR);
 			conn->state = NETWORK_CONNSTATE_ERROR;
 			conn_set_error(conn, "too weak connection (not acked for 10 seconds)");
 		}
 	}
 	
-	// send keep alives if nothing has happend for 250ms
+	/* send keep alives if nothing has happend for 250ms */
 	if(conn->state == NETWORK_CONNSTATE_ONLINE)
 	{
 		if(time_get()-conn->last_send_time> time_freq()/4)
@@ -466,12 +507,12 @@ static int conn_update(NETCONNECTION *conn)
 	}
 	else if(conn->state == NETWORK_CONNSTATE_CONNECT)
 	{
-		if(time_get()-conn->last_send_time > time_freq()/2) // send a new connect every 500ms
+		if(time_get()-conn->last_send_time > time_freq()/2) /* send a new connect every 500ms */
 			conn_send(conn, NETWORK_PACKETFLAG_CONNECT, 0, 0);
 	}
 	else if(conn->state == NETWORK_CONNSTATE_CONNECTACCEPTED)
 	{
-		if(time_get()-conn->last_send_time > time_freq()/2) // send a new connect/accept every 500ms
+		if(time_get()-conn->last_send_time > time_freq()/2) /* send a new connect/accept every 500ms */
 			conn_send(conn, NETWORK_PACKETFLAG_CONNECT|NETWORK_PACKETFLAG_ACCEPT, 0, 0);
 	}
 	
@@ -481,11 +522,11 @@ static int conn_update(NETCONNECTION *conn)
 
 static int check_packet(unsigned char *buffer, int size, NETPACKETDATA *packet)
 {
-	// check the size
+	/* check the size */
 	if(size < NETWORK_HEADER_SIZE || size > NETWORK_MAX_PACKET_SIZE)
 		return -1;
 	
-	// read the packet
+	/* read the packet */
 	packet->ID[0] = 'T';
 	packet->ID[1] = 'W';
 	packet->version = NETWORK_VERSION;
@@ -497,26 +538,28 @@ static int check_packet(unsigned char *buffer, int size, NETPACKETDATA *packet)
 	packet->data_size = size - NETWORK_HEADER_SIZE;
 	packet->data = buffer+NETWORK_HEADER_SIZE;
 	
-	// check the packet
+	/* check the packet */
 	if(packet->ID[0] != 'T' || packet->ID[1] != 'W')
 		return 1;
 	
 	if(packet->version != NETWORK_VERSION)
 		return 1;
 
-	// TODO: perform crc check
+	/* TODO: perform crc check */
 	
-	// return success
+	/* return success */
 	return 0;
 }
 
-NETSERVER *net_server_open(NETADDR4 bindaddr, int max_clients, int flags)
+NETSERVER *netserver_open(NETADDR4 bindaddr, int max_clients, int flags)
 {
+	int i;
+	NETSERVER *server;
 	NETSOCKET socket = net_udp4_create(bindaddr);
 	if(socket == NETSOCKET_INVALID)
 		return 0;
 	
-	NETSERVER *server = (NETSERVER *)mem_alloc(sizeof(NETSERVER), 1);
+	server = (NETSERVER *)mem_alloc(sizeof(NETSERVER), 1);
 	mem_zero(server, sizeof(NETSERVER));
 	server->socket = socket;
 	server->max_clients = max_clients;
@@ -525,13 +568,13 @@ NETSERVER *net_server_open(NETADDR4 bindaddr, int max_clients, int flags)
 	if(server->max_clients < 1)
 		server->max_clients = 1;
 	
-	for(int i = 0; i < NETWORK_MAX_CLIENTS; i++)
+	for(i = 0; i < NETWORK_MAX_CLIENTS; i++)
 		conn_init(&server->slots[i].conn, server->socket);
 
 	return server;
 }
 
-int net_server_set_callbacks(NETSERVER *s, NETFUNC_NEWCLIENT new_client, NETFUNC_DELCLIENT del_client, void *user)
+int netserver_set_callbacks(NETSERVER *s, NETFUNC_NEWCLIENT new_client, NETFUNC_DELCLIENT del_client, void *user)
 {
 	s->new_client = new_client;
 	s->del_client = del_client;
@@ -539,83 +582,61 @@ int net_server_set_callbacks(NETSERVER *s, NETFUNC_NEWCLIENT new_client, NETFUNC
 	return 0;
 }
 
-int net_server_close(NETSERVER *s)
+int netserver_max_clients(NETSERVER *s)
 {
-	// TODO: implement me
-	return 0;
+	return s->max_clients;
 }
 
-/*
-int net_server_newclient(NETSERVER *s)
+int netserver_close(NETSERVER *s)
 {
-	for(int i = 0; i < s->max_clients; i++)
-	{
-		if(s->slots[i].conn.connected)
-		{
-			s->slots[i].conn.connected = 0;
-			return i;
-		}
-	}
-	
-	return -1;
+	/* TODO: implement me */
+	return 0;
 }
 
-int net_server_delclient(NETSERVER *s)
-{
-	for(int i = 0; i < s->max_clients; i++)
-	{
-		if(s->slots[i].conn.disconnected)
-		{
-			s->slots[i].conn.disconnected = 0;
-			return i;
-		}
-	}
-	
-	return -1;
-}*/
-
-int net_server_drop(NETSERVER *s, int client_id, const char *reason)
+int netserver_drop(NETSERVER *s, int client_id, const char *reason)
 {
-	// TODO: insert lots of checks here
+	/* TODO: insert lots of checks here */
 	dbg_msg("net_server", "client dropped. cid=%d reason=\"%s\"", client_id, reason);
 	conn_disconnect(&s->slots[client_id].conn, reason);
-	
+
 	if(s->del_client)
 		s->del_client(client_id, s->user_ptr);
 		
-	//conn_reset(&s->slots[client_id].conn);
 	return 0;
 }
 
-int net_server_update(NETSERVER *s)
+int netserver_update(NETSERVER *s)
 {
-	for(int i = 0; i < s->max_clients; i++)
+	int i;
+	for(i = 0; i < s->max_clients; i++)
 	{
 		conn_update(&s->slots[i].conn);
 		if(s->slots[i].conn.state == NETWORK_CONNSTATE_ERROR)
-			net_server_drop(s, i, conn_error(&s->slots[i].conn));
+			netserver_drop(s, i, conn_error(&s->slots[i].conn));
 	}
 	return 0;
 }
 
-int net_server_recv(NETSERVER *s, NETPACKET *packet)
+int netserver_recv(NETSERVER *s, NETPACKET *packet)
 {
+	NETPACKETDATA data;
+	int i, r, bytes, found;
+	NETADDR4 addr;
+	
 	while(1)
 	{
-		NETADDR4 addr;
-		int bytes = net_udp4_recv(s->socket, &addr, s->recv_buffer, NETWORK_MAX_PACKET_SIZE);
+		bytes = net_udp4_recv(s->socket, &addr, s->recv_buffer, NETWORK_MAX_PACKET_SIZE);
 
-		// no more packets for now
+		/* no more packets for now */
 		if(bytes <= 0)
 			break;
 		
-		NETPACKETDATA data;
-		int r = check_packet(s->recv_buffer, bytes, &data);
+		r = check_packet(s->recv_buffer, bytes, &data);
 		if(r == 0)
 		{
 			if(data.flags&NETWORK_PACKETFLAG_CONNLESS)
 			{
-				// connection less packets
+				/* connection less packets */
 				packet->client_id = -1;
 				packet->address = addr;
 				packet->flags = PACKETFLAG_CONNLESS;
@@ -625,31 +646,29 @@ int net_server_recv(NETSERVER *s, NETPACKET *packet)
 			}
 			else
 			{
-				// ok packet, process it
+				/* ok packet, process it */
 				if(data.flags == NETWORK_PACKETFLAG_CONNECT)
 				{
-					int found = 0;
+					found = 0;
 					
-					// check if we already got this client
-					for(int i = 0; i < s->max_clients; i++)
+					/* check if we already got this client */
+					for(i = 0; i < s->max_clients; i++)
 					{
 						if(s->slots[i].conn.state != NETWORK_CONNSTATE_OFFLINE &&
 							net_addr4_cmp(&s->slots[i].conn.peeraddr, &addr) == 0)
 						{
-							found = 1; // silent ignore.. we got this client already
-							//dbg_msg("netserver", "ignored connect request %d", i);
+							found = 1; /* silent ignore.. we got this client already */
 							break;
 						}
 					}
 					
-					// client that wants to connect
+					/* client that wants to connect */
 					if(!found)
 					{
-						for(int i = 0; i < s->max_clients; i++)
+						for(i = 0; i < s->max_clients; i++)
 						{
 							if(s->slots[i].conn.state == NETWORK_CONNSTATE_OFFLINE)
 							{
-								//dbg_msg("netserver", "connection started %d", i);
 								found = 1;
 								conn_feed(&s->slots[i].conn, &data, &addr);
 								if(s->new_client)
@@ -661,7 +680,7 @@ int net_server_recv(NETSERVER *s, NETPACKET *packet)
 					
 					if(!found)
 					{
-						// send connectionless packet
+						/* send connectionless packet */
 						const char errstring[] = "server full";
 						NETPACKETDATA p;
 						p.ID[0] = 'T';
@@ -679,8 +698,8 @@ int net_server_recv(NETSERVER *s, NETPACKET *packet)
 				}
 				else
 				{
-					// find matching slot
-					for(int i = 0; i < s->max_clients; i++)
+					/* find matching slot */
+					for(i = 0; i < s->max_clients; i++)
 					{
 						if(net_addr4_cmp(&s->slots[i].conn.peeraddr, &addr) == 0)
 						{
@@ -703,22 +722,22 @@ int net_server_recv(NETSERVER *s, NETPACKET *packet)
 		}
 		else
 		{
-			// errornous packet, drop it
+			/* errornous packet, drop it */
 			dbg_msg("server", "crazy packet");
 		}
 		
-		// read header
-		// do checksum
+		/* read header */
+		/* do checksum */
 	}	
 	
 	return 0;
 }
 
-int net_server_send(NETSERVER *s, NETPACKET *packet)
+int netserver_send(NETSERVER *s, NETPACKET *packet)
 {
 	if(packet->flags&PACKETFLAG_CONNLESS)
 	{
-		// send connectionless packet
+		/* send connectionless packet */
 		NETPACKETDATA p;
 		p.ID[0] = 'T';
 		p.ID[1] = 'W';
@@ -743,23 +762,23 @@ int net_server_send(NETSERVER *s, NETPACKET *packet)
 	return 0;
 }
 
-void net_server_stats(NETSERVER *s, NETSTATS *stats)
+void netserver_stats(NETSERVER *s, NETSTATS *stats)
 {
 	mem_zero(stats, sizeof(NETSTATS));
 	
 	int num_stats = sizeof(NETSTATS)/sizeof(int);
 	int *istats = (int *)stats;
+	int c, i;
 	
-	for(int c = 0; c < s->max_clients; c++)
+	for(c = 0; c < s->max_clients; c++)
 	{
 		int *sstats = (int *)(&(s->slots[c].conn.stats));
-		for(int i = 0; i < num_stats; i++)
+		for(i = 0; i < num_stats; i++)
 			istats[i] += sstats[i];
 	}
 }
 
-//
-NETCLIENT *net_client_open(NETADDR4 bindaddr, int flags)
+NETCLIENT *netclient_open(NETADDR4 bindaddr, int flags)
 {
 	NETCLIENT *client = (NETCLIENT *)mem_alloc(sizeof(NETCLIENT), 1);
 	mem_zero(client, sizeof(NETCLIENT));
@@ -768,44 +787,41 @@ NETCLIENT *net_client_open(NETADDR4 bindaddr, int flags)
 	return client;
 }
 
-int net_client_close(NETCLIENT *c)
+int netclient_close(NETCLIENT *c)
 {
-	// TODO: implement me
+	/* TODO: implement me */
 	return 0;
 }
 
-int net_client_update(NETCLIENT *c)
+int netclient_update(NETCLIENT *c)
 {
-	// TODO: implement me
 	conn_update(&c->conn);
 	if(c->conn.state == NETWORK_CONNSTATE_ERROR)
-		net_client_disconnect(c, conn_error(&c->conn));
+		netclient_disconnect(c, conn_error(&c->conn));
 	return 0;
 }
 
-int net_client_disconnect(NETCLIENT *c, const char *reason)
+int netclient_disconnect(NETCLIENT *c, const char *reason)
 {
-	// TODO: do this more graceful
-	dbg_msg("net_client", "disconnected. reason=\"%s\"", reason);
+	dbg_msg("netclient", "disconnected. reason=\"%s\"", reason);
 	conn_disconnect(&c->conn, reason);
 	return 0;
 }
 
-int net_client_connect(NETCLIENT *c, NETADDR4 *addr)
+int netclient_connect(NETCLIENT *c, NETADDR4 *addr)
 {
-	//net_client_disconnect(c);
 	conn_connect(&c->conn, addr);
 	return 0;
 }
 
-int net_client_recv(NETCLIENT *c, NETPACKET *packet)
+int netclient_recv(NETCLIENT *c, NETPACKET *packet)
 {
 	while(1)
 	{
 		NETADDR4 addr;
 		int bytes = net_udp4_recv(c->socket, &addr, c->recv_buffer, NETWORK_MAX_PACKET_SIZE);
 
-		// no more packets for now
+		/* no more packets for now */
 		if(bytes <= 0)
 			break;
 		
@@ -816,7 +832,7 @@ int net_client_recv(NETCLIENT *c, NETPACKET *packet)
 		{
 			if(data.flags&NETWORK_PACKETFLAG_CONNLESS)
 			{
-				// connection less packets
+				/* connection less packets */
 				packet->client_id = -1;
 				packet->address = addr;
 				packet->flags = PACKETFLAG_CONNLESS;
@@ -828,7 +844,7 @@ int net_client_recv(NETCLIENT *c, NETPACKET *packet)
 			{
 				if(conn_feed(&c->conn, &data, &addr))
 				{
-					// fill in packet
+					/* fill in packet */
 					packet->client_id = 0;
 					packet->address = addr;
 					packet->flags = 0;
@@ -838,7 +854,7 @@ int net_client_recv(NETCLIENT *c, NETPACKET *packet)
 				}
 				else
 				{
-					// errornous packet, drop it
+					/* errornous packet, drop it */
 				}
 			}			
 		}
@@ -847,11 +863,11 @@ int net_client_recv(NETCLIENT *c, NETPACKET *packet)
 	return 0;
 }
 
-int net_client_send(NETCLIENT *c, NETPACKET *packet)
+int netclient_send(NETCLIENT *c, NETPACKET *packet)
 {
 	if(packet->flags&PACKETFLAG_CONNLESS)
 	{
-		// send connectionless packet
+		/* send connectionless packet */
 		NETPACKETDATA p;
 		p.ID[0] = 'T';
 		p.ID[1] = 'W';
@@ -867,7 +883,6 @@ int net_client_send(NETCLIENT *c, NETPACKET *packet)
 	}
 	else
 	{
-		// TODO: insert stuff for stateless stuff
 		dbg_assert(packet->client_id == 0, "errornous client id");
 
 		int flags = 0;		
@@ -878,7 +893,7 @@ int net_client_send(NETCLIENT *c, NETPACKET *packet)
 	return 0;
 }
 
-int net_client_state(NETCLIENT *c)
+int netclient_state(NETCLIENT *c)
 {
 	if(c->conn.state == NETWORK_CONNSTATE_ONLINE)
 		return NETSTATE_ONLINE;
@@ -887,12 +902,12 @@ int net_client_state(NETCLIENT *c)
 	return NETSTATE_CONNECTING;
 }
 
-void net_client_stats(NETCLIENT *c, NETSTATS *stats)
+void netclient_stats(NETCLIENT *c, NETSTATS *stats)
 {
 	*stats = c->conn.stats;
 }
 
-const char *net_client_error_string(NETCLIENT *c)
+const char *netclient_error_string(NETCLIENT *c)
 {
 	return conn_error(&c->conn);
 }
diff --git a/src/engine/network.h b/src/engine/network.h
index afd0dcd0..05c54f0e 100644
--- a/src/engine/network.h
+++ b/src/engine/network.h
@@ -1,16 +1,16 @@
 
-struct NETPACKET
+typedef struct
 {
-	// -1 means that it's a stateless packet
-	// 0 on the client means the server
+	/* -1 means that it's a stateless packet */
+	/* 0 on the client means the server */
 	int client_id;
-	NETADDR4 address; // only used when client_id == -1
+	NETADDR4 address; /* only used when client_id == -1 */
 	int flags;
 	int data_size;
 	const void *data;
-};
+} NETPACKET;
 
-struct NETSTATS
+typedef struct
 {
 	int send_bytes;
 	int recv_bytes;
@@ -19,10 +19,10 @@ struct NETSTATS
 	
 	int resend_packets;
 	int resend_bytes;
-};
+} NETSTATS;
 
-struct NETSERVER;
-struct NETCLIENT;
+typedef struct NETSERVER_t NETSERVER;
+typedef struct NETCLIENT_t NETCLIENT;
 
 enum
 {
@@ -38,32 +38,29 @@ enum
 typedef int (*NETFUNC_DELCLIENT)(int cid, void *user);
 typedef int (*NETFUNC_NEWCLIENT)(int cid, void *user);
 
-// server side
-NETSERVER *net_server_open(NETADDR4 bindaddr, int max_clients, int flags);
-int net_server_set_callbacks(NETSERVER *s, NETFUNC_NEWCLIENT new_client, NETFUNC_DELCLIENT del_client, void *user);
-int net_server_recv(NETSERVER *s, NETPACKET *packet);
-int net_server_send(NETSERVER *s, NETPACKET *packet);
-int net_server_close(NETSERVER *s);
-int net_server_update(NETSERVER *s);
-int net_server_drop(NETSERVER *s, int client_id, const char *reason);
-//int net_server_newclient(NETSERVER *s); // -1 when no more, else, client id
-//int net_server_delclient(NETSERVER *s); // -1 when no more, else, client id
-void net_server_stats(NETSERVER *s, NETSTATS *stats);
-
-// client side
-NETCLIENT *net_client_open(NETADDR4 bindaddr, int flags);
-int net_client_disconnect(NETCLIENT *c, const char *reason);
-int net_client_connect(NETCLIENT *c, NETADDR4 *addr);
-int net_client_recv(NETCLIENT *c, NETPACKET *packet);
-int net_client_send(NETCLIENT *c, NETPACKET *packet);
-int net_client_close(NETCLIENT *c);
-int net_client_update(NETCLIENT *c);
-int net_client_state(NETCLIENT *c);
-void net_client_stats(NETCLIENT *c, NETSTATS *stats);
-const char *net_client_error_string(NETCLIENT *c);
+/* server side */
+NETSERVER *netserver_open(NETADDR4 bindaddr, int max_clients, int flags);
+int netserver_set_callbacks(NETSERVER *s, NETFUNC_NEWCLIENT new_client, NETFUNC_DELCLIENT del_client, void *user);
+int netserver_recv(NETSERVER *s, NETPACKET *packet);
+int netserver_send(NETSERVER *s, NETPACKET *packet);
+int netserver_close(NETSERVER *s);
+int netserver_update(NETSERVER *s);
+int netserver_drop(NETSERVER *s, int client_id, const char *reason);
+int netserver_max_clients(NETSERVER *s);
+void netserver_stats(NETSERVER *s, NETSTATS *stats);
 
+/* client side */
+NETCLIENT *netclient_open(NETADDR4 bindaddr, int flags);
+int netclient_disconnect(NETCLIENT *c, const char *reason);
+int netclient_connect(NETCLIENT *c, NETADDR4 *addr);
+int netclient_recv(NETCLIENT *c, NETPACKET *packet);
+int netclient_send(NETCLIENT *c, NETPACKET *packet);
+int netclient_close(NETCLIENT *c);
+int netclient_update(NETCLIENT *c);
+int netclient_state(NETCLIENT *c);
+void netclient_stats(NETCLIENT *c, NETSTATS *stats);
+const char *netclient_error_string(NETCLIENT *c);
 
-// wrapper classes for c++
 #ifdef __cplusplus
 class net_server
 {
@@ -72,21 +69,20 @@ public:
 	net_server() : ptr(0) {}
 	~net_server() { close(); }
 	
-	int open(NETADDR4 bindaddr, int max, int flags) { ptr = net_server_open(bindaddr, max, flags); return ptr != 0; }
-	int close() { int r = net_server_close(ptr); ptr = 0; return r; }
+	int open(NETADDR4 bindaddr, int max, int flags) { ptr = netserver_open(bindaddr, max, flags); return ptr != 0; }
+	int close() { int r = netserver_close(ptr); ptr = 0; return r; }
 	
 	int set_callbacks(NETFUNC_NEWCLIENT new_client, NETFUNC_DELCLIENT del_client, void *user)
-	{ return net_server_set_callbacks(ptr, new_client, del_client, user); }
+	{ return netserver_set_callbacks(ptr, new_client, del_client, user); }
 	
-	int recv(NETPACKET *packet) { return net_server_recv(ptr, packet); }
-	int send(NETPACKET *packet) { return net_server_send(ptr, packet); }
-	int update() { return net_server_update(ptr); }
+	int recv(NETPACKET *packet) { return netserver_recv(ptr, packet); }
+	int send(NETPACKET *packet) { return netserver_send(ptr, packet); }
+	int update() { return netserver_update(ptr); }
 	
-	int drop(int client_id, const char *reason) { return net_server_drop(ptr, client_id, reason); } 
-	//int newclient() { return net_server_newclient(ptr); }
-	//int delclient() { return net_server_delclient(ptr); }
-	
-	void stats(NETSTATS *stats) { net_server_stats(ptr, stats); }
+	int drop(int client_id, const char *reason) { return netserver_drop(ptr, client_id, reason); } 
+
+	int max_clients() { return netserver_max_clients(ptr); }
+	void stats(NETSTATS *stats) { netserver_stats(ptr, stats); }
 };
 
 
@@ -97,19 +93,19 @@ public:
 	net_client() : ptr(0) {}
 	~net_client() { close(); }
 	
-	int open(NETADDR4 bindaddr, int flags) { ptr = net_client_open(bindaddr, flags); return ptr != 0; }
-	int close() { int r = net_client_close(ptr); ptr = 0; return r; }
+	int open(NETADDR4 bindaddr, int flags) { ptr = netclient_open(bindaddr, flags); return ptr != 0; }
+	int close() { int r = netclient_close(ptr); ptr = 0; return r; }
 	
-	int connect(NETADDR4 *addr) { return net_client_connect(ptr, addr); }
-	int disconnect(const char *reason) { return net_client_disconnect(ptr, reason); }
+	int connect(NETADDR4 *addr) { return netclient_connect(ptr, addr); }
+	int disconnect(const char *reason) { return netclient_disconnect(ptr, reason); }
 	
-	int recv(NETPACKET *packet) { return net_client_recv(ptr, packet); }
-	int send(NETPACKET *packet) { return net_client_send(ptr, packet); }
-	int update() { return net_client_update(ptr); }
+	int recv(NETPACKET *packet) { return netclient_recv(ptr, packet); }
+	int send(NETPACKET *packet) { return netclient_send(ptr, packet); }
+	int update() { return netclient_update(ptr); }
 	
-	const char *error_string() { return net_client_error_string(ptr); }
+	const char *error_string() { return netclient_error_string(ptr); }
 	
-	int state() { return net_client_state(ptr); }
-	void stats(NETSTATS *stats) { net_client_stats(ptr, stats); }
+	int state() { return netclient_state(ptr); }
+	void stats(NETSTATS *stats) { netclient_stats(ptr, stats); }
 };
 #endif
diff --git a/src/engine/packer.c b/src/engine/packer.c
new file mode 100644
index 00000000..190749c2
--- /dev/null
+++ b/src/engine/packer.c
@@ -0,0 +1,89 @@
+
+#include "packer.h"
+#include "compression.h"
+
+void packer_reset(PACKER *p)
+{
+	p->error = 0;
+	p->current = p->buffer;
+	p->end = p->current + PACKER_BUFFER_SIZE;
+}
+
+void packer_add_int(PACKER *p, int i)
+{
+	p->current = vint_pack(p->current, i);
+}
+
+void packer_add_string(PACKER *p, const char *str, int limit)
+{
+	if(limit > 0)
+	{
+		while(*str && limit != 0)
+		{
+			*p->current++ = *str++;
+			limit--;
+		}
+		*p->current++ = 0;
+	}
+	else
+	{
+		while(*str)
+			*p->current++ = *str++;
+		*p->current++ = 0;
+	}
+}
+
+void packer_add_raw(PACKER *p, const unsigned char *data, int size)
+{
+	while(size)
+	{
+		*p->current++ = *data++;
+		size--;
+	}
+}
+
+int packer_size(PACKER *p)
+{
+	return (const unsigned char *)p->current-(const unsigned char *)p->buffer;
+}
+
+const unsigned char *packer_data(PACKER *p)
+{
+	return (const unsigned char *)p->buffer;
+}
+
+void unpacker_reset(UNPACKER *p, const unsigned char *data, int size)
+{
+	p->error = 0;
+	p->start = data;
+	p->end = p->start + size;
+	p->current = p->start;
+}
+
+int unpacker_get_int(UNPACKER *p)
+{
+	int i;
+	if(p->current >= p->end)
+		return 0;
+	p->current = vint_unpack(p->current, &i);
+	return i;
+}
+
+const char *unpacker_get_string(UNPACKER *p)
+{
+	if(p->current >= p->end)
+		return "";
+		
+	const char *ptr = (const char *)p->current;
+	while(*p->current) /* skip the string */
+		p->current++;
+	p->current++;
+	return ptr;
+}
+
+const unsigned char *unpacker_get_raw(UNPACKER *p, int size)
+{
+	const unsigned char *ptr = p->current;
+	p->current += size;
+	return ptr;
+}
diff --git a/src/engine/packer.h b/src/engine/packer.h
new file mode 100644
index 00000000..af1c8195
--- /dev/null
+++ b/src/engine/packer.h
@@ -0,0 +1,34 @@
+
+enum
+{
+	PACKER_BUFFER_SIZE=1024*2
+};
+
+typedef struct
+{
+	
+	unsigned char buffer[PACKER_BUFFER_SIZE];
+	unsigned char *current;
+	unsigned char *end;
+	int error;
+} PACKER;
+
+typedef struct
+{
+	const unsigned char *current;
+	const unsigned char *start;
+	const unsigned char *end;
+	int error;
+} UNPACKER;
+
+void packer_reset(PACKER *p);
+void packer_add_int(PACKER *p, int i);
+void packer_add_string(PACKER *p, const char *str, int limit);
+void packer_add_raw(PACKER *p, const unsigned char *data, int size);
+int packer_size(PACKER *p);
+const unsigned char *packer_data(PACKER *p);
+
+void unpacker_reset(UNPACKER *p, const unsigned char *data, int size);
+int unpacker_get_int(UNPACKER *p);
+const char *unpacker_get_string(UNPACKER *p);
+const unsigned char *unpacker_get_raw(UNPACKER *p, int size);
diff --git a/src/engine/packet.h b/src/engine/packet.h
deleted file mode 100644
index 1dd3c3ab..00000000
--- a/src/engine/packet.h
+++ /dev/null
@@ -1,315 +0,0 @@
-#include <stdarg.h>
-#include <string.h>
-#include <baselib/stream/file.h>
-#include <baselib/network.h>
-
-#include "versions.h"
-#include "ringbuffer.h"
-#include "compression.h"
-#include "snapshot.h"
-
-enum
-{
-	NETMSG_NULL=0,
-	
-	// the first thing sent by the client
-	// contains the version info for the client
-	NETMSG_INFO=1,
-	
-	// sent by server
-	NETMSG_MAP,
-	NETMSG_SNAP,
-	NETMSG_SNAPEMPTY,
-	NETMSG_SNAPSMALL,
-	
-	// sent by client
-	NETMSG_ENTERGAME,
-	NETMSG_INPUT,
-	NETMSG_SNAPACK,
-	
-	// sent by both
-	NETMSG_ERROR,
-};
-
-
-// this should be revised
-enum
-{
-	MAX_NAME_LENGTH=32,
-	MAX_CLANNAME_LENGTH=32,
-	MAX_INPUT_SIZE=128,
-	MAX_SNAPSHOT_SIZE=64*1024,
-	MAX_SNAPSHOT_PACKSIZE=768
-};
-
-
-class snapshot_storage
-{
-	struct holder
-	{
-		int64 tagtime;
-		int tick;
-		int data_size;
-		int *data() { return (int *)(this+1); }
-	};
-	
-	ring_buffer buffer;
-	
-public:
-	void purge_until(int tick)
-	{
-		while(1)
-		{
-			ring_buffer::item *i = buffer.first();
-			if(!i)
-				break;
-			holder *h = (holder *)i->data();
-			if(h->tick < tick)
-				buffer.pop_first();
-			else
-				break;
-		}
-	}
-	
-	void purge_all()
-	{
-		buffer.reset();
-	}
-
-	void add(int tick, int64 tagtime, int data_size, void *data)
-	{
-		holder *h = (holder *)buffer.alloc(sizeof(holder)+data_size);
-		h->tick = tick;
-		h->data_size = data_size;
-		h->tagtime = tagtime;
-		mem_copy(h->data(), data, data_size);
-	}
-	
-	int get(int tick, int64 *tagtime, void **data)
-	{
-		ring_buffer::item *i = buffer.first();
-		while(i)
-		{
-			holder *h = (holder *)i->data();
-			if(h->tick == tick)
-			{
-				if(data)
-					*data = h->data();
-				if(tagtime)
-					*tagtime = h->tagtime;
-				return h->data_size;
-			}
-				
-			i = i->next;
-		}
-		
-		return -1;
-	}
-};
-
-class snapshot_builder
-{
-public:
-	static const int MAX_ITEMS = 512;
-
-	char data[MAX_SNAPSHOT_SIZE];
-	int data_size;
-
-	int offsets[MAX_ITEMS];
-	int num_items;
-
-	int top_size;
-	int top_items;
-
-	int snapnum;
-
-	snapshot_builder()
-	{
-		top_size = 0;
-		top_items = 0;
-		snapnum = 0;
-	}
-
-	void start()
-	{
-		data_size = 0;
-		num_items = 0;
-	}
-	
-	snapshot::item *get_item(int index) 
-	{
-		return (snapshot::item *)&(data[offsets[index]]);
-	}
-	
-	int *get_item_data(int key)
-	{
-		for(int i = 0; i < num_items; i++)
-		{
-			if(get_item(i)->key() == key)
-				return (int *)get_item(i)->data();
-		}
-		return 0;
-	}
-
-	int finish(void *snapdata)
-	{
-		snapnum++;
-
-		// flattern and make the snapshot
-		snapshot *snap = (snapshot *)snapdata;
-		snap->data_size = data_size;
-		snap->num_items = num_items;
-		int offset_size = sizeof(int)*num_items;
-		mem_copy(snap->offsets(), offsets, offset_size);
-		mem_copy(snap->data_start(), data, data_size);
-		return sizeof(snapshot) + offset_size + data_size;
-	}
-
-	void *new_item(int type, int id, int size)
-	{
-		snapshot::item *obj = (snapshot::item *)(data+data_size);
-		mem_zero(obj, sizeof(snapshot::item) + size);
-		obj->type_and_id = (type<<16)|id;
-		offsets[num_items] = data_size;
-		data_size += sizeof(snapshot::item) + size;
-		num_items++;
-		
-		dbg_assert(data_size < MAX_SNAPSHOT_SIZE, "too much data");
-		dbg_assert(num_items < MAX_ITEMS, "too many items");
-
-		return obj->data();
-	}
-};
-
-class data_packer
-{
-	enum
-	{
-		BUFFER_SIZE=1024*2
-	};
-	
-	unsigned char buffer[BUFFER_SIZE];
-	unsigned char *current;
-	unsigned char *end;
-	int error;
-public:
-	void reset()
-	{
-		error = 0;
-		current = buffer;
-		end = current + BUFFER_SIZE;
-	}
-	
-	void add_int(int i)
-	{
-		// TODO: add space check
-		// TODO: variable length encoding perhaps
-		// TODO: add debug marker
-		current = vint_pack(current, i);
-		//*current++ = (i>>24)&0xff;
-		//*current++ = (i>>16)&0xff;
-		//*current++ = (i>>8)&0xff;
-		//*current++ = i&0xff;
-	}
-
-	void add_string(const char *p, int limit)
-	{
-		// TODO: add space check
-		// TODO: add debug marker
-		if(limit > 0)
-		{
-			while(*p && limit != 0)
-			{
-				*current++ = *p++;
-				limit--;
-			}
-			*current++ = 0;
-		}
-		else
-		{
-			while(*p)
-				*current++ = *p++;
-			*current++ = 0;
-		}
-	}
-	
-	void add_raw(const unsigned char *data, int size)
-	{
-		// TODO: add space check
-		// TODO: add debug marker
-		//add_int(size);
-		while(size)
-		{
-			*current++ = *data++;
-			size--;
-		}
-	}
-	
-	int size() const
-	{
-		return (const unsigned char *)current-(const unsigned char *)buffer;
-	}
-	
-	const unsigned char *data()
-	{
-		return (const unsigned char *)buffer;
-	}
-};
-
-class data_unpacker
-{
-	const unsigned char *current;
-	const unsigned char *start;
-	const unsigned char *end;
-	int error;
-	
-public:
-	void reset(const unsigned char *data, int size)
-	{
-		error = 0;
-		start = data;
-		end = start + size;
-		current = start;
-	}
-	
-	int get_int()
-	{
-		if(current >= end)
-			return 0;
-			
-		int i;
-		current = vint_unpack(current, &i);
-		// TODO: might be changed into variable width
-		// TODO: add range check
-		// TODO: add debug marker
-		//i = (current[0]<<24) | (current[1]<<16) | (current[2]<<8) | (current[3]);
-		//current += 4;
-		return i;
-	}
-	
-	const char *get_string()
-	{
-		if(current >= end)
-			return "";
-			
-		// TODO: add range check
-		// TODO: add debug marker
-		const char *ptr = (const char *)current;
-		while(*current) // skip the string
-			current++;
-		current++;
-		return ptr;
-	}
-	
-	const unsigned char *get_raw(int size)
-	{
-		// TODO: add range check
-		// TODO: add debug marker
-		//int s = get_int();
-		//if(size)
-			//*size = s;
-		const unsigned char *ptr = current;
-		current += size;
-		return ptr;
-	}
-};
diff --git a/src/engine/protocol.h b/src/engine/protocol.h
new file mode 100644
index 00000000..81c0480c
--- /dev/null
+++ b/src/engine/protocol.h
@@ -0,0 +1,34 @@
+#include "system.h"
+
+enum
+{
+	NETMSG_NULL=0,
+	
+	/* the first thing sent by the client
+	contains the version info for the client */
+	NETMSG_INFO=1,
+	
+	/* sent by server */
+	NETMSG_MAP,
+	NETMSG_SNAP,
+	NETMSG_SNAPEMPTY,
+	NETMSG_SNAPSMALL,
+	
+	/* sent by client */
+	NETMSG_ENTERGAME,
+	NETMSG_INPUT,
+	NETMSG_SNAPACK,
+	
+	/* sent by both */
+	NETMSG_ERROR,
+};
+
+
+/* this should be revised */
+enum
+{
+	MAX_NAME_LENGTH=32,
+	MAX_CLANNAME_LENGTH=32,
+	MAX_INPUT_SIZE=128,
+	MAX_SNAPSHOT_PACKSIZE=1200
+};
diff --git a/src/engine/ringbuffer.h b/src/engine/ringbuffer.h
deleted file mode 100644
index 3208efbf..00000000
--- a/src/engine/ringbuffer.h
+++ /dev/null
@@ -1,84 +0,0 @@
-
-// TODO: remove all the allocations from this class
-class ring_buffer
-{
-public:
-	struct item
-	{
-		item *next;
-		item *prev;
-		int size;
-		unsigned char *data() { return (unsigned char *)(this+1); }
-	};
-	
-	item *first_item;
-	item *last_item;
-	
-	unsigned buffer_size;
-	
-	ring_buffer()
-	{
-		first_item = 0;
-		last_item = 0;
-		buffer_size = 0;
-	}
-	
-	~ring_buffer()
-	{
-		reset();
-	}
-	
-	void reset()
-	{
-		// clear all
-		while(first())
-			pop_first();
-	}
-	
-	void *alloc(int size)
-	{
-		item *i = (item*)mem_alloc(sizeof(item)+size, 1);
-		i->size = size;
-		
-		i->prev = last_item;
-		i->next = 0;
-		if(last_item)
-			last_item->next = i;
-		else
-			first_item = i;
-		last_item = i;
-		
-		buffer_size += size;
-		return i->data();
-	}
-	
-	item *first()
-	{
-		return first_item;
-	}
-
-	/*
-	void *peek_data()
-	{
-		if(!first)
-			return 0;
-		return (void*)(first+1);
-	}*/
-	
-	void pop_first()
-	{
-		if(first_item)
-		{
-			item *next = first_item->next;
-			buffer_size -= first_item->size;
-			mem_free(first_item);
-			first_item = next;
-			if(first_item)
-				first_item->prev = 0;
-			else
-				last_item = 0;
-		}
-	}
-	
-	unsigned size() { return buffer_size; }
-};
diff --git a/src/engine/server/server.c b/src/engine/server/server.c
new file mode 100644
index 00000000..e07d2237
--- /dev/null
+++ b/src/engine/server/server.c
@@ -0,0 +1,659 @@
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include <engine/system.h>
+#include <engine/config.h>
+
+#include <engine/interface.h>
+
+#include <engine/protocol.h>
+#include <engine/snapshot.h>
+
+#include <engine/compression.h>
+#include <engine/versions.h>
+
+#include <engine/network.h>
+#include <engine/config.h>
+#include <engine/packer.h>
+
+#include <mastersrv/mastersrv.h>
+
+static SNAPBUILD builder;
+
+static int64 lasttick;
+static int64 lastheartbeat;
+static NETADDR4 master_server;
+
+static int biggest_snapshot;
+
+void *snap_new_item(int type, int id, int size)
+{
+	dbg_assert(type >= 0 && type <=0xffff, "incorrect type");
+	dbg_assert(id >= 0 && id <=0xffff, "incorrect id");
+	return snapbuild_new_item(&builder, type, id, size);
+}
+
+typedef struct
+{
+	short next;
+	short state; // 0 = free, 1 = alloced, 2 = timed
+	int timeout_tick;
+} SNAP_ID;
+
+static const int MAX_IDS = 8*1024; // should be lowered
+static SNAP_ID snap_ids[8*1024];
+static int snap_first_free_id;
+static int snap_first_timed_id;
+static int snap_last_timed_id;
+static int snap_id_usage;
+static int snap_id_inusage;
+static int snap_id_inited = 0;
+
+static void snap_init_id()
+{
+	int i;
+	for(i = 0; i < MAX_IDS; i++)
+	{
+		snap_ids[i].next = i+1;
+		snap_ids[i].state = 0;
+	}
+		
+	snap_ids[MAX_IDS-1].next = -1;
+	snap_first_free_id = 0;
+	snap_first_timed_id = -1;
+	snap_last_timed_id = -1;
+	snap_id_usage = 0;
+	snap_id_inusage = 0;
+	
+	snap_id_inited = 1;
+}
+
+int snap_new_id()
+{
+	dbg_assert(snap_id_inited == 1, "requesting id too soon");
+	
+	// process timed ids
+	while(snap_first_timed_id != -1 && snap_ids[snap_first_timed_id].timeout_tick < server_tick())
+	{
+		int next_timed = snap_ids[snap_first_timed_id].next;
+		
+		// add it to the free list
+		snap_ids[snap_first_timed_id].next = snap_first_free_id;
+		snap_ids[snap_first_timed_id].state = 0;
+		snap_first_free_id = snap_first_timed_id;
+		
+		// remove it from the timed list
+		snap_first_timed_id = next_timed;
+		if(snap_first_timed_id == -1)
+			snap_last_timed_id = -1;
+			
+		snap_id_usage--;
+	}
+	
+	int id = snap_first_free_id;
+	dbg_assert(id != -1, "id error");
+	snap_first_free_id = snap_ids[snap_first_free_id].next;
+	snap_ids[id].state = 1;
+	snap_id_usage++;
+	snap_id_inusage++;
+	return id;
+}
+
+void snap_free_id(int id)
+{
+	dbg_assert(snap_ids[id].state == 1, "id is not alloced");
+
+	snap_id_inusage--;
+	snap_ids[id].state = 2;
+	snap_ids[id].timeout_tick = server_tick() + server_tickspeed()*5;
+	snap_ids[id].next = -1;
+	
+	if(snap_last_timed_id != -1)
+	{
+		snap_ids[snap_last_timed_id].next = id;
+		snap_last_timed_id = id;
+	}
+	else
+	{
+		snap_first_timed_id = id;
+		snap_last_timed_id = id;
+	}
+}
+
+enum
+{
+	SRVCLIENT_STATE_EMPTY = 0,
+	SRVCLIENT_STATE_CONNECTING = 1,
+	SRVCLIENT_STATE_INGAME = 2,
+};
+
+//
+typedef struct
+{
+	// connection state info
+	int state;
+	int latency;
+	
+	int last_acked_snapshot;
+	SNAPSTORAGE snapshots;
+
+	char name[MAX_NAME_LENGTH];
+	char clan[MAX_CLANNAME_LENGTH];
+} CLIENT;
+
+static CLIENT clients[MAX_CLIENTS];
+static int current_tick = 0;
+static NETSERVER *net;
+
+int server_tick()
+{
+	return current_tick;
+}
+
+int server_tickspeed()
+{
+	return SERVER_TICK_SPEED;
+}
+
+int server_init()
+{
+	int i;
+	for(i = 0; i < MAX_CLIENTS; i++)
+	{
+		clients[i].state = SRVCLIENT_STATE_EMPTY;
+		clients[i].name[0] = 0;
+		clients[i].clan[0] = 0;
+		snapstorage_init(&clients[i].snapshots);
+	}
+
+	current_tick = 0;
+
+	return 0;
+}
+
+int server_getclientinfo(int client_id, CLIENT_INFO *info)
+{
+	dbg_assert(client_id >= 0 && client_id < MAX_CLIENTS, "client_id is not valid");
+	dbg_assert(info != 0, "info can not be null");
+
+	if(clients[client_id].state == SRVCLIENT_STATE_INGAME)
+	{
+		info->name = clients[client_id].name;
+		info->latency = clients[client_id].latency;
+		return 1;
+	}
+	return 0;
+}
+
+
+int server_send_msg(int client_id)
+{
+	const MSG_INFO *info = msg_get_info();
+	NETPACKET packet;
+	mem_zero(&packet, sizeof(NETPACKET));
+	
+	packet.client_id = client_id;
+	packet.data = info->data;
+	packet.data_size = info->size;
+
+	if(info->flags&MSGFLAG_VITAL)	
+		packet.flags = PACKETFLAG_VITAL;
+			
+	if(client_id == -1)
+	{
+		// broadcast
+		int i;
+		for(i = 0; i < MAX_CLIENTS; i++)
+			if(clients[i].state == SRVCLIENT_STATE_INGAME)
+			{
+				packet.client_id = i;
+				netserver_send(net, &packet);
+			}
+	}
+	else
+		netserver_send(net, &packet);
+	return 0;
+}
+
+
+static void server_do_tick()
+{
+	current_tick++;
+	mods_tick();
+}
+
+static void server_do_snap()
+{
+	mods_presnap();
+
+	int i;
+	for( i = 0; i < MAX_CLIENTS; i++)
+	{
+		if(clients[i].state == SRVCLIENT_STATE_INGAME)
+		{
+			char data[MAX_SNAPSHOT_SIZE];
+			char deltadata[MAX_SNAPSHOT_SIZE];
+			char compdata[MAX_SNAPSHOT_SIZE];
+			snapbuild_init(&builder);
+			mods_snap(i);
+
+			// finish snapshot
+			int snapshot_size = snapbuild_finish(&builder, data);
+
+			// remove old snapshos
+			// keep 1 seconds worth of snapshots
+			snapstorage_purge_until(&clients[i].snapshots, current_tick-SERVER_TICK_SPEED);
+			
+			// save it the snapshot
+			snapstorage_add(&clients[i].snapshots, current_tick, time_get(), snapshot_size, data);
+			
+			// find snapshot that we can preform delta against
+			static SNAPSHOT emptysnap;
+			emptysnap.data_size = 0;
+			emptysnap.num_items = 0;
+			
+			SNAPSHOT *deltashot = &emptysnap;
+			int deltashot_size;
+			int delta_tick = -1;
+			{
+				deltashot_size = snapstorage_get(&clients[i].snapshots, clients[i].last_acked_snapshot, 0, &deltashot);
+				if(deltashot_size >= 0)
+				//{
+					delta_tick = clients[i].last_acked_snapshot;
+					//deltashot = (SNAPSHOT *)delta_data;
+				//}
+			}
+			
+			// create delta
+			int deltasize = snapshot_create_delta(deltashot, (SNAPSHOT*)data, deltadata);
+			
+			if(deltasize)
+			{
+				// compress it
+				unsigned char intdata[MAX_SNAPSHOT_SIZE];
+				int intsize = intpack_compress(deltadata, deltasize, intdata);
+				
+				int compsize = zerobit_compress(intdata, intsize, compdata);
+				snapshot_size = compsize;
+
+				if(snapshot_size > biggest_snapshot)
+					biggest_snapshot = snapshot_size;
+
+				const int max_size = MAX_SNAPSHOT_PACKSIZE;
+				int numpackets = (snapshot_size+max_size-1)/max_size;
+				(void)numpackets;
+				int n, left;
+				for(n = 0, left = snapshot_size; left; n++)
+				{
+					int chunk = left < max_size ? left : max_size;
+					left -= chunk;
+
+					msg_pack_start_system(NETMSG_SNAP, 0);
+					msg_pack_int(current_tick);
+					msg_pack_int(current_tick-delta_tick); // compressed with
+					msg_pack_int(chunk);
+					msg_pack_raw(&compdata[n*max_size], chunk);
+					msg_pack_end();
+					server_send_msg(i);
+				}
+			}
+			else
+			{
+				msg_pack_start_system(NETMSG_SNAPEMPTY, 0);
+				msg_pack_int(current_tick);
+				msg_pack_int(current_tick-delta_tick); // compressed with
+				msg_pack_end();
+				server_send_msg(i);
+			}
+		}
+	}
+
+	mods_postsnap();
+}
+
+
+static int new_client_callback(int cid, void *user)
+{
+	clients[cid].state = SRVCLIENT_STATE_CONNECTING;
+	clients[cid].name[0] = 0;
+	clients[cid].clan[0] = 0;
+	snapstorage_purge_all(&clients[cid].snapshots);
+	clients[cid].last_acked_snapshot = -1;
+	return 0;
+}
+
+static int del_client_callback(int cid, void *user)
+{
+	clients[cid].state = SRVCLIENT_STATE_EMPTY;
+	clients[cid].name[0] = 0;
+	clients[cid].clan[0] = 0;
+	snapstorage_purge_all(&clients[cid].snapshots);
+	
+	mods_client_drop(cid);
+	return 0;
+}
+
+
+static void server_send_map(int cid)
+{
+	msg_pack_start_system(NETMSG_MAP, MSGFLAG_VITAL);
+	msg_pack_string(config.sv_map, 0);
+	msg_pack_end();
+	server_send_msg(cid);
+}
+	
+static void server_send_heartbeat()
+{
+	NETPACKET packet;
+	packet.client_id = -1;
+	packet.address = master_server;
+	packet.flags = PACKETFLAG_CONNLESS;
+	packet.data_size = sizeof(SERVERBROWSE_HEARTBEAT);
+	packet.data = SERVERBROWSE_HEARTBEAT;
+	netserver_send(net, &packet);
+}
+
+static void server_process_client_packet(NETPACKET *packet)
+{
+	int cid = packet->client_id;
+	int sys;
+	int msg = msg_unpack_start(packet->data, packet->data_size, &sys);
+	if(sys)
+	{
+		// system message
+		if(msg == NETMSG_INFO)
+		{
+			char version[64];
+			strncpy(version, msg_unpack_string(), 64);
+			if(strcmp(version, TEEWARS_NETVERSION_STRING) != 0)
+			{
+				// OH FUCK! wrong version, drop him
+				char reason[256];
+				sprintf(reason, "wrong version. server is running %s.", TEEWARS_NETVERSION_STRING);
+				netserver_drop(net, cid, reason);
+				return;
+			}
+			
+			strncpy(clients[cid].name, msg_unpack_string(), MAX_NAME_LENGTH);
+			strncpy(clients[cid].clan, msg_unpack_string(), MAX_CLANNAME_LENGTH);
+			const char *password = msg_unpack_string();
+			const char *skin = msg_unpack_string();
+			(void)password; // ignore these variables
+			(void)skin;
+			server_send_map(cid);
+		}
+		else if(msg == NETMSG_ENTERGAME)
+		{
+			if(clients[cid].state != SRVCLIENT_STATE_INGAME)
+			{
+				dbg_msg("server", "player as entered the game. cid=%x", cid);
+				clients[cid].state = SRVCLIENT_STATE_INGAME;
+				mods_client_enter(cid);
+			}
+		}
+		else if(msg == NETMSG_INPUT)
+		{
+			int input[MAX_INPUT_SIZE];
+			int size = msg_unpack_int();
+			int i;
+			for(i = 0; i < size/4; i++)
+				input[i] = msg_unpack_int();
+			mods_client_input(cid, input);
+		}
+		else if(msg == NETMSG_SNAPACK)
+		{
+			clients[cid].last_acked_snapshot = msg_unpack_int();
+			int64 tagtime;
+			if(snapstorage_get(&clients[cid].snapshots, clients[cid].last_acked_snapshot, &tagtime, 0) >= 0)
+				clients[cid].latency = (int)(((time_get()-tagtime)*1000)/time_freq());
+		}
+		else
+		{
+			dbg_msg("server", "strange message cid=%d msg=%d data_size=%d", cid, msg, packet->data_size);
+		}
+	}
+	else
+	{
+		// game message
+		mods_message(msg, cid);
+	}
+}
+
+static void server_send_serverinfo(NETADDR4 *addr)
+{
+	NETPACKET packet;
+	
+	PACKER p;
+	packer_reset(&p);
+	packer_add_raw(&p, SERVERBROWSE_INFO, sizeof(SERVERBROWSE_INFO));
+	packer_add_string(&p, config.sv_name, 128);
+	packer_add_string(&p, config.sv_map, 128);
+	packer_add_int(&p, netserver_max_clients(net)); // max_players
+	int c = 0;
+	int i;
+	for(i = 0; i < MAX_CLIENTS; i++)
+	{
+		if(!clients[i].state != SRVCLIENT_STATE_EMPTY)
+			c++;
+	}
+	packer_add_int(&p, c); // num_players
+	
+	packet.client_id = -1;
+	packet.address = *addr;
+	packet.flags = PACKETFLAG_CONNLESS;
+	packet.data_size = packer_size(&p);
+	packet.data = packer_data(&p);
+	netserver_send(net, &packet);
+}
+
+
+static void server_send_fwcheckresponse(NETADDR4 *addr)
+{
+	NETPACKET packet;
+	packet.client_id = -1;
+	packet.address = *addr;
+	packet.flags = PACKETFLAG_CONNLESS;
+	packet.data_size = sizeof(SERVERBROWSE_FWRESPONSE);
+	packet.data = SERVERBROWSE_FWRESPONSE;
+	netserver_send(net, &packet);
+}
+
+static void server_pump_network()
+{
+	netserver_update(net);
+	
+	// process packets
+	NETPACKET packet;
+	while(netserver_recv(net, &packet))
+	{
+		if(packet.client_id == -1)
+		{
+			// stateless
+			if(packet.data_size == sizeof(SERVERBROWSE_GETINFO) &&
+				memcmp(packet.data, SERVERBROWSE_GETINFO, sizeof(SERVERBROWSE_GETINFO)) == 0)
+			{
+				server_send_serverinfo(&packet.address);
+			}
+			else if(packet.data_size == sizeof(SERVERBROWSE_FWCHECK) &&
+				memcmp(packet.data, SERVERBROWSE_FWCHECK, sizeof(SERVERBROWSE_FWCHECK)) == 0)
+			{
+				server_send_fwcheckresponse(&packet.address);
+			}
+			else if(packet.data_size == sizeof(SERVERBROWSE_FWOK) &&
+				memcmp(packet.data, SERVERBROWSE_FWOK, sizeof(SERVERBROWSE_FWOK)) == 0)
+			{
+				if(config.debug)
+					dbg_msg("server", "no firewall/nat problems detected");
+			}
+			else if(packet.data_size == sizeof(SERVERBROWSE_FWERROR) &&
+				memcmp(packet.data, SERVERBROWSE_FWERROR, sizeof(SERVERBROWSE_FWERROR)) == 0)
+			{
+				dbg_msg("server", "ERROR: the master server reports that clients can not connect to this server.");
+				dbg_msg("server", "ERROR: configure your firewall/nat to let trough udp on port %d.", 8303);
+			}
+		}
+		else
+			server_process_client_packet(&packet);
+	}
+}
+
+
+static int server_run()
+{
+	biggest_snapshot = 0;
+
+	net_init(); // For Windows compatibility.
+	
+	snap_init_id();
+
+	// load map
+	if(!map_load(config.sv_map))
+	{
+		dbg_msg("server", "failed to load map. mapname='%s'", config.sv_map);
+		return -1;
+	}
+	
+	// start server
+	NETADDR4 bindaddr;
+
+	if(strlen(config.sv_bindaddr) && net_host_lookup(config.sv_bindaddr, config.sv_port, &bindaddr) != 0)
+	{
+		// sweet!
+	}
+	else
+	{
+		mem_zero(&bindaddr, sizeof(bindaddr));
+		bindaddr.port = config.sv_port;
+	}
+	
+	net = netserver_open(bindaddr, config.sv_max_clients, 0);
+	if(!net)
+	{
+		dbg_msg("server", "couldn't open socket. port might already be in use");
+		return -1;
+	}
+	
+	netserver_set_callbacks(net, new_client_callback, del_client_callback, 0);
+	
+	dbg_msg("server", "server name is '%s'", config.sv_name);
+	dbg_msg("server", "masterserver is '%s'", config.masterserver);
+	if (net_host_lookup(config.masterserver, MASTERSERVER_PORT, &master_server) != 0)
+	{
+		// TODO: fix me
+		//master_server = netaddr4(0, 0, 0, 0, 0);
+	}
+
+	mods_init();
+
+	int64 time_per_tick = time_freq()/SERVER_TICK_SPEED;
+	int64 time_per_heartbeat = time_freq() * 30;
+	int64 starttime = time_get();
+	lasttick = starttime;
+	lastheartbeat = 0;
+
+	int64 reporttime = time_get();
+	int reportinterval = 3;
+
+	int64 simulationtime = 0;
+	int64 snaptime = 0;
+	int64 networktime = 0;
+	int64 totaltime = 0;
+
+	while(1)
+	{
+		int64 t = time_get();
+		if(t-lasttick > time_per_tick)
+		{
+			{
+				int64 start = time_get();
+				server_do_tick();
+				simulationtime += time_get()-start;
+			}
+
+			{
+				int64 start = time_get();
+				server_do_snap();
+				snaptime += time_get()-start;
+			}
+
+			lasttick += time_per_tick;
+		}
+
+		if(config.sv_sendheartbeats)
+		{
+			if (t > lastheartbeat+time_per_heartbeat)
+			{
+				server_send_heartbeat();
+				lastheartbeat = t+time_per_heartbeat;
+			}
+		}
+
+		{
+			int64 start = time_get();
+			server_pump_network();
+			networktime += time_get()-start;
+		}
+
+		if(reporttime < time_get())
+		{
+			if(config.debug)
+			{
+				dbg_msg("server", "sim=%.02fms snap=%.02fms net=%.02fms total=%.02fms load=%.02f%% ids=%d/%d",
+					(simulationtime/reportinterval)/(double)time_freq()*1000,
+					(snaptime/reportinterval)/(double)time_freq()*1000,
+					(networktime/reportinterval)/(double)time_freq()*1000,
+					(totaltime/reportinterval)/(double)time_freq()*1000,
+					(totaltime)/reportinterval/(double)time_freq()*100.0f,
+					snap_id_inusage, snap_id_usage);
+			}
+
+			simulationtime = 0;
+			snaptime = 0;
+			networktime = 0;
+			totaltime = 0;
+
+			reporttime += time_freq()*reportinterval;
+		}
+		totaltime += time_get()-t;
+		thread_sleep(1);
+	}
+
+	mods_shutdown();
+	map_unload();
+
+	return 0;
+}
+
+
+int main(int argc, char **argv)
+{
+	dbg_msg("server", "starting...");
+
+	config_reset();
+
+#ifdef CONF_PLATFORM_MACOSX
+	const char *config_filename = "~/.teewars";
+#else
+	const char *config_filename = "default.cfg";
+#endif
+
+	int i;
+	for(i = 1; i < argc; i++)
+	{
+		if(argv[i][0] == '-' && argv[i][1] == 'f' && argv[i][2] == 0 && argc - i > 1)
+		{
+			config_filename = argv[i+1];
+			i++;
+		}
+	}
+
+	config_load(config_filename);
+
+	// parse arguments
+	for(i = 1; i < argc; i++)
+		config_set(argv[i]);
+
+	server_run();
+	return 0;
+}
diff --git a/src/engine/server/server.cpp b/src/engine/server/server.cpp
deleted file mode 100644
index 984292e9..00000000
--- a/src/engine/server/server.cpp
+++ /dev/null
@@ -1,702 +0,0 @@
-#include <cstdio>
-#include <cstring>
-#include <cstdlib>
-
-#include <baselib/system.h>
-#include <baselib/config.h>
-
-#include <engine/interface.h>
-
-#include <engine/packet.h>
-#include <engine/snapshot.h>
-
-#include <engine/compression.h>
-#include <engine/versions.h>
-
-#include <engine/network.h>
-#include <engine/config.h>
-
-#include <mastersrv/mastersrv.h>
-
-namespace baselib {}
-using namespace baselib;
-
-static snapshot_builder builder;
-
-void *snap_new_item(int type, int id, int size)
-{
-	dbg_assert(type >= 0 && type <=0xffff, "incorrect type");
-	dbg_assert(id >= 0 && id <=0xffff, "incorrect id");
-	return builder.new_item(type, id, size);
-}
-
-
-struct snap_id
-{
-	short next;
-	short state; // 0 = free, 1 = alloced, 2 = timed
-	int timeout_tick;
-};
-
-static const int MAX_IDS = 8*1024; // should be lowered
-static snap_id snap_ids[8*1024];
-static int snap_first_free_id;
-static int snap_first_timed_id;
-static int snap_last_timed_id;
-static int snap_id_usage;
-static int snap_id_inusage;
-
-static int snap_id_inited = 0;
-
-void snap_init_id()
-{
-	for(int i = 0; i < MAX_IDS; i++)
-	{
-		snap_ids[i].next = i+1;
-		snap_ids[i].state = 0;
-	}
-		
-	snap_ids[MAX_IDS-1].next = -1;
-	snap_first_free_id = 0;
-	snap_first_timed_id = -1;
-	snap_last_timed_id = -1;
-	snap_id_usage = 0;
-	snap_id_inusage = 0;
-	
-	snap_id_inited = 1;
-}
-
-int snap_new_id()
-{
-	dbg_assert(snap_id_inited == 1, "requesting id too soon");
-	
-	// process timed ids
-	while(snap_first_timed_id != -1 && snap_ids[snap_first_timed_id].timeout_tick < server_tick())
-	{
-		int next_timed = snap_ids[snap_first_timed_id].next;
-		
-		// add it to the free list
-		snap_ids[snap_first_timed_id].next = snap_first_free_id;
-		snap_ids[snap_first_timed_id].state = 0;
-		snap_first_free_id = snap_first_timed_id;
-		
-		// remove it from the timed list
-		snap_first_timed_id = next_timed;
-		if(snap_first_timed_id == -1)
-			snap_last_timed_id = -1;
-			
-		snap_id_usage--;
-	}
-	
-	int id = snap_first_free_id;
-	dbg_assert(id != -1, "id error");
-	snap_first_free_id = snap_ids[snap_first_free_id].next;
-	snap_ids[id].state = 1;
-	snap_id_usage++;
-	snap_id_inusage++;
-	return id;
-}
-
-void snap_free_id(int id)
-{
-	dbg_assert(snap_ids[id].state == 1, "id is not alloced");
-
-	snap_id_inusage--;
-	snap_ids[id].state = 2;
-	snap_ids[id].timeout_tick = server_tick() + server_tickspeed()*5;
-	snap_ids[id].next = -1;
-	
-	if(snap_last_timed_id != -1)
-	{
-		snap_ids[snap_last_timed_id].next = id;
-		snap_last_timed_id = id;
-	}
-	else
-	{
-		snap_first_timed_id = id;
-		snap_last_timed_id = id;
-	}
-}
-
-
-
-
-//
-class client
-{
-public:
-	enum
-	{
-		STATE_EMPTY = 0,
-		STATE_CONNECTING = 1,
-		STATE_INGAME = 2,
-	};
-
-	struct stored_snapshot
-	{
-		int64 send_time;
-		snapshot snap;
-	};
-
-	// connection state info
-	int state;
-	int latency;
-	
-	int last_acked_snapshot;
-	snapshot_storage snapshots;
-
-	char name[MAX_NAME_LENGTH];
-	char clan[MAX_CLANNAME_LENGTH];
-
-	bool is_empty() const { return state == STATE_EMPTY; }
-	bool is_ingame() const { return state == STATE_INGAME; }
-};
-
-static client clients[MAX_CLIENTS];
-static int current_tick = 0;
-static net_server net;
-
-int server_tick()
-{
-	return current_tick;
-}
-
-int server_tickspeed()
-{
-	return SERVER_TICK_SPEED;
-}
-
-int server_init()
-{
-	for(int i = 0; i < MAX_CLIENTS; i++)
-	{
-		clients[i].state = client::STATE_EMPTY;
-		clients[i].name[0] = 0;
-		clients[i].clan[0] = 0;
-		//clients[i].lastactivity = 0;
-	}
-
-	current_tick = 0;
-
-	return 0;
-}
-
-int server_getclientinfo(int client_id, client_info *info)
-{
-	dbg_assert(client_id >= 0 && client_id < MAX_CLIENTS, "client_id is not valid");
-	dbg_assert(info != 0, "info can not be null");
-
-	if(clients[client_id].is_ingame())
-	{
-		info->name = clients[client_id].name;
-		info->latency = clients[client_id].latency;
-		return 1;
-	}
-	return 0;
-}
-
-
-int server_send_msg(int client_id)
-{
-	const msg_info *info = msg_get_info();
-	NETPACKET packet;
-	mem_zero(&packet, sizeof(NETPACKET));
-	
-	packet.client_id = client_id;
-	packet.data = info->data;
-	packet.data_size = info->size;
-
-	if(info->flags&MSGFLAG_VITAL)	
-		packet.flags = PACKETFLAG_VITAL;
-			
-	if(client_id == -1)
-	{
-		// broadcast
-		for(int i = 0; i < MAX_CLIENTS; i++)
-			if(clients[i].is_ingame())
-			{
-				packet.client_id = i;
-				net.send(&packet);
-			}
-	}
-	else
-		net.send(&packet);
-	return 0;
-}
-
-static int new_client_callback(int cid, void *user)
-{
-	clients[cid].state = client::STATE_CONNECTING;
-	clients[cid].name[0] = 0;
-	clients[cid].clan[0] = 0;
-	clients[cid].snapshots.purge_all();
-	clients[cid].last_acked_snapshot = -1;
-	return 0;
-}
-
-static int del_client_callback(int cid, void *user)
-{
-	clients[cid].state = client::STATE_EMPTY;
-	clients[cid].name[0] = 0;
-	clients[cid].clan[0] = 0;
-	clients[cid].snapshots.purge_all();
-	
-	mods_client_drop(cid);
-	return 0;
-}
-		
-// TODO: remove this class
-class server
-{
-public:
-	//socket_udp4 game_socket;
-	int64 lasttick;
-	int64 lastheartbeat;
-	netaddr4 master_server;
-
-	int biggest_snapshot;
-
-	bool run()
-	{
-		biggest_snapshot = 0;
-
-		net_init(); // For Windows compatibility.
-		
-		snap_init_id();
-
-		// load map
-		if(!map_load(config.sv_map))
-		{
-			dbg_msg("server", "failed to load map. mapname='%s'", config.sv_map);
-			return false;
-		}
-		
-		// start server
-		NETADDR4 bindaddr;
-
-		if(strlen(config.sv_bindaddr) && net_host_lookup(config.sv_bindaddr, config.sv_port, &bindaddr) != 0)
-		{
-			// sweet!	
-		}
-		else
-		{
-			mem_zero(&bindaddr, sizeof(bindaddr));
-			bindaddr.port = config.sv_port;
-		}
-		
-		if(!net.open(bindaddr, config.sv_max_clients, 0))
-		{
-			dbg_msg("server", "couldn't open socket. port might already be in use");
-			return false;
-		}
-		
-		net.set_callbacks(new_client_callback, del_client_callback, 0);
-		
-		dbg_msg("server", "server name is '%s'", config.sv_name);
-		dbg_msg("server", "masterserver is '%s'", config.masterserver);
-		if (net_host_lookup(config.masterserver, MASTERSERVER_PORT, &master_server) != 0)
-		{
-			// TODO: fix me
-			//master_server = netaddr4(0, 0, 0, 0, 0);
-		}
-
-		mods_init();
-
-		int64 time_per_tick = time_freq()/SERVER_TICK_SPEED;
-		int64 time_per_heartbeat = time_freq() * 30;
-		int64 starttime = time_get();
-		//int64 lasttick = starttime;
-		lasttick = starttime;
-		lastheartbeat = 0;
-
-		int64 reporttime = time_get();
-		int reportinterval = 3;
-		//int64 reportinterval = time_freq()*3;
-
-		int64 simulationtime = 0;
-		int64 snaptime = 0;
-		int64 networktime = 0;
-		int64 totaltime = 0;
-
-		while(true)
-		{
-			int64 t = time_get();
-			if(t-lasttick > time_per_tick)
-			{
-				{
-					int64 start = time_get();
-					tick();
-					simulationtime += time_get()-start;
-				}
-
-				{
-					int64 start = time_get();
-					snap();
-					snaptime += time_get()-start;
-				}
-
-				lasttick += time_per_tick;
-			}
-
-			if(config.sv_sendheartbeats)
-			{
-				if (t > lastheartbeat+time_per_heartbeat)
-				{
-					send_heartbeat();
-					lastheartbeat = t+time_per_heartbeat;
-				}
-			}
-
-			{
-				int64 start = time_get();
-				pump_network();
-				networktime += time_get()-start;
-			}
-
-			if(reporttime < time_get())
-			{
-				if(config.debug)
-				{
-					dbg_msg("server", "sim=%.02fms snap=%.02fms net=%.02fms total=%.02fms load=%.02f%% ids=%d/%d",
-						(simulationtime/reportinterval)/(double)time_freq()*1000,
-						(snaptime/reportinterval)/(double)time_freq()*1000,
-						(networktime/reportinterval)/(double)time_freq()*1000,
-						(totaltime/reportinterval)/(double)time_freq()*1000,
-						(totaltime)/reportinterval/(double)time_freq()*100.0f,
-						snap_id_inusage, snap_id_usage);
-				}
-
-				simulationtime = 0;
-				snaptime = 0;
-				networktime = 0;
-				totaltime = 0;
-
-				reporttime += time_freq()*reportinterval;
-			}
-			totaltime += time_get()-t;
-			thread_sleep(1);
-		}
-
-		mods_shutdown();
-		map_unload();
-	}
-
-	void tick()
-	{
-		current_tick++;
-		mods_tick();
-	}
-
-	void snap()
-	{
-		//if(current_tick&1)
-		//	return;
-		mods_presnap();
-
-		for(int i = 0; i < MAX_CLIENTS; i++)
-		{
-			if(clients[i].is_ingame())
-			{
-				char data[MAX_SNAPSHOT_SIZE];
-				char deltadata[MAX_SNAPSHOT_SIZE];
-				char compdata[MAX_SNAPSHOT_SIZE];
-				//char intdata[MAX_SNAPSHOT_SIZE];
-				builder.start();
-				mods_snap(i);
-
-				// finish snapshot
-				int snapshot_size = builder.finish(data);
-
-				// remove old snapshos
-				// keep 1 seconds worth of snapshots
-				clients[i].snapshots.purge_until(current_tick-SERVER_TICK_SPEED);
-				
-				// save it the snapshot
-				clients[i].snapshots.add(current_tick, time_get(), snapshot_size, data);
-				
-				// find snapshot that we can preform delta against
-				static snapshot emptysnap;
-				emptysnap.data_size = 0;
-				emptysnap.num_items = 0;
-				
-				snapshot *deltashot = &emptysnap;
-				int deltashot_size;
-				int delta_tick = -1;
-				{
-					void *delta_data;
-					deltashot_size = clients[i].snapshots.get(clients[i].last_acked_snapshot, 0, (void **)&delta_data);
-					if(deltashot_size >= 0)
-					{
-						delta_tick = clients[i].last_acked_snapshot;
-						deltashot = (snapshot *)delta_data;
-					}
-				}
-				
-				// create delta
-				int deltasize = snapshot_create_delta(deltashot, (snapshot*)data, deltadata);
-				
-				if(deltasize)
-				{
-					// compress it
-					//int intsize = -1;
-					unsigned char intdata[MAX_SNAPSHOT_SIZE];
-					int intsize = intpack_compress(deltadata, deltasize, intdata);
-					
-					int compsize = zerobit_compress(intdata, intsize, compdata);
-					//dbg_msg("compress", "%5d --delta-> %5d --int-> %5d --zero-> %5d %5d",
-						//snapshot_size, deltasize, intsize, compsize, intsize-compsize);
-					snapshot_size = compsize;
-
-					if(snapshot_size > biggest_snapshot)
-						biggest_snapshot = snapshot_size;
-
-					const int max_size = MAX_SNAPSHOT_PACKSIZE;
-					int numpackets = (snapshot_size+max_size-1)/max_size;
-					(void)numpackets;
-					for(int n = 0, left = snapshot_size; left; n++)
-					{
-						int chunk = left < max_size ? left : max_size;
-						left -= chunk;
-
-						//if(numpackets == 1)
-						//	msg_pack_start_system(NETMSG_SNAPSMALL, 0);
-						//else
-						msg_pack_start_system(NETMSG_SNAP, 0);
-						msg_pack_int(current_tick);
-						msg_pack_int(current_tick-delta_tick); // compressed with
-						msg_pack_int(chunk);
-						msg_pack_raw(&compdata[n*max_size], chunk);
-						msg_pack_end();
-						//const msg_info *info = msg_get_info();
-						//dbg_msg("server", "size=%d", info->size);
-						server_send_msg(i);
-					}
-				}
-				else
-				{
-					msg_pack_start_system(NETMSG_SNAPEMPTY, 0);
-					msg_pack_int(current_tick);
-					msg_pack_int(current_tick-delta_tick); // compressed with
-					msg_pack_end();
-					server_send_msg(i);
-				}
-			}
-		}
-
-		mods_postsnap();
-	}
-
-	void send_map(int cid)
-	{
-		msg_pack_start_system(NETMSG_MAP, MSGFLAG_VITAL);
-		msg_pack_string(config.sv_map, 0);
-		msg_pack_end();
-		server_send_msg(cid);
-	}
-	
-	void send_heartbeat()
-	{
-		NETPACKET packet;
-		packet.client_id = -1;
-		packet.address = master_server;
-		packet.flags = PACKETFLAG_CONNLESS;
-		packet.data_size = sizeof(SERVERBROWSE_HEARTBEAT);
-		packet.data = SERVERBROWSE_HEARTBEAT;
-		net.send(&packet);
-	}
-
-	void drop(int cid, const char *reason)
-	{
-		if(clients[cid].state == client::STATE_EMPTY)
-			return;
-
-		clients[cid].state = client::STATE_EMPTY;
-		mods_client_drop(cid);
-		dbg_msg("server", "player dropped. reason='%s' cid=%x name='%s'", reason, cid, clients[cid].name);
-	}
-
-	void process_client_packet(NETPACKET *packet)
-	{
-		int cid = packet->client_id;
-		int sys;
-		int msg = msg_unpack_start(packet->data, packet->data_size, &sys);
-		if(sys)
-		{
-			// system message
-			if(msg == NETMSG_INFO)
-			{
-				char version[64];
-				strncpy(version, msg_unpack_string(), 64);
-				if(strcmp(version, TEEWARS_NETVERSION_STRING) != 0)
-				//if(strcmp(version, "ERROR") != 0)
-				{
-					// OH FUCK! wrong version, drop him
-					char reason[256];
-					sprintf(reason, "wrong version. server is running %s.", TEEWARS_NETVERSION_STRING);
-					net.drop(cid, reason);
-					return;
-				}
-				
-				strncpy(clients[cid].name, msg_unpack_string(), MAX_NAME_LENGTH);
-				strncpy(clients[cid].clan, msg_unpack_string(), MAX_CLANNAME_LENGTH);
-				const char *password = msg_unpack_string();
-				const char *skin = msg_unpack_string();
-				(void)password; // ignore these variables
-				(void)skin;
-				send_map(cid);
-			}
-			else if(msg == NETMSG_ENTERGAME)
-			{
-				if(clients[cid].state != client::STATE_INGAME)
-				{
-					dbg_msg("server", "player as entered the game. cid=%x", cid);
-					clients[cid].state = client::STATE_INGAME;
-					mods_client_enter(cid);
-				}
-			}
-			else if(msg == NETMSG_INPUT)
-			{
-				int input[MAX_INPUT_SIZE];
-				int size = msg_unpack_int();
-				for(int i = 0; i < size/4; i++)
-					input[i] = msg_unpack_int();
-				mods_client_input(cid, input);
-			}
-			else if(msg == NETMSG_SNAPACK)
-			{
-				clients[cid].last_acked_snapshot = msg_unpack_int();
-				int64 tagtime;
-				if(clients[cid].snapshots.get(clients[cid].last_acked_snapshot, &tagtime, 0) >= 0)
-					clients[cid].latency = (int)(((time_get()-tagtime)*1000)/time_freq());
-			}
-			else
-			{
-				dbg_msg("server", "strange message cid=%d msg=%d data_size=%d", cid, msg, packet->data_size);
-			}
-		}
-		else
-		{
-			// game message
-			mods_message(msg, cid);
-		}
-	}
-
-	void process_packet(NETPACKET *packet)
-	{
-	}
-
-	void client_timeout(int clientId)
-	{
-		drop(clientId, "client timedout");
-	}
-
-	void send_serverinfo(NETADDR4 *addr)
-	{
-		NETPACKET packet;
-		
-		data_packer packer;
-		packer.reset();
-		packer.add_raw(SERVERBROWSE_INFO, sizeof(SERVERBROWSE_INFO));
-		packer.add_string(config.sv_name, 128);
-		packer.add_string(config.sv_map, 128);
-		packer.add_int(MAX_CLIENTS); // max_players
-		int c = 0;
-		for(int i = 0; i < MAX_CLIENTS; i++)
-		{
-			if(!clients[i].is_empty())
-				c++;
-		}
-		packer.add_int(c); // num_players
-		
-		packet.client_id = -1;
-		packet.address = *addr;
-		packet.flags = PACKETFLAG_CONNLESS;
-		packet.data_size = packer.size();
-		packet.data = packer.data();
-		net.send(&packet);
-	}
-
-
-	void send_fwcheckresponse(NETADDR4 *addr)
-	{
-		NETPACKET packet;
-		packet.client_id = -1;
-		packet.address = *addr;
-		packet.flags = PACKETFLAG_CONNLESS;
-		packet.data_size = sizeof(SERVERBROWSE_FWRESPONSE);
-		packet.data = SERVERBROWSE_FWRESPONSE;
-		net.send(&packet);
-	}
-
-	void pump_network()
-	{
-		net.update();
-		
-		// process packets
-		NETPACKET packet;
-		while(net.recv(&packet))
-		{
-			if(packet.client_id == -1)
-			{
-				// stateless
-				if(packet.data_size == sizeof(SERVERBROWSE_GETINFO) &&
-					memcmp(packet.data, SERVERBROWSE_GETINFO, sizeof(SERVERBROWSE_GETINFO)) == 0)
-				{
-					send_serverinfo(&packet.address);
-				}
-				else if(packet.data_size == sizeof(SERVERBROWSE_FWCHECK) &&
-					memcmp(packet.data, SERVERBROWSE_FWCHECK, sizeof(SERVERBROWSE_FWCHECK)) == 0)
-				{
-					send_fwcheckresponse(&packet.address);
-				}
-				else if(packet.data_size == sizeof(SERVERBROWSE_FWOK) &&
-					memcmp(packet.data, SERVERBROWSE_FWOK, sizeof(SERVERBROWSE_FWOK)) == 0)
-				{
-					if(config.debug)
-						dbg_msg("server", "no firewall/nat problems detected");
-				}
-				else if(packet.data_size == sizeof(SERVERBROWSE_FWERROR) &&
-					memcmp(packet.data, SERVERBROWSE_FWERROR, sizeof(SERVERBROWSE_FWERROR)) == 0)
-				{
-					dbg_msg("server", "ERROR: the master server reports that clients can not connect to this server.");
-					dbg_msg("server", "ERROR: configure your firewall/nat to let trough udp on port %d.", 8303);
-				}
-			}
-			else
-				process_client_packet(&packet);
-		}
-	}
-};
-
-int main(int argc, char **argv)
-{
-	dbg_msg("server", "starting...");
-
-	config_reset();
-
-#ifdef CONF_PLATFORM_MACOSX
-	const char *config_filename = "~/.teewars";
-#else
-	const char *config_filename = "default.cfg";
-#endif
-
-	for(int i = 1; i < argc; i++)
-	{
-		if(argv[i][0] == '-' && argv[i][1] == 'f' && argv[i][2] == 0 && argc - i > 1)
-		{
-			config_filename = argv[i+1];
-			i++;
-		}
-	}
-
-	config_load(config_filename);
-
-	// parse arguments
-	for(int i = 1; i < argc; i++)
-		config_set(argv[i]);
-
-	server_init();
-	server s;
-	s.run();
-	return 0;
-}
diff --git a/src/engine/snapshot.c b/src/engine/snapshot.c
new file mode 100644
index 00000000..72e73642
--- /dev/null
+++ b/src/engine/snapshot.c
@@ -0,0 +1,441 @@
+
+#include "packet.h"
+#include "snapshot.h"
+
+
+int *snapitem_data(SNAPSHOT_ITEM *item) { return (int *)(item+1); }
+int snapitem_type(SNAPSHOT_ITEM *item) { return item->type_and_id>>16; }
+int snapitem_id(SNAPSHOT_ITEM *item) { return item->type_and_id&0xffff; }
+int snapitem_key(SNAPSHOT_ITEM *item) { return item->type_and_id; }
+
+int *snapshot_offsets(SNAPSHOT *snap) { return (int *)(snap+1); }
+char *snapshot_datastart(SNAPSHOT *snap) { return (char*)(snapshot_offsets(snap)+snap->num_items); }
+
+SNAPSHOT_ITEM *snapshot_get_item(SNAPSHOT *snap, int index)
+{ return (SNAPSHOT_ITEM *)(snapshot_datastart(snap) + snapshot_offsets(snap)[index]); };
+
+int snapshot_get_item_datasize(SNAPSHOT *snap, int index)
+{
+    if(index == snap->num_items-1)
+        return (snap->data_size - snapshot_offsets(snap)[index]) - sizeof(SNAPSHOT_ITEM);
+    return (snapshot_offsets(snap)[index+1] - snapshot_offsets(snap)[index]) - sizeof(SNAPSHOT_ITEM);
+}
+
+int snapshot_get_item_index(SNAPSHOT *snap, int key)
+{
+    /* TODO: this should not be a linear search. very bad */
+    int i;
+    for(i = 0; i < snap->num_items; i++)
+    {
+        if(snapitem_key(snapshot_get_item(snap, i)) == key)
+            return i;
+    }
+    return -1;
+}
+
+
+
+typedef struct
+{
+	int num_deleted_items;
+	int num_update_items;
+	int num_temp_items; /* needed? */
+	int data[1];
+	
+	/*
+	char *data_start() { return (char *)&offsets[num_deleted_items+num_update_items+num_temp_items]; }
+	
+	int deleted_item(int index) { return offsets[index]; }
+	item *update_item(int index) { return (item *)(data_start() + offsets[num_deleted_items+index]); }
+	item *temp_item(int index) { return (item *)(data_start() + offsets[num_deleted_items+num_update_items+index]); }
+	*/
+} SNAPSHOT_DELTA;
+
+
+static const int MAX_ITEMS = 512;
+static SNAPSHOT_DELTA empty = {0,0,0,{0}};
+
+void *snapshot_empty_delta()
+{
+	return &empty;
+}
+
+int snapshot_crc(SNAPSHOT *snap)
+{
+	int crc = 0;
+	int i, b;
+	SNAPSHOT_ITEM *item;
+	int size;
+	
+	for(i = 0; i < snap->num_items; i++)
+	{
+		item = snapshot_get_item(snap, i);
+		size = snapshot_get_item_datasize(snap, i);
+		
+		for(b = 0; b < size/4; b++)
+			crc += snapitem_data(item)[b];
+	}
+	return crc;
+}
+
+void snapshot_debug_dump(SNAPSHOT *snap)
+{
+	int size, i, b;
+	SNAPSHOT_ITEM *item;
+	
+	dbg_msg("snapshot", "data_size=%d num_items=%d", snap->data_size, snap->num_items);
+	for(i = 0; i < snap->num_items; i++)
+	{
+		item = snapshot_get_item(snap, i);
+		size = snapshot_get_item_datasize(snap, i);
+		dbg_msg("snapshot", "\ttype=%d id=%d", snapitem_type(item), snapitem_id(item));
+		for(b = 0; b < size/4; b++)
+			dbg_msg("snapshot", "\t\t%3d %12d\t%08x", b, snapitem_data(item)[b], snapitem_data(item)[b]);
+	}
+}
+
+static int diff_item(int *past, int *current, int *out, int size)
+{
+	/*
+	int needed = 0;
+	while(size)
+	{
+		*out = *current-*past;
+		if(*out)
+			needed = 1;
+		out++;
+		current++;
+		past++;
+		size--;
+	}*/
+
+	int needed = 0;
+	while(size)
+	{
+		*out = *current-*past;
+		if(*out)
+			needed = 1;
+		
+		out++;
+		past++;
+		current++;
+		size--;
+	}
+	
+	return needed;
+}
+
+static void undiff_item(int *past, int *diff, int *out, int size)
+{
+	while(size)
+	{
+		*out = *past+*diff;
+		out++;
+		past++;
+		diff++;
+		size--;
+	}
+}
+
+int snapshot_create_delta(SNAPSHOT *from, SNAPSHOT *to, void *dstdata)
+{
+	SNAPSHOT_DELTA *delta = (SNAPSHOT_DELTA *)dstdata;
+	int *data = (int *)delta->data;
+	int i, itemsize, pastindex;
+	SNAPSHOT_ITEM *fromitem;
+	SNAPSHOT_ITEM *curitem;
+	SNAPSHOT_ITEM *pastitem;
+	int count = 0;
+	int size_count = 0;
+	
+	delta->num_deleted_items = 0;
+	delta->num_update_items = 0;
+	delta->num_temp_items = 0;
+
+	/* pack deleted stuff */
+	for(i = 0; i < from->num_items; i++)
+	{
+		fromitem = snapshot_get_item(from, i);
+		if(snapshot_get_item_index(to, (snapitem_key(fromitem))) == -1)
+		{
+			/* deleted */
+			delta->num_deleted_items++;
+			*data = snapitem_key(fromitem);
+			data++;
+		}
+	}
+	
+	/* pack updated stuff */
+	for(i = 0; i < to->num_items; i++)
+	{
+		/* do delta */
+		itemsize = snapshot_get_item_datasize(to, i);
+		
+		curitem = snapshot_get_item(to, i);
+		pastindex = snapshot_get_item_index(from, snapitem_key(curitem));
+		if(pastindex != -1)
+		{
+			pastitem = snapshot_get_item(from, pastindex);
+			if(diff_item((int*)snapitem_data(pastitem), (int*)snapitem_data(curitem), data+3, itemsize/4))
+			{
+				*data++ = itemsize;
+				*data++ = snapitem_type(curitem);
+				*data++ = snapitem_id(curitem);
+				/*data++ = curitem->key();*/
+				data += itemsize/4;
+				delta->num_update_items++;
+			}
+		}
+		else
+		{
+			*data++ = itemsize;
+			*data++ = snapitem_type(curitem);
+			*data++ = snapitem_id(curitem);
+			/*data++ = curitem->key();*/
+			
+			mem_copy(data, snapitem_data(curitem), itemsize);
+			size_count += itemsize;
+			data += itemsize/4;
+			delta->num_update_items++;
+			count++;
+		}
+	}
+	
+	if(0)
+	{
+		dbg_msg("snapshot", "%d %d %d",
+			delta->num_deleted_items,
+			delta->num_update_items,
+			delta->num_temp_items);
+	}
+
+	/*
+	// TODO: pack temp stuff
+	
+	// finish
+	//mem_copy(delta->offsets, deleted, delta->num_deleted_items*sizeof(int));
+	//mem_copy(&(delta->offsets[delta->num_deleted_items]), update, delta->num_update_items*sizeof(int));
+	//mem_copy(&(delta->offsets[delta->num_deleted_items+delta->num_update_items]), temp, delta->num_temp_items*sizeof(int));
+	//mem_copy(delta->data_start(), data, data_size);
+	//delta->data_size = data_size;
+	* */
+	
+	if(!delta->num_deleted_items && !delta->num_update_items && !delta->num_temp_items)
+		return 0;
+	
+	return (int)((char*)data-(char*)dstdata);
+}
+
+int snapshot_unpack_delta(SNAPSHOT *from, SNAPSHOT *to, void *srcdata, int data_size)
+{
+	SNAPBUILD builder;
+	SNAPSHOT_DELTA *delta = (SNAPSHOT_DELTA *)srcdata;
+	int *data = (int *)delta->data;
+	SNAPSHOT_ITEM *fromitem;
+	int i, d, keep, itemsize;
+	int *deleted;
+	int id, type, key;
+	int fromindex;
+	int *newdata;
+			
+	snapbuild_init(&builder);
+	
+	/* unpack deleted stuff */
+	deleted = data;
+	data += delta->num_deleted_items;
+
+	/* copy all non deleted stuff */
+	for(i = 0; i < from->num_items; i++)
+	{
+		/* dbg_assert(0, "fail!"); */
+		fromitem = snapshot_get_item(from, i);
+		itemsize = snapshot_get_item_datasize(from, i);
+		keep = 1;
+		for(d = 0; d < delta->num_deleted_items; d++)
+		{
+			if(deleted[d] == snapitem_key(fromitem))
+			{
+				keep = 0;
+				break;
+			}
+		}
+		
+		if(keep)
+		{
+			/* keep it */
+			mem_copy(
+				snapbuild_new_item(&builder, snapitem_type(fromitem), snapitem_id(fromitem), itemsize),
+				snapitem_data(fromitem), itemsize);
+		}
+	}
+		
+	/* unpack updated stuff */
+	for(i = 0; i < delta->num_update_items; i++)
+	{
+		itemsize = *data++;
+		type = *data++;
+		id = *data++;
+		
+		key = (type<<16)|id;
+		
+		/* create the item if needed */
+		newdata = snapbuild_get_item_data(&builder, key);
+		if(!newdata)
+			newdata = (int *)snapbuild_new_item(&builder, key>>16, key&0xffff, itemsize);
+			
+		fromindex = snapshot_get_item_index(from, key);
+		if(fromindex != -1)
+		{
+			/* we got an update so we need to apply the diff */
+			undiff_item((int *)snapitem_data(snapshot_get_item(from, fromindex)), data, newdata, itemsize/4);
+		}
+		else /* no previous, just copy the data */
+			mem_copy(newdata, data, itemsize);
+			
+		data += itemsize/4;
+	}
+	
+	/* finish up */
+	return snapbuild_finish(&builder, to);
+}
+
+/* SNAPSTORAGE */
+
+void snapstorage_init(SNAPSTORAGE *ss)
+{
+	ss->first = 0;
+}
+
+void snapstorage_purge_all(SNAPSTORAGE *ss)
+{
+	SNAPSTORAGE_HOLDER *h = ss->first;
+	SNAPSTORAGE_HOLDER *next;
+
+	while(h)
+	{
+		next = h->next;
+		mem_free(h);
+		h = next;
+	}
+
+	/* no more snapshots in storage */
+	ss->first = 0;
+	ss->last = 0;
+}
+
+void snapstorage_purge_until(SNAPSTORAGE *ss, int tick)
+{
+	SNAPSTORAGE_HOLDER *next;
+	SNAPSTORAGE_HOLDER *h = ss->first;
+	
+	while(h)
+	{
+		next = h->next;
+		if(h->tick >=  tick)
+			return; /* no more to remove */
+		mem_free(h);
+		
+		ss->first = next;
+		next->prev = 0x0;
+		
+		h = next;
+	}
+	
+	/* no more snapshots in storage */
+	ss->first = 0;
+	ss->last = 0;
+}
+
+void snapstorage_add(SNAPSTORAGE *ss, int tick, int64 tagtime, int data_size, void *data)
+{
+	/* allocate memory for holder + snapshot_data */
+	SNAPSTORAGE_HOLDER *h = (SNAPSTORAGE_HOLDER *)mem_alloc(sizeof(SNAPSTORAGE_HOLDER)+data_size, 1);
+	
+	/* set data */
+	h->tick = tick;
+	h->tagtime = tagtime;
+	h->snap_size = data_size;
+	h->snap = (SNAPSHOT*)(h+1);
+	mem_copy(h->snap, data, data_size);
+	
+	/* link */
+	h->next = 0;
+	h->prev = ss->last;
+	if(ss->last)
+		ss->last->next = h;
+	else
+		ss->first = h;
+	ss->last = h;
+}
+
+int snapstorage_get(SNAPSTORAGE *ss, int tick, int64 *tagtime, SNAPSHOT **data)
+{
+	SNAPSTORAGE_HOLDER *h = ss->first;
+	
+	while(h)
+	{
+		if(h->tick == tick)
+		{
+			if(tagtime)
+				*tagtime = h->tagtime;
+			if(data)
+				*data = h->snap;
+			return h->snap_size;
+		}
+		
+		h = h->next;
+	}
+	
+	return -1;
+}
+
+/* SNAPBUILD */
+
+void snapbuild_init(SNAPBUILD *sb)
+{
+	sb->data_size = 0;
+	sb->num_items = 0;
+}
+
+SNAPSHOT_ITEM *snapbuild_get_item(SNAPBUILD *sb, int index) 
+{
+	return (SNAPSHOT_ITEM *)&(sb->data[sb->offsets[index]]);
+}
+
+int *snapbuild_get_item_data(SNAPBUILD *sb, int key)
+{
+	int i;
+	for(i = 0; i < sb->num_items; i++)
+	{
+		if(snapitem_key(snapbuild_get_item(sb, i)) == key)
+			return (int *)snapitem_data(snapbuild_get_item(sb, i));
+	}
+	return 0;
+}
+
+int snapbuild_finish(SNAPBUILD *sb, void *snapdata)
+{
+	/* flattern and make the snapshot */
+	SNAPSHOT *snap = (SNAPSHOT *)snapdata;
+	snap->data_size = sb->data_size;
+	snap->num_items = sb->num_items;
+	int offset_size = sizeof(int)*sb->num_items;
+	mem_copy(snapshot_offsets(snap), sb->offsets, offset_size);
+	mem_copy(snapshot_datastart(snap), sb->data, sb->data_size);
+	return sizeof(SNAPSHOT) + offset_size + sb->data_size;
+}
+
+void *snapbuild_new_item(SNAPBUILD *sb, int type, int id, int size)
+{
+	SNAPSHOT_ITEM *obj = (SNAPSHOT_ITEM *)(sb->data+sb->data_size);
+	mem_zero(obj, sizeof(SNAPSHOT_ITEM) + size);
+	obj->type_and_id = (type<<16)|id;
+	sb->offsets[sb->num_items] = sb->data_size;
+	sb->data_size += sizeof(SNAPSHOT_ITEM) + size;
+	sb->num_items++;
+	
+	dbg_assert(sb->data_size < MAX_SNAPSHOT_SIZE, "too much data");
+	dbg_assert(sb->num_items < SNAPBUILD_MAX_ITEMS, "too many items");
+
+	return snapitem_data(obj);
+}
diff --git a/src/engine/snapshot.cpp b/src/engine/snapshot.cpp
deleted file mode 100644
index e8b75d36..00000000
--- a/src/engine/snapshot.cpp
+++ /dev/null
@@ -1,263 +0,0 @@
-
-#include "packet.h"
-#include "snapshot.h"
-
-struct snapshot_delta
-{
-	int num_deleted_items;
-	int num_update_items;
-	int num_temp_items; // needed?
-	int data[1];
-	
-	/*
-	char *data_start() { return (char *)&offsets[num_deleted_items+num_update_items+num_temp_items]; }
-	
-	int deleted_item(int index) { return offsets[index]; }
-	item *update_item(int index) { return (item *)(data_start() + offsets[num_deleted_items+index]); }
-	item *temp_item(int index) { return (item *)(data_start() + offsets[num_deleted_items+num_update_items+index]); }
-	* */
-};
-
-
-static const int MAX_ITEMS = 512;
-static snapshot_delta empty = {0,0,0,{0}};
-
-void *snapshot_empty_delta()
-{
-	return &empty;
-}
-
-int snapshot_crc(snapshot *snap)
-{
-	int crc = 0;
-	
-	for(int i = 0; i < snap->num_items; i++)
-	{
-		snapshot::item *item = snap->get_item(i);
-		int size = snap->get_item_datasize(i);
-		
-		for(int b = 0; b < size/4; b++)
-			crc += item->data()[b];
-	}
-	return crc;
-}
-
-void snapshot_debug_dump(snapshot *snap)
-{
-	dbg_msg("snapshot", "data_size=%d num_items=%d", snap->data_size, snap->num_items);
-	for(int i = 0; i < snap->num_items; i++)
-	{
-		snapshot::item *item = snap->get_item(i);
-		int size = snap->get_item_datasize(i);
-		dbg_msg("snapshot", "\ttype=%d id=%d", item->type(), item->id());
-		for(int b = 0; b < size/4; b++)
-			dbg_msg("snapshot", "\t\t%3d %12d\t%08x", b, item->data()[b], item->data()[b]);
-	}
-}
-
-static int diff_item(int *past, int *current, int *out, int size)
-{
-	/*
-	int needed = 0;
-	while(size)
-	{
-		*out = *current-*past;
-		if(*out)
-			needed = 1;
-		out++;
-		current++;
-		past++;
-		size--;
-	}*/
-
-	int needed = 0;
-	while(size)
-	{
-		*out = *current-*past;
-		if(*out)
-			needed = 1;
-		
-		out++;
-		past++;
-		current++;
-		size--;
-	}
-	
-	return needed;
-}
-
-// 1 = 4-3
-// d = n-p
-
-// n(4) = p(3)+d(1)
-
-static void undiff_item(int *past, int *diff, int *out, int size)
-{
-	while(size)
-	{
-		*out = *past+*diff;
-		out++;
-		past++;
-		diff++;
-		size--;
-	}
-}
-
-int snapshot_create_delta(snapshot *from, snapshot *to, void *dstdata)
-{
-	//int deleted[MAX_ITEMS];
-	//int update[MAX_ITEMS];
-	//int mark[MAX_ITEMS];
-	//char data[MAX_SNAPSHOT_SIZE];
-	
-	snapshot_delta *delta = (snapshot_delta *)dstdata;
-	int *data = (int *)delta->data;
-	
-	
-	delta->num_deleted_items = 0;
-	delta->num_update_items = 0;
-	delta->num_temp_items = 0;
-
-	// pack deleted stuff
-	for(int i = 0; i < from->num_items; i++)
-	{
-		snapshot::item *fromitem = from->get_item(i);
-		if(to->get_item_index(fromitem->key()) == -1)
-		{
-			// deleted
-			delta->num_deleted_items++;
-			*data = fromitem->key();
-			data++;
-		}
-	}
-	
-	// pack updated stuff
-	int count = 0, size_count = 0;
-	for(int i = 0; i < to->num_items; i++)
-	{
-		// do delta
-		int itemsize = to->get_item_datasize(i);
-		
-		snapshot::item *curitem = to->get_item(i);
-		int pastindex = from->get_item_index(curitem->key());
-		if(pastindex != -1)
-		{
-			snapshot::item *pastitem = from->get_item(pastindex);
-			if(diff_item((int*)pastitem->data(), (int*)curitem->data(), data+3, itemsize/4))
-			{
-				*data++ = itemsize;
-				*data++ = curitem->type();
-				*data++ = curitem->id();
-				//*data++ = curitem->key();
-				data += itemsize/4;
-				delta->num_update_items++;
-			}
-		}
-		else
-		{
-			*data++ = itemsize;
-			*data++ = curitem->type();
-			*data++ = curitem->id();
-			//*data++ = curitem->key();
-			
-			mem_copy(data, curitem->data(), itemsize);
-			size_count += itemsize;
-			data += itemsize/4;
-			delta->num_update_items++;
-			count++;
-		}
-	}
-	
-	if(0)
-	{
-		dbg_msg("snapshot", "%d %d %d",
-			delta->num_deleted_items,
-			delta->num_update_items,
-			delta->num_temp_items);
-	}
-
-	// TODO: pack temp stuff
-	
-	// finish
-	//mem_copy(delta->offsets, deleted, delta->num_deleted_items*sizeof(int));
-	//mem_copy(&(delta->offsets[delta->num_deleted_items]), update, delta->num_update_items*sizeof(int));
-	//mem_copy(&(delta->offsets[delta->num_deleted_items+delta->num_update_items]), temp, delta->num_temp_items*sizeof(int));
-	//mem_copy(delta->data_start(), data, data_size);
-	//delta->data_size = data_size;
-	
-	if(!delta->num_deleted_items && !delta->num_update_items && !delta->num_temp_items)
-		return 0;
-	
-	return (int)((char*)data-(char*)dstdata);
-}
-
-int snapshot_unpack_delta(snapshot *from, snapshot *to, void *srcdata, int data_size)
-{
-	snapshot_builder builder;
-	snapshot_delta *delta = (snapshot_delta *)srcdata;
-	int *data = (int *)delta->data;
-	
-	builder.start();
-	
-	// unpack deleted stuff
-	int *deleted = data;
-	data += delta->num_deleted_items;
-
-	// copy all non deleted stuff
-	for(int i = 0; i < from->num_items; i++)
-	{
-		//dbg_assert(0, "fail!");
-		snapshot::item *fromitem = from->get_item(i);
-		int itemsize = from->get_item_datasize(i);
-		int keep = 1;
-		for(int d = 0; d < delta->num_deleted_items; d++)
-		{
-			if(deleted[d] == fromitem->key())
-			{
-				keep = 0;
-				break;
-			}
-		}
-		
-		if(keep)
-		{
-			// keep it
-			int *newdata = (int *)(snapshot::item *)builder.new_item(fromitem->type(), fromitem->id(), itemsize);
-			mem_copy(newdata, fromitem->data(), itemsize);
-		}
-	}
-		
-	// unpack updated stuff
-	for(int i = 0; i < delta->num_update_items; i++)
-	{
-		int itemsize, id, type, key;
-		itemsize = *data++;
-		//key = *data++;
-		type = *data++;
-		id = *data++;
-		
-		key = (type<<16)|id;
-		
-		// create the item if needed
-		int *newdata = builder.get_item_data(key);
-		if(!newdata)
-			newdata = (int *)builder.new_item(key>>16, key&0xffff, itemsize);
-			
-		int fromindex = from->get_item_index(key);
-		if(fromindex != -1)
-		{
-			// we got an update so we need to apply the diff
-			int *pastdata = (int *)from->get_item(fromindex)->data();
-			undiff_item(pastdata, data, newdata, itemsize/4);
-		}
-		else // no previous, just copy the data
-			mem_copy(newdata, data, itemsize);
-			
-		data += itemsize/4;
-	}
-	
-	// TODO: unpack temp stuff
-	
-	// finish up
-	return builder.finish(to);
-}
diff --git a/src/engine/snapshot.h b/src/engine/snapshot.h
index e3358b1a..819b65c2 100644
--- a/src/engine/snapshot.h
+++ b/src/engine/snapshot.h
@@ -1,49 +1,88 @@
-#ifndef FILE_SNAPSHOT_H
-#define FILE_SNAPSHOT_H
+#ifndef ENGINE_SNAPSHOT_H
+#define ENGINE_SNAPSHOT_H
 
-struct snapshot
+/* SNAPSHOT */
+
+enum
+{
+	MAX_SNAPSHOT_SIZE=64*1024,
+};
+
+typedef struct
+{
+	int type_and_id;
+} SNAPSHOT_ITEM;
+
+typedef struct 
 {
 	int data_size;
 	int num_items;
+} SNAPSHOT;
+
+int *snapitem_data(SNAPSHOT_ITEM *item);
+int snapitem_type(SNAPSHOT_ITEM *item);
+int snapitem_id(SNAPSHOT_ITEM *item);
+int snapitem_key(SNAPSHOT_ITEM *item);
+
+int *snapshot_offsets(SNAPSHOT *snap);
+char *snapshot_datastart(SNAPSHOT *snap);
+
+SNAPSHOT_ITEM *snapshot_get_item(SNAPSHOT *snap, int index);
+int snapshot_get_item_datasize(SNAPSHOT *snap, int index);
+int snapshot_get_item_index(SNAPSHOT *snap, int key);
+
+void *snapshot_empty_delta();
+int snapshot_crc(SNAPSHOT *snap);
+void snapshot_debug_dump(SNAPSHOT *snap);
+int snapshot_create_delta(SNAPSHOT *from, SNAPSHOT *to, void *data);
+int snapshot_unpack_delta(SNAPSHOT *from, SNAPSHOT *to, void *data, int data_size);
+
+/* SNAPSTORAGE */
+
+typedef struct SNAPSTORAGE_HOLDER_t
+{
+	struct SNAPSTORAGE_HOLDER_t *prev;
+	struct SNAPSTORAGE_HOLDER_t *next;
 	
-	struct item
-	{
-		int type_and_id;
-
-		int *data() { return (int *)(this+1); }		
-		int type() { return type_and_id>>16; }
-		int id() { return type_and_id&(0xffff); }
-		int key() { return type_and_id; }
-	};
-
-	int *offsets() { return (int *)(this+1); }		
-	char *data_start() { return (char *)(offsets() + num_items); }
-	item *get_item(int index) { return (item *)(data_start() + offsets()[index]); };
-	
-	// returns the number of ints in the item data
-	int get_item_datasize(int index)
-	{
-		if(index == num_items-1)
-			return (data_size - offsets()[index]) - sizeof(item);
-		return (offsets()[index+1] - offsets()[index]) - sizeof(item);
-	}
+	int64 tagtime;
+	int tick;
 	
-	int get_item_index(int key)
-	{
-		// TODO: this should not be a linear search. very bad
-		for(int i = 0; i < num_items; i++)
-		{
-			if(get_item(i)->key() == key)
-				return i;
-		}
-		return -1;
-	}
+	int snap_size;
+	SNAPSHOT *snap;
+} SNAPSTORAGE_HOLDER;
+ 
+typedef struct SNAPSTORAGE_t
+{
+	SNAPSTORAGE_HOLDER *first;
+	SNAPSTORAGE_HOLDER *last;
+} SNAPSTORAGE;
+
+void snapstorage_init(SNAPSTORAGE *ss);
+void snapstorage_purge_all(SNAPSTORAGE *ss);
+void snapstorage_purge_until(SNAPSTORAGE *ss, int tick);
+void snapstorage_add(SNAPSTORAGE *ss, int tick, int64 tagtime, int data_size, void *data);
+int snapstorage_get(SNAPSTORAGE *ss, int tick, int64 *tagtime, SNAPSHOT **data);
+
+/* SNAPBUILD */
+
+enum
+{
+	SNAPBUILD_MAX_ITEMS = 512,
 };
 
-void *snapshot_empty_delta();
-int snapshot_crc(snapshot *snap);
-void snapshot_debug_dump(snapshot *snap);
-int snapshot_create_delta(snapshot *from, snapshot *to, void *data);
-int snapshot_unpack_delta(snapshot *from, snapshot *to, void *data, int data_size);
+typedef struct SNAPBUILD
+{
+	char data[MAX_SNAPSHOT_SIZE];
+	int data_size;
+
+	int offsets[SNAPBUILD_MAX_ITEMS];
+	int num_items;
+} SNAPBUILD;
+
+void snapbuild_init(SNAPBUILD *sb);
+SNAPSHOT_ITEM *snapbuild_get_item(SNAPBUILD *sb, int index);
+int *snapbuild_get_item_data(SNAPBUILD *sb, int key);
+int snapbuild_finish(SNAPBUILD *sb, void *snapdata);
+void *snapbuild_new_item(SNAPBUILD *sb, int type, int id, int size);
 
-#endif // FILE_SNAPSHOT_H
+#endif /* ENGINE_SNAPSHOT_H */
diff --git a/src/engine/system.c b/src/engine/system.c
new file mode 100644
index 00000000..19fcba2e
--- /dev/null
+++ b/src/engine/system.c
@@ -0,0 +1,560 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <string.h>
+#include <time.h>
+
+#include "system.h"
+
+#if defined(CONF_FAMILY_UNIX)
+	#include <sys/time.h>
+	#include <unistd.h>
+
+	/* unix net includes */
+	#include <sys/types.h>
+	#include <sys/socket.h>
+	#include <sys/ioctl.h>
+	#include <errno.h>
+	#include <netdb.h>      
+	#include <netinet/in.h>
+	#include <fcntl.h>
+
+	#include <dirent.h>
+	#include <unistd.h>
+#elif defined(CONF_FAMILY_WINDOWS)
+	#define WIN32_LEAN_AND_MEAN 
+	#include <windows.h>
+	#include <winsock2.h>
+	#include <ws2tcpip.h>
+	#include <fcntl.h>
+
+	#define EWOULDBLOCK WSAEWOULDBLOCK
+#else
+	#error NOT IMPLEMENTED
+#endif
+
+IOHANDLE logfile = 0;
+
+void dbg_assert_imp(const char *filename, int line, int test, const char *msg)
+{
+	if(!test)
+	{
+		dbg_msg("assert", "%s(%d): %s", filename, line, msg);
+		dbg_break();
+	}
+}
+
+void dbg_break()
+{
+	*((unsigned*)0) = 0x0;
+}
+
+int dbg_log_to_file(const char *filename)
+{
+	logfile = io_open(filename, IOFLAG_WRITE);
+	if(logfile)
+		return 1;
+	return 0;
+}
+
+void dbg_msg(const char *sys, const char *fmt, ...)
+{
+	va_list args;
+#if defined(CONF_FAMILY_WINDOWS)
+	char str[1024];
+	va_start(args, fmt);
+	vsprintf(str, fmt, args);
+	va_end(args);
+	OutputDebugString(str);
+	OutputDebugString("\n");
+#endif
+
+	va_start(args, fmt);
+	printf("[%08x][%s]: ", (int)time(0), sys);
+	vprintf(fmt, args);
+	va_end(args);
+	printf("\n");
+}
+
+int memory_alloced = 0;
+
+struct memheader
+{
+	const char *filename;
+	int line;
+	int size;
+	struct memheader *prev;
+	struct memheader *next;
+};
+
+struct memtail
+{
+	int guard;
+};
+
+struct memheader *first = 0;
+
+void *mem_alloc_debug(const char *filename, int line, unsigned size, unsigned alignment)
+{
+	/* TODO: fix alignment */
+	/* TODO: add debugging */
+	struct memheader *header = (struct memheader *)malloc(size+sizeof(struct memheader)+sizeof(struct memtail));
+	struct memtail *tail = (struct memtail *)(((char*)(header+1))+size);
+	header->size = size;
+	header->filename = filename;
+	header->line = line;
+	memory_alloced += header->size;
+	
+	tail->guard = 0xbaadc0de;
+
+	header->prev = (struct memheader *)0;
+	header->next = first;
+	if(first)
+		first->prev = header;
+	first = header;
+	
+	/*dbg_msg("mem", "++ %p", header+1); */
+	return header+1;
+}
+
+void mem_free(void *p)
+{
+	if(p)
+	{
+		struct memheader *header = (struct memheader *)p - 1;
+		struct memtail *tail = (struct memtail *)(((char*)(header+1))+header->size);
+		
+		if(tail->guard != 0xbaadc0de)
+			dbg_msg("mem", "!! %p", p);
+		/* dbg_msg("mem", "-- %p", p); */
+		memory_alloced -= header->size;
+		
+		if(header->prev)
+			header->prev->next = header->next;
+		else
+			first = header->next;
+		if(header->next)
+			header->next->prev = header->prev;
+		
+		free(header);
+	}
+}
+
+void mem_debug_dump()
+{
+	char buf[1024];
+	struct memheader *header = first;
+	IOHANDLE f = io_open("memory.txt", IOFLAG_WRITE);
+	
+	while(header)
+	{
+		sprintf(buf, "%s(%d): %d\n", header->filename, header->line, header->size);
+		io_write(f, buf, strlen(buf));
+		header = header->next;
+	}
+}
+
+
+void mem_copy(void *dest, const void *source, unsigned size)
+{
+	memcpy(dest, source, size);
+}
+
+void mem_move(void *dest, const void *source, unsigned size)
+{
+	memmove(dest, source, size);
+}
+
+void mem_zero(void *block,unsigned size)
+{
+	memset(block, 0, size);
+}
+
+IOHANDLE io_open(const char *filename, int flags)
+{
+	if(flags == IOFLAG_READ)
+		return (IOHANDLE)fopen(filename, "rb");
+	if(flags == IOFLAG_WRITE)
+		return (IOHANDLE)fopen(filename, "wb");
+	return 0x0;
+}
+
+unsigned io_read(IOHANDLE io, void *buffer, unsigned size)
+{
+	return fread(buffer, 1, size, (FILE*)io);
+}
+
+unsigned io_skip(IOHANDLE io, unsigned size)
+{
+	fseek((FILE*)io, size, SEEK_CUR);
+	return size;
+}
+
+int io_seek(IOHANDLE io, int offset, int origin)
+{
+	int real_origin;
+
+	switch(origin)
+	{
+	case 0: /*IOSEEK_SET:*/
+		real_origin = SEEK_SET;
+		break;
+	case 1: /*IOSEEK_CUR:*/
+		real_origin = SEEK_CUR;
+		break;
+	case 2: /*IOSEEK_END:*/
+		real_origin = SEEK_END;
+	}
+
+	return fseek((FILE*)io, offset, origin);
+}
+
+long int io_tell(IOHANDLE io)
+{
+	return ftell((FILE*)io);
+}
+
+long int io_length(IOHANDLE io)
+{
+	long int length;
+	io_seek(io, 0, IOSEEK_END);
+	length = io_tell(io);
+	io_seek(io, 0, IOSEEK_SET);
+	return length;
+}
+
+unsigned io_write(IOHANDLE io, const void *buffer, unsigned size)
+{
+	return fwrite(buffer, 1, size, (FILE*)io);
+}
+
+int io_close(IOHANDLE io)
+{
+	fclose((FILE*)io);
+	return 1;
+}
+
+void thread_sleep(int milliseconds)
+{
+#if defined(CONF_FAMILY_UNIX)
+	usleep(milliseconds*1000);
+#elif defined(CONF_FAMILY_WINDOWS)
+	Sleep(milliseconds);
+#else
+	#error not implemented
+#endif
+}
+
+/* -----  time ----- */
+int64 time_get()
+{
+#if defined(CONF_FAMILY_UNIX)
+	struct timeval val;
+	gettimeofday(&val, NULL);
+	return (int64)val.tv_sec*(int64)1000000+(int64)val.tv_usec;
+#elif defined(CONF_FAMILY_WINDOWS)
+	int64 t;
+	QueryPerformanceCounter((PLARGE_INTEGER)&t);
+	return t;
+#else
+	#error not implemented
+#endif
+}
+
+int64 time_freq()
+{
+#if defined(CONF_FAMILY_UNIX)
+	return 1000000;
+#elif defined(CONF_FAMILY_WINDOWS)
+	int64 t;
+	QueryPerformanceFrequency((PLARGE_INTEGER)&t);
+	return t;
+#else
+	#error not implemented
+#endif
+}
+
+/* -----  network ----- */
+static void netaddr4_to_sockaddr(const NETADDR4 *src, struct sockaddr *dest)
+{
+	struct sockaddr_in *p = (struct sockaddr_in *)dest;
+	mem_zero(p, sizeof(struct sockaddr_in));
+	p->sin_family = AF_INET;
+	p->sin_port = htons(src->port);
+	p->sin_addr.s_addr = htonl(src->ip[0]<<24|src->ip[1]<<16|src->ip[2]<<8|src->ip[3]);
+}
+
+static void sockaddr_to_netaddr4(const struct sockaddr *src, NETADDR4 *dst)
+{
+	unsigned int ip = htonl(((struct sockaddr_in*)src)->sin_addr.s_addr);
+	dst->port = htons(((struct sockaddr_in*)src)->sin_port);
+	dst->ip[0] = (unsigned char)((ip>>24)&0xFF);
+	dst->ip[1] = (unsigned char)((ip>>16)&0xFF);
+	dst->ip[2] = (unsigned char)((ip>>8)&0xFF);
+	dst->ip[3] = (unsigned char)(ip&0xFF);
+}
+
+int net_addr4_cmp(const NETADDR4 *a, const NETADDR4 *b)
+{
+	if(	a->ip[0] != b->ip[0] ||
+		a->ip[1] != b->ip[1] ||
+		a->ip[2] != b->ip[2] ||
+		a->ip[3] != b->ip[3] ||
+		a->port != b->port
+	)
+		return 1;
+	return 0;
+}
+
+
+int net_host_lookup(const char *hostname, unsigned short port, NETADDR4 *addr)
+{
+	struct hostent* ip = gethostbyname(hostname);
+
+	if(ip && ip->h_length > 0)
+	{
+		addr->ip[0] = ip->h_addr_list[0][0];
+		addr->ip[1] = ip->h_addr_list[0][1];
+		addr->ip[2] = ip->h_addr_list[0][2];
+		addr->ip[3] = ip->h_addr_list[0][3];
+		addr->port = port;
+		return 0;
+	}
+
+	return -1;
+}
+
+NETSOCKET net_udp4_create(NETADDR4 bindaddr)
+{
+	struct sockaddr addr;
+	unsigned int mode = 1;
+	int broadcast = 1;
+
+	/* create socket */
+	int sock = socket(AF_INET, SOCK_DGRAM, 0);
+	if(sock < 0)
+		return NETSOCKET_INVALID;
+	
+	/* bind, we should check for error */
+	netaddr4_to_sockaddr(&bindaddr, &addr);
+	if(bind(sock, &addr, sizeof(addr)) != 0)
+	{
+		net_udp4_close(sock);
+		return NETSOCKET_INVALID;
+	}
+	
+	/* set non-blocking */
+#if defined(CONF_FAMILY_WINDOWS)
+	ioctlsocket(sock, FIONBIO, (unsigned long *)&mode);
+#else
+	ioctl(sock, FIONBIO, (unsigned long *)&mode);
+#endif
+
+	/* set boardcast */
+	setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast));
+	
+	/* return */
+	return sock;
+}
+
+int net_udp4_send(NETSOCKET sock, const NETADDR4 *addr, const void *data, int size)
+{
+	struct sockaddr sa;
+	int d;
+	mem_zero(&sa, sizeof(sa));
+	netaddr4_to_sockaddr(addr, &sa);
+	d = sendto((int)sock, data, size, 0, &sa, sizeof(sa));
+	return d;
+}
+
+int net_udp4_recv(NETSOCKET sock, NETADDR4 *addr, void *data, int maxsize)
+{
+	struct sockaddr from;
+	int bytes;
+	socklen_t fromlen = sizeof(struct sockaddr);
+	bytes = recvfrom(sock, data, maxsize, 0, &from, &fromlen);
+	if(bytes > 0)
+	{
+		sockaddr_to_netaddr4(&from, addr);
+		return bytes;
+	}
+	else if(bytes == 0)
+		return 0;
+	return -1; /* error */
+}
+
+int net_udp4_close(NETSOCKET sock)
+{
+#if defined(CONF_FAMILY_WINDOWS)
+	closesocket(sock);
+#else
+	close((int)sock);
+#endif
+	return 0;
+}
+
+NETSOCKET net_tcp4_create(const NETADDR4 *a)
+{
+    struct sockaddr addr;
+
+    /* create socket */
+    int sock = socket(AF_INET, SOCK_STREAM, 0);
+    if(sock < 0)
+        return NETSOCKET_INVALID;
+
+    /* bind, we should check for error */
+    netaddr4_to_sockaddr(a, &addr);
+    bind(sock, &addr, sizeof(addr));
+
+    /* return */
+    return sock;
+}
+
+int net_tcp4_set_non_blocking(NETSOCKET sock)
+{
+	unsigned int mode = 1;
+#if defined(CONF_FAMILY_WINDOWS)
+	return ioctlsocket(sock, FIONBIO, (unsigned long *)&mode);
+#else
+	return ioctl(sock, FIONBIO, (unsigned long *)&mode);
+#endif
+}
+
+int net_tcp4_set_blocking(NETSOCKET sock)
+{
+	unsigned int mode = 0;
+#if defined(CONF_FAMILY_WINDOWS)
+	return ioctlsocket(sock, FIONBIO, (unsigned long *)&mode);
+#else
+	return ioctl(sock, FIONBIO, (unsigned long *)&mode);
+#endif
+}
+
+int net_tcp4_listen(NETSOCKET sock, int backlog)
+{
+	return listen(sock, backlog);
+}
+
+int net_tcp4_accept(NETSOCKET sock, NETSOCKET *new_sock, NETADDR4 *a)
+{
+	int s;
+	socklen_t sockaddr_len;
+	struct sockaddr addr;
+
+	sockaddr_len = sizeof(addr);
+
+	s = accept(sock, &addr, &sockaddr_len);
+
+	if (s != -1)
+	{
+		sockaddr_to_netaddr4(&addr, a);
+		*new_sock = s;
+	}
+	return s;
+}
+
+int net_tcp4_connect(NETSOCKET sock, const NETADDR4 *a)
+{
+  struct sockaddr addr;
+
+  netaddr4_to_sockaddr(a, &addr);
+  return connect(sock, &addr, sizeof(addr)); 
+}
+
+int net_tcp4_connect_non_blocking(NETSOCKET sock, const NETADDR4 *a)
+{
+	struct sockaddr addr;
+	int res;
+
+	netaddr4_to_sockaddr(a, &addr);
+	net_tcp4_set_non_blocking(sock);
+  	res = connect(sock, &addr, sizeof(addr));
+	net_tcp4_set_blocking(sock);
+
+	return res;
+}
+
+int net_tcp4_send(NETSOCKET sock, const void *data, int size)
+{
+  int d;
+  d = send((int)sock, data, size, 0);
+  return d;
+}
+
+int net_tcp4_recv(NETSOCKET sock, void *data, int maxsize)
+{
+  int bytes;
+  bytes = recv((int)sock, data, maxsize, 0);
+  return bytes;
+}
+
+int net_tcp4_close(NETSOCKET sock)
+{
+#if defined(CONF_FAMILY_WINDOWS)
+	closesocket(sock);
+#else
+	close((int)sock);
+#endif
+	return 0;
+}
+
+int net_errno()
+{
+	return errno;
+}
+
+int net_would_block()
+{
+	return net_errno() == EWOULDBLOCK;
+}
+
+int net_init()
+{
+#if defined(CONF_FAMILY_WINDOWS)
+	WSADATA wsaData;
+	int err = WSAStartup(MAKEWORD(1, 1), &wsaData);
+	dbg_assert(err == 0, "network initialization failed.");
+	return err==0?0:1;
+#endif
+
+	return 0;
+}
+
+int fs_listdir(const char *dir, fs_listdir_callback cb, void *user)
+{
+#if defined(CONF_FAMILY_WINDOWS)
+	WIN32_FIND_DATA finddata;
+	HANDLE handle;
+	char buffer[1024*2];
+	strcpy(buffer, dir);
+	strcat(buffer, "/*");
+
+	handle = FindFirstFileA(buffer, &finddata);
+
+	if (handle == INVALID_HANDLE_VALUE)
+		return 0;
+
+	/* add all the entries */
+	do
+	{
+		if(finddata.cFileName[0] != '.')
+			cb(finddata.cFileName, 0, user);
+	} while (FindNextFileA(handle, &finddata));
+
+	FindClose(handle);
+	return 0;
+#else
+	struct dirent *entry;
+	DIR *d = opendir(dir);
+
+	if(!d)
+		return 0;
+		
+	while((entry = readdir(d)) != NULL)
+		cb(entry->d_name, 0, user);
+
+	/* close the directory and return */
+	closedir(d);
+	return 0;
+#endif
+}
diff --git a/src/engine/system.h b/src/engine/system.h
new file mode 100644
index 00000000..e311d571
--- /dev/null
+++ b/src/engine/system.h
@@ -0,0 +1,522 @@
+#ifndef BASE_SYSTEM_H
+#define BASE_SYSTEM_H
+
+#include "detect.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Group: Debug */
+
+/**********
+	Function: dbg_assert
+	
+	Breaks into the debugger based on a test.
+	
+	Parameters:
+		test - Result of the test.
+		msg - Message that should be printed if the test fails.
+	
+	Remarks:
+		Does nothing in release version of the library.
+	
+	See Also:
+		<dbg_break>
+**********/
+void dbg_assert(int test, const char *msg);
+#define dbg_assert(test,msg) dbg_assert_imp(__FILE__, __LINE__, test,  msg)
+void dbg_assert_imp(const char *filename, int line, int test, const char *msg);
+
+/**********
+	Function: dbg_break
+	
+	Breaks into the debugger.
+	
+	Remarks:
+		Does nothing in release version of the library.
+	
+	See Also:
+		<dbg_assert>
+**********/
+void dbg_break();
+
+/**********
+	Function: dbg_msg
+	
+	Prints a debug message.
+	
+	Parameters:
+		sys - A string that describes what system the message belongs to
+		fmt - A printf styled format string.
+	
+	Remarks:
+		Does nothing in relase version of the library.
+		
+	See Also:
+		<dbg_assert>
+**********/
+void dbg_msg(const char *sys, const char *fmt, ...);
+
+/* Group: Memory */
+
+/**********
+	Function: mem_alloc
+	
+	Allocates memory.
+	
+	Parameters:
+		size - Size of the needed block.
+		alignment - Alignment for the block.
+	
+	Returns:
+		Returns a pointer to the newly allocated block. Returns a
+		null pointer if the memory couldn't be allocated.
+		
+	Remarks:
+		- Passing 0 to size will allocated the smallest amount possible
+		and return a unique pointer.
+
+	See Also:
+		<mem_free>
+**********/
+void *mem_alloc_debug(const char *filename, int line, unsigned size, unsigned alignment);
+#define mem_alloc(s,a) mem_alloc_debug(__FILE__, __LINE__, (s), (a))
+
+/**********
+	Function: mem_free
+	
+	Frees a block allocated through <mem_alloc>.
+	
+	Remarks:
+		- In the debug version of the library the function will assert if
+		a non-valid block is passed, like a null pointer or a block that
+		isn't allocated.
+	
+	See Also:
+		<mem_alloc>
+**********/
+void mem_free(void *block);
+
+/**********
+	Function: mem_copy
+		Copies a a memory block.
+	
+	Parameters:
+		dest - Destination.
+		source - Source to copy.
+		size - Size of the block to copy.
+	
+	Remarks:
+		- This functions DOES NOT handles cases where source and
+		destination is overlapping.
+	
+	See Also:
+		<mem_move>
+**********/
+void mem_copy(void *dest, const void *source, unsigned size);
+
+/**********
+	Function: mem_move
+		Copies a a memory block.
+	
+	Parameters:
+		dest - Destination.
+		source - Source to copy.
+		size - Size of the block to copy.
+	
+	Remarks:
+		- This functions handles cases where source and destination is overlapping.
+	
+	See Also:
+		<mem_copy>
+**********/
+void mem_move(void *dest, const void *source, unsigned size);
+
+/**********
+	Function: mem_zero
+		Sets a complete memory block to 0.
+	
+	Parameters:
+		block - Pointer to the block to zero out.
+		size - Size of the block.
+**********/
+void mem_zero(void *block, unsigned size);
+
+/* ------- io ------- */
+enum {
+	IOFLAG_READ = 1,
+	IOFLAG_WRITE = 2,
+	IOFLAG_RANDOM = 4,
+
+	IOSEEK_SET = 0,
+	IOSEEK_CUR = 1,
+	IOSEEK_END = 2
+};
+
+typedef struct IOINTERNAL *IOHANDLE;
+
+/**** Group: File IO ****/
+
+/****
+	Function: io_open
+	
+	Opens a file.
+
+	Parameters:
+		filename - File to open.
+		flags - A set of flags. IOFLAG_READ, IOFLAG_WRITE, IOFLAG_RANDOM.
+
+	Returns:
+		Returns a handle to the file on success and 0 on failure.
+
+****/
+IOHANDLE io_open(const char *filename, int flags);
+
+/****
+	Function: io_read
+	
+	Reads data into a buffer from a file.
+
+	Parameters:
+		io - Handle to the file to read data from.
+		buffer - Pointer to the buffer that will recive the data.
+		size - Number of bytes to read from the file.
+		
+	Returns:
+		Number of bytes read.
+
+****/
+unsigned io_read(IOHANDLE io, void *buffer, unsigned size);
+
+/*****
+	Function: io_skip
+	
+	Skips data in a file.
+	
+	Parameters:
+		io - Handle to the file.
+		size - Number of bytes to skip.
+		
+	Returns:
+		Number of bytes skipped.
+****/
+unsigned io_skip(IOHANDLE io, unsigned size);
+
+/*****
+	Function: io_write
+	
+	Writes data from a buffer to file.
+	
+	Parameters:
+		io - Handle to the file.
+		buffer - Pointer to the data that should be written.
+		size - Number of bytes to write.
+		
+	Returns:
+		Number of bytes written.
+*****/
+unsigned io_write(IOHANDLE io, const void *buffer, unsigned size);
+
+/*****
+	Function: io_seek
+	
+	Seeks to a specified offset in the file.
+	
+	Parameters:
+		io - Handle to the file.
+		offset - Offset from pos to stop.
+		origin - Position to start searching from.
+		
+	Returns:
+		Returns 0 on success.
+*****/
+int io_seek(IOHANDLE io, int offset, int origin);
+
+/*****
+	Function: io_tell
+	
+	Gets the current position in the file.
+	
+	Parameters:
+		io - Handle to the file.
+		
+	Returns:
+		Returns the current position. -1L if an error occured.
+*****/
+long int io_tell(IOHANDLE io);
+
+/*****
+	Function: io_length
+	
+	Gets the total length of the file. Resetting cursor to the beginning
+	
+	Parameters:
+		io - Handle to the file.
+		
+	Returns:
+		Returns the total size. -1L if an error occured.
+*****/
+long int io_length(IOHANDLE io);
+
+/*****
+	Function: io_close
+	
+	Closes a file.
+	
+	Parameters:
+		io - Handle to the file.
+		
+	Returns:
+		Returns 0 on success.
+*****/
+int io_close(IOHANDLE io);
+
+/**** Group: Threads ****/
+
+int thread_create(); /* NOT IMPLEMENTED */
+int thread_destory(); /* NOT IMPLEMENTED */
+
+int thread_run(); /* NOT IMPLEMENTED */
+int thread_pause(); /* NOT IMPLEMENTED */
+int thread_wait(); /* NOT IMPLEMENTED */
+
+/*****
+	Function: thread_sleep
+	
+	Suspends the current thread for a given period.
+	
+	Parameters:
+		milliseconds - Number of milliseconds to sleep.
+*****/
+void thread_sleep(int milliseconds);
+
+/**** Group: Locks ****/
+typedef struct LOCKINTERNAL *LOCK;
+
+LOCK lock_create();
+void lock_destroy(LOCK lock);
+
+void lock_shared(LOCK lock);
+void lock_exclusive(LOCK lock);
+int lock_try_shared(LOCK lock);
+int lock_try_exclusive(LOCK lock);
+void lock_release(LOCK lock);
+
+/**** Group: Timer ****/
+typedef long long int64;
+
+/*****
+	Function: time_get
+	
+	Fetches a sample from a high resolution timer.
+	
+	Returns:
+		Current value of the timer.
+
+	Remarks:
+		To know how fast the timer is ticking, see <time_freq>.
+*****/
+int64 time_get();
+
+/*****
+	Function: time_freq
+	
+	Returns the frequency of the high resolution timer.
+	
+	Returns:
+		Returns the frequency of the high resolution timer.
+*****/
+int64 time_freq();
+
+/**** Group: Network General ipv4 ****/
+typedef int NETSOCKET;
+enum
+{
+	NETSOCKET_INVALID = -1,
+};
+
+typedef struct 
+{
+	unsigned char ip[4];
+	unsigned short port;
+} NETADDR4;
+
+/*****
+	Function: net_host_lookup
+	
+	Does a hostname lookup by name and fills out the passed NETADDE4 struct with the recieved details.
+
+	Returns:
+		0 on success.
+*****/
+int net_host_lookup(const char *hostname, unsigned short port, NETADDR4 *addr);
+
+/**** Group: Network UDP4 ****/
+
+/*****
+	Function: net_udp4_create
+	
+	Creates a UDP4 socket and binds it to a port.
+
+	Parameters:
+		port - Port to bind the socket to.
+	
+	Returns:
+		On success it returns an handle to the socket. On failure it returns NETSOCKET_INVALID.
+*****/
+NETSOCKET net_udp4_create(NETADDR4 bindaddr);
+
+/*****
+	Function: net_udp4_send
+	
+	Sends a packet over an UDP4 socket.
+
+	Parameters:
+		sock - Socket to use.
+		addr - Where to send the packet.
+		data - Pointer to the packet data to send.
+		size - Size of the packet.
+	
+	Returns:
+		On success it returns the number of bytes sent. Returns -1 on error.
+*****/
+int net_udp4_send(NETSOCKET sock, const NETADDR4 *addr, const void *data, int size);
+
+/*****
+	Function: net_udp4_recv
+	
+	Recives a packet over an UDP4 socket.
+
+	Parameters:
+		sock - Socket to use.
+		addr - Pointer to an NETADDR4 that will recive the address.
+		data - Pointer to a buffer that will recive the data.
+		maxsize - Maximum size to recive.
+	
+	Returns:
+		On success it returns the number of bytes recived. Returns -1 on error.
+*****/
+int net_udp4_recv(NETSOCKET sock, NETADDR4 *addr, void *data, int maxsize);
+
+/*****
+	Function: net_udp4_close
+	
+	Closes an UDP4 socket.
+
+	Parameters:
+		sock - Socket to close.
+	
+	Returns:
+		Returns 0 on success. -1 on error.
+*****/
+int net_udp4_close(NETSOCKET sock);
+
+
+/**** Group: Network TCP4 ****/
+
+/*****
+	Function: net_tcp4_create
+	
+	DOCTODO: serp
+*****/
+NETSOCKET net_tcp4_create(const NETADDR4 *a);
+
+/*****
+	Function: net_tcp4_set_non_blocking
+
+	DOCTODO: serp
+*****/
+int net_tcp4_set_non_blocking(NETSOCKET sock);
+
+/*****
+	Function: net_tcp4_set_non_blocking
+
+	DOCTODO: serp
+*****/
+int net_tcp4_set_blocking(NETSOCKET sock);
+
+/*****
+	Function: net_tcp4_listen
+
+	DOCTODO: serp 
+*****/
+int net_tcp4_listen(NETSOCKET sock, int backlog);
+
+/*****
+	Function: net_tcp4_accept
+	
+	DOCTODO: serp
+*****/
+int net_tcp4_accept(NETSOCKET sock, NETSOCKET *new_sock, NETADDR4 *a);
+
+/*****
+	Function: net_tcp4_connect
+	
+	DOCTODO: serp
+*****/
+int net_tcp4_connect(NETSOCKET sock, const NETADDR4 *a);
+
+/*****
+	Function: net_tcp4_connect_non_blocking
+	
+	DOCTODO: serp
+*****/
+int net_tcp4_connect_non_blocking(NETSOCKET sock, const NETADDR4 *a);
+
+/*****
+	Function: net_tcp4_send
+	
+	DOCTODO: serp
+*****/
+int net_tcp4_send(NETSOCKET sock, const void *data, int size);
+
+/*****
+	Function: net_tcp4_recv
+	
+	DOCTODO: serp
+*****/
+int net_tcp4_recv(NETSOCKET sock, void *data, int maxsize);
+
+/*****
+	Function: net_tcp4_close
+	
+	DOCTODO: serp
+*****/
+int net_tcp4_close(NETSOCKET sock);
+
+/*****
+	Function: net_errno
+
+	DOCTODO: serp
+*****/
+int net_errno();
+
+/*****
+	Function: net_would_block
+
+	DOCTODO: serp
+*****/
+int net_would_block();
+
+/*****
+	Function: net_init
+
+	DOCTODO: serp
+*****/
+int net_init();
+
+
+
+/* NOT DOCUMENTED */
+typedef void (*fs_listdir_callback)(const char *name, int is_dir, void *user);
+int fs_listdir(const char *dir, fs_listdir_callback cb, void *user);
+int net_addr4_cmp(const NETADDR4 *a, const NETADDR4 *b);
+
+void mem_debug_dump();
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif