diff -rupN teeworlds-b177-r50edfd37-source/src//base/detect.h alien-rc4/src//base/detect.h
--- teeworlds-b177-r50edfd37-source/src//base/detect.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//base/detect.h	2012-06-14 23:57:39.000000000 +0200
@@ -63,7 +63,7 @@
 #if defined(__sun)
 	#define CONF_FAMILY_UNIX 1
 	#define CONF_FAMILY_STRING "unix"
-	#define CONF_PLATFROM_SOLARIS 1
+	#define CONF_PLATFORM_SOLARIS 1
 	#define CONF_PLATFORM_STRING "solaris"
 #endif
 
@@ -77,7 +77,7 @@
 
 
 /* use gcc endianness definitions when available */
-#if defined(__GNUC__) && !defined(__APPLE__)
+#if defined(__GNUC__) && !defined(__APPLE__) && !defined(__MINGW32__) && !defined(__sun)
 	#if defined(__FreeBSD__) || defined(__OpenBSD__)
 		#include <sys/endian.h>
 	#else
@@ -101,7 +101,7 @@
 	#endif
 #endif
 
-#if defined(__ia64__)
+#if defined(__ia64__) || defined(_M_IA64)
 	#define CONF_ARCH_IA64 1
 	#define CONF_ARCH_STRING "ia64"
 	#if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG)
@@ -109,7 +109,7 @@
 	#endif
 #endif
 
-#if defined(__amd64__) || defined(__x86_64__)
+#if defined(__amd64__) || defined(__x86_64__) || defined(_M_X64)
 	#define CONF_ARCH_AMD64 1
 	#define CONF_ARCH_STRING "amd64"
 	#if !defined(CONF_ARCH_ENDIAN_LITTLE) && !defined(CONF_ARCH_ENDIAN_BIG)
diff -rupN teeworlds-b177-r50edfd37-source/src//base/system.c alien-rc4/src//base/system.c
--- teeworlds-b177-r50edfd37-source/src//base/system.c	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//base/system.c	2012-06-14 23:57:39.000000000 +0200
@@ -7,9 +7,7 @@
 #include <ctype.h>
 #include <time.h>
 
-/*#include "detect.h"*/
 #include "system.h"
-/*#include "e_console.h"*/
 
 #if defined(CONF_FAMILY_UNIX)
 	#include <sys/time.h>
@@ -46,6 +44,10 @@
 	#error NOT IMPLEMENTED
 #endif
 
+#if defined(CONF_PLATFORM_SOLARIS)
+	#include <sys/filio.h>
+#endif
+
 #if defined(__cplusplus)
 extern "C" {
 #endif
@@ -123,7 +125,7 @@ static IOHANDLE logfile = 0;
 static void logger_file(const char *line)
 {
 	io_write(logfile, line, strlen(line));
-	io_write(logfile, "\n", 1);
+	io_write_newline(logfile);
 	io_flush(logfile);
 }
 
@@ -140,8 +142,6 @@ void dbg_logger_file(const char *filenam
 }
 /* */
 
-int memory_alloced = 0;
-
 typedef struct MEMHEADER
 {
 	const char *filename;
@@ -163,8 +163,10 @@ void *mem_alloc_debug(const char *filena
 {
 	/* TODO: fix alignment */
 	/* TODO: add debugging */
+	MEMTAIL *tail;
 	MEMHEADER *header = (struct MEMHEADER *)malloc(size+sizeof(MEMHEADER)+sizeof(MEMTAIL));
-	MEMTAIL *tail = (struct MEMTAIL *)(((char*)(header+1))+size);
+	dbg_assert(header != 0, "mem_alloc failure");
+	tail = (struct MEMTAIL *)(((char*)(header+1))+size);
 	header->size = size;
 	header->filename = filename;
 	header->line = line;
@@ -220,8 +222,9 @@ void mem_debug_dump(IOHANDLE file)
 	{
 		while(header)
 		{
-			str_format(buf, sizeof(buf), "%s(%d): %d\n", header->filename, header->line, header->size);
+			str_format(buf, sizeof(buf), "%s(%d): %d", header->filename, header->line, header->size);
 			io_write(file, buf, strlen(buf));
+			io_write_newline(file);
 			header = header->next;
 		}
 
@@ -276,8 +279,13 @@ IOHANDLE io_open(const char *filename, i
 		if(!filename || !length || filename[length-1] == '\\')
 			return 0x0;
 		handle = FindFirstFile(filename, &finddata);
-		if(handle == INVALID_HANDLE_VALUE || str_comp(filename+length-str_length(finddata.cFileName), finddata.cFileName))
+		if(handle == INVALID_HANDLE_VALUE)
+			return 0x0;
+		else if(str_comp(filename+length-str_length(finddata.cFileName), finddata.cFileName) != 0)
+		{
+			FindClose(handle);
 			return 0x0;
+		}
 		FindClose(handle);
 	#endif
 		return (IOHANDLE)fopen(filename, "rb");
@@ -339,6 +347,15 @@ unsigned io_write(IOHANDLE io, const voi
 	return fwrite(buffer, 1, size, (FILE*)io);
 }
 
+unsigned io_write_newline(IOHANDLE io)
+{
+#if defined(CONF_FAMILY_WINDOWS)
+	return fwrite("\r\n", 1, 2, (FILE*)io);
+#else
+	return fwrite("\n", 1, 1, (FILE*)io);
+#endif
+}
+
 int io_close(IOHANDLE io)
 {
 	fclose((FILE*)io);
@@ -488,6 +505,21 @@ void lock_release(LOCK lock)
 #endif
 }
 
+#if defined(CONF_FAMILY_UNIX)
+void semaphore_init(SEMAPHORE *sem) { sem_init(sem, 0, 0); }
+void semaphore_wait(SEMAPHORE *sem) { sem_wait(sem); }
+void semaphore_signal(SEMAPHORE *sem) { sem_post(sem); }
+void semaphore_destroy(SEMAPHORE *sem) { sem_destroy(sem); }
+#elif defined(CONF_FAMILY_WINDOWS)
+void semaphore_init(SEMAPHORE *sem) { *sem = CreateSemaphore(0, 0, 10000, 0); }
+void semaphore_wait(SEMAPHORE *sem) { WaitForSingleObject((HANDLE)*sem, 0L); }
+void semaphore_signal(SEMAPHORE *sem) { ReleaseSemaphore((HANDLE)*sem, 1, NULL); }
+void semaphore_destroy(SEMAPHORE *sem) { CloseHandle((HANDLE)*sem); }
+#else
+	#error not implemented on this platform
+#endif
+
+
 /* -----  time ----- */
 int64 time_get()
 {
@@ -578,18 +610,18 @@ int net_addr_comp(const NETADDR *a, cons
 	return mem_comp(a, b, sizeof(NETADDR));
 }
 
-void net_addr_str(const NETADDR *addr, char *string, int max_length)
+void net_addr_str(const NETADDR *addr, char *string, int max_length, int add_port)
 {
 	if(addr->type == NETTYPE_IPV4)
 	{
-		if(addr->port != 0)
+		if(add_port != 0)
 			str_format(string, max_length, "%d.%d.%d.%d:%d", addr->ip[0], addr->ip[1], addr->ip[2], addr->ip[3], addr->port);
 		else
 			str_format(string, max_length, "%d.%d.%d.%d", addr->ip[0], addr->ip[1], addr->ip[2], addr->ip[3]);
 	}
 	else if(addr->type == NETTYPE_IPV6)
 	{
-		if(addr->port != 0)
+		if(add_port != 0)
 			str_format(string, max_length, "[%x:%x:%x:%x:%x:%x:%x:%x]:%d",
 				(addr->ip[0]<<8)|addr->ip[1], (addr->ip[2]<<8)|addr->ip[3], (addr->ip[4]<<8)|addr->ip[5], (addr->ip[6]<<8)|addr->ip[7],
 				(addr->ip[8]<<8)|addr->ip[9], (addr->ip[10]<<8)|addr->ip[11], (addr->ip[12]<<8)|addr->ip[13], (addr->ip[14]<<8)|addr->ip[15],
@@ -824,7 +856,15 @@ static int priv_net_create_socket(int do
 	sock = socket(domain, type, 0);
 	if(sock < 0)
 	{
+#if defined(CONF_FAMILY_WINDOWS)
+		char buf[128];
+		int error = WSAGetLastError();
+		if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, 0, error, 0, buf, sizeof(buf), 0) == 0)
+			buf[0] = 0;
+		dbg_msg("net", "failed to create socket with domain %d and type %d (%d '%s')", domain, type, error, buf);
+#else
 		dbg_msg("net", "failed to create socket with domain %d and type %d (%d '%s')", domain, type, errno, strerror(errno));
+#endif
 		return -1;
 	}
 
@@ -841,7 +881,15 @@ static int priv_net_create_socket(int do
 	e = bind(sock, addr, sockaddrlen);
 	if(e != 0)
 	{
+#if defined(CONF_FAMILY_WINDOWS)
+		char buf[128];
+		int error = WSAGetLastError();
+		if(FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS, 0, error, 0, buf, sizeof(buf), 0) == 0)
+			buf[0] = 0;
+		dbg_msg("net", "failed to bind socket with domain %d and type %d (%d '%s')", domain, type, error, buf);
+#else
 		dbg_msg("net", "failed to bind socket with domain %d and type %d (%d '%s')", domain, type, errno, strerror(errno));
+#endif
 		priv_net_close_socket(sock);
 		return -1;
 	}
@@ -1119,7 +1167,7 @@ int net_tcp_accept(NETSOCKET sock, NETSO
 		sockaddr_len = sizeof(addr);
 
 		s = accept(sock.ipv4sock, (struct sockaddr *)&addr, &sockaddr_len);
-		
+
 		if (s != -1)
 		{
 			sockaddr_to_netaddr((const struct sockaddr *)&addr, a);
@@ -1135,7 +1183,7 @@ int net_tcp_accept(NETSOCKET sock, NETSO
 		sockaddr_len = sizeof(addr);
 
 		s = accept(sock.ipv6sock, (struct sockaddr *)&addr, &sockaddr_len);
-		
+
 		if (s != -1)
 		{
 			sockaddr_to_netaddr((const struct sockaddr *)&addr, a);
@@ -1186,7 +1234,7 @@ int net_tcp_send(NETSOCKET sock, const v
 		bytes = send((int)sock.ipv4sock, (const char*)data, size, 0);
 	if(sock.ipv6sock >= 0)
 		bytes = send((int)sock.ipv6sock, (const char*)data, size, 0);
-		
+
 	return bytes;
 }
 
@@ -1198,7 +1246,7 @@ int net_tcp_recv(NETSOCKET sock, void *d
 		bytes = recv((int)sock.ipv4sock, (char*)data, maxsize, 0);
 	if(sock.ipv6sock >= 0)
 		bytes = recv((int)sock.ipv6sock, (char*)data, maxsize, 0);
-		
+
 	return bytes;
 }
 
@@ -1477,7 +1525,7 @@ int net_socket_read_wait(NETSOCKET sock,
 	return 0;
 }
 
-unsigned time_timestamp()
+int time_timestamp()
 {
 	return time(0);
 }
diff -rupN teeworlds-b177-r50edfd37-source/src//base/system.h alien-rc4/src//base/system.h
--- teeworlds-b177-r50edfd37-source/src//base/system.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//base/system.h	2012-06-14 23:57:39.000000000 +0200
@@ -240,6 +240,18 @@ unsigned io_skip(IOHANDLE io, int size);
 unsigned io_write(IOHANDLE io, const void *buffer, unsigned size);
 
 /*
+	Function: io_write_newline
+		Writes newline to file.
+
+	Parameters:
+		io - Handle to the file.
+
+	Returns:
+		Number of bytes written.
+*/
+unsigned io_write_newline(IOHANDLE io);
+
+/*
 	Function: io_seek
 		Seeks to a specified offset in the file.
 
@@ -388,6 +400,23 @@ int lock_try(LOCK lock);
 void lock_wait(LOCK lock);
 void lock_release(LOCK lock);
 
+
+/* Group: Semaphores */
+
+#if defined(CONF_FAMILY_UNIX)
+	#include <semaphore.h>
+	typedef sem_t SEMAPHORE;
+#elif defined(CONF_FAMILY_WINDOWS)
+	typedef void* SEMAPHORE;
+#else
+	#error missing sempahore implementation
+#endif
+
+void semaphore_init(SEMAPHORE *sem);
+void semaphore_wait(SEMAPHORE *sem);
+void semaphore_signal(SEMAPHORE *sem);
+void semaphore_destroy(SEMAPHORE *sem);
+
 /* Group: Timer */
 #ifdef __GNUC__
 /* if compiled with -pedantic-errors it will complain about long
@@ -425,7 +454,7 @@ int64 time_freq();
 	Returns:
 		The time as a UNIX timestamp
 */
-unsigned time_timestamp();
+int time_timestamp();
 
 /* Group: Network General */
 typedef struct
@@ -499,12 +528,13 @@ int net_addr_comp(const NETADDR *a, cons
 		addr - Address to turn into a string.
 		string - Buffer to fill with the string.
 		max_length - Maximum size of the string.
+		add_port - add port to string or not
 
 	Remarks:
 		- The string will always be zero terminated
 
 */
-void net_addr_str(const NETADDR *addr, char *string, int max_length);
+void net_addr_str(const NETADDR *addr, char *string, int max_length, int add_port);
 
 /*
 	Function: net_addr_from_str
@@ -1130,25 +1160,6 @@ void mem_debug_dump(IOHANDLE file);
 
 void swap_endian(void *data, unsigned elem_size, unsigned num);
 
-/* Group: Debug levels */
-//by format
-enum {
-	DBG_FMT_RAW				= 1,	//raw output
-	DBG_FMT_TIME			= 2,	//show time
-	DBG_FMT_SYS				= 3,	//show sys
-	DBG_FMT_FULL			= 4		//show both
-};
-
-enum {
-	DBG_LEVEL_IMPORTANT			= 0,	//important always showed messages
-	DBG_LEVEL_ERROR				= 1,	//error messages
-	DBG_LEVEL_WARNING			= 2,	//warning messages
-	DBG_LEVEL_MSG				= 3,	//extra debug messages
-	DBG_LEVEL_INFO				= 4		//info messages
-};
-
-#define DBG_LEVEL_LOW DBG_LEVEL_IMPORTANT
-#define DBG_LEVEL_HIGH DBG_LEVEL_INFO
 
 typedef void (*DBG_LOGGER)(const char *line);
 void dbg_logger(DBG_LOGGER logger);
diff -rupN teeworlds-b177-r50edfd37-source/src//base/tl/threading.h alien-rc4/src//base/tl/threading.h
--- teeworlds-b177-r50edfd37-source/src//base/tl/threading.h	1970-01-01 01:00:00.000000000 +0100
+++ alien-rc4/src//base/tl/threading.h	2012-06-14 23:57:39.000000000 +0200
@@ -0,0 +1,106 @@
+
+#pragma once
+
+#include "../system.h"
+
+/*
+	atomic_inc - should return the value after increment
+	atomic_dec - should return the value after decrement
+	atomic_compswap - should return the value before the eventual swap
+	
+*/
+
+#if defined(__GNUC__)
+
+	inline unsigned atomic_inc(volatile unsigned *pValue)
+	{
+		return __sync_fetch_and_add(pValue, 1);
+	}
+
+	inline unsigned atomic_dec(volatile unsigned *pValue)
+	{
+		return __sync_fetch_and_add(pValue, -1);
+	}
+
+	inline unsigned atomic_compswap(volatile unsigned *pValue, unsigned comperand, unsigned value)
+	{
+		return __sync_val_compare_and_swap(pValue, comperand, value);
+	}
+
+	inline void sync_barrier()
+	{
+		__sync_synchronize();
+	}
+
+#elif defined(_MSC_VER)
+	#include <intrin.h>
+
+	inline unsigned atomic_inc(volatile unsigned *pValue)
+	{
+		return _InterlockedIncrement((volatile long *)pValue);
+	}
+	
+	inline unsigned atomic_dec(volatile unsigned *pValue)
+	{
+		return _InterlockedDecrement((volatile long *)pValue);
+	}
+
+	inline unsigned atomic_compswap(volatile unsigned *pValue, unsigned comperand, unsigned value)
+	{
+		return _InterlockedCompareExchange((volatile long *)pValue, (long)value, (long)comperand);
+	}
+
+	inline void sync_barrier()
+	{
+		_ReadWriteBarrier();
+	}
+#else
+	#error missing atomic implementation for this compiler
+#endif
+
+class semaphore
+{
+	SEMAPHORE sem;
+public:
+	semaphore() { semaphore_init(&sem); }
+	~semaphore() { semaphore_destroy(&sem); }
+	void wait() { semaphore_wait(&sem); }
+	void signal() { semaphore_signal(&sem); }
+};
+
+class lock
+{
+	friend class scope_lock;
+
+	LOCK var;
+
+	void take() { lock_wait(var); }
+	void release() { lock_release(var); }
+
+public:
+	lock()
+	{
+		var = lock_create();
+	}
+
+	~lock()
+	{
+		lock_destroy(var);
+	}
+};
+
+class scope_lock
+{
+	lock *var;
+public:
+	scope_lock(lock *l)
+	{
+		var = l;
+		var->take();
+	}
+
+	~scope_lock()
+	{
+		var->release();
+	}
+};
diff -rupN teeworlds-b177-r50edfd37-source/src//base/vmath.h alien-rc4/src//base/vmath.h
--- teeworlds-b177-r50edfd37-source/src//base/vmath.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//base/vmath.h	2012-06-14 23:57:39.000000000 +0200
@@ -25,12 +25,18 @@ public:
 	vector2_base operator -(const vector2_base &v) const { return vector2_base(x-v.x, y-v.y); }
 	vector2_base operator +(const vector2_base &v) const { return vector2_base(x+v.x, y+v.y); }
 	vector2_base operator *(const T v) const { return vector2_base(x*v, y*v); }
+	vector2_base operator *(const vector2_base &v) const { return vector2_base(x*v.x, y*v.y); }
+	vector2_base operator /(const T v) const { return vector3_base(x/v, y/v); }
+	vector2_base operator /(const vector2_base &v) const { return vector2_base(x/v.x, y/v.y); }
 
 	const vector2_base &operator =(const vector2_base &v) { x = v.x; y = v.y; return *this; }
 
 	const vector2_base &operator +=(const vector2_base &v) { x += v.x; y += v.y; return *this; }
 	const vector2_base &operator -=(const vector2_base &v) { x -= v.x; y -= v.y; return *this; }
 	const vector2_base &operator *=(const T v) { x *= v; y *= v; return *this;	}
+	const vector2_base &operator *=(const vector2_base &v) { x *= v.x; y *= v.y; return *this; }
+	const vector2_base &operator /=(const T v) { x /= v; y /= v; return *this;	}
+	const vector2_base &operator /=(const vector2_base &v) { x /= v.x; y /= v.y; return *this; }
 
 	bool operator ==(const vector2_base &v) const { return x == v.x && y == v.y; } //TODO: do this with an eps instead
 
@@ -107,10 +113,14 @@ public:
 	vector3_base operator *(const T v) const { return vector3_base(x*v, y*v, z*v); }
 	vector3_base operator *(const vector3_base &v) const { return vector3_base(x*v.x, y*v.y, z*v.z); }
 	vector3_base operator /(const T v) const { return vector3_base(x/v, y/v, z/v); }
+	vector3_base operator /(const vector3_base &v) const { return vector3_base(x/v.x, y/v.y, z/v.z); }
 
 	const vector3_base &operator +=(const vector3_base &v) { x += v.x; y += v.y; z += v.z; return *this; }
 	const vector3_base &operator -=(const vector3_base &v) { x -= v.x; y -= v.y; z -= v.z; return *this; }
 	const vector3_base &operator *=(const T v) { x *= v; y *= v; z *= v; return *this;	}
+	const vector3_base &operator *=(const vector3_base &v) { x *= v.x; y *= v.y; z *= v.z; return *this; }
+	const vector3_base &operator /=(const T v) { x /= v; y /= v; z /= v; return *this;	}
+	const vector3_base &operator /=(const vector3_base &v) { x /= v.x; y /= v.y; z /= v.z; return *this; }
 
 	bool operator ==(const vector3_base &v) const { return x == v.x && y == v.y && z == v.z; } //TODO: do this with an eps instead
 
@@ -180,12 +190,17 @@ public:
 	vector4_base operator -() const { return vector4_base(-x, -y, -z, -w); }
 	vector4_base operator *(const vector4_base &v) const { return vector4_base(x*v.x, y*v.y, z*v.z, w*v.w); }
 	vector4_base operator *(const T v) const { return vector4_base(x*v, y*v, z*v, w*v); }
+	vector4_base operator /(const vector4_base &v) const { return vector4_base(x/v.x, y/v.y, z/v.z, w/v.w); }
+	vector4_base operator /(const T v) const { return vector4_base(x/v, y/v, z/v, w/v); }
 
 	const vector4_base &operator =(const vector4_base &v) { x = v.x; y = v.y; z = v.z; w = v.w; return *this; }
 
 	const vector4_base &operator +=(const vector4_base &v) { x += v.x; y += v.y; z += v.z; w += v.w; return *this; }
 	const vector4_base &operator -=(const vector4_base &v) { x -= v.x; y -= v.y; z -= v.z; w -= v.w; return *this; }
 	const vector4_base &operator *=(const T v) { x *= v; y *= v; z *= v; w *= v; return *this;	}
+	const vector4_base &operator *=(const vector4_base &v) { x *= v.x; y *= v.y; z *= v.z; w *= v.w; return *this; }
+	const vector4_base &operator /=(const T v) { x /= v; y /= v; z /= v; w /= v; return *this;	}
+	const vector4_base &operator /=(const vector4_base &v) { x /= v.x; y /= v.y; z /= v.z; w /= v.w; return *this; }
 
 	bool operator ==(const vector4_base &v) const { return x == v.x && y == v.y && z == v.z && w == v.w; } //TODO: do this with an eps instead
 
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/client/backend_sdl.cpp alien-rc4/src//engine/client/backend_sdl.cpp
--- teeworlds-b177-r50edfd37-source/src//engine/client/backend_sdl.cpp	1970-01-01 01:00:00.000000000 +0100
+++ alien-rc4/src//engine/client/backend_sdl.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -0,0 +1,515 @@
+
+#include "SDL.h"
+#include "SDL_opengl.h"
+
+#include <base/tl/threading.h>
+
+#include "graphics_threaded.h"
+#include "backend_sdl.h"
+
+// ------------ CGraphicsBackend_Threaded
+
+void CGraphicsBackend_Threaded::ThreadFunc(void *pUser)
+{
+	CGraphicsBackend_Threaded *pThis = (CGraphicsBackend_Threaded *)pUser;
+
+	while(!pThis->m_Shutdown)
+	{
+		pThis->m_Activity.wait();
+		if(pThis->m_pBuffer)
+		{
+			pThis->m_pProcessor->RunBuffer(pThis->m_pBuffer);
+			sync_barrier();
+			pThis->m_pBuffer = 0x0;
+			pThis->m_BufferDone.signal();
+		}
+	}
+}
+
+CGraphicsBackend_Threaded::CGraphicsBackend_Threaded()
+{
+	m_pBuffer = 0x0;
+	m_pProcessor = 0x0;
+	m_pThread = 0x0;
+}
+
+void CGraphicsBackend_Threaded::StartProcessor(ICommandProcessor *pProcessor)
+{
+	m_Shutdown = false;
+	m_pProcessor = pProcessor;
+	m_pThread = thread_create(ThreadFunc, this);
+	m_BufferDone.signal();
+}
+
+void CGraphicsBackend_Threaded::StopProcessor()
+{
+	m_Shutdown = true;
+	m_Activity.signal();
+	thread_wait(m_pThread);
+	thread_destroy(m_pThread);
+}
+
+void CGraphicsBackend_Threaded::RunBuffer(CCommandBuffer *pBuffer)
+{
+	WaitForIdle();
+	m_pBuffer = pBuffer;
+	m_Activity.signal();
+}
+
+bool CGraphicsBackend_Threaded::IsIdle() const
+{
+	return m_pBuffer == 0x0;
+}
+
+void CGraphicsBackend_Threaded::WaitForIdle()
+{
+	while(m_pBuffer != 0x0)
+		m_BufferDone.wait();
+}
+
+
+// ------------ CCommandProcessorFragment_General
+
+void CCommandProcessorFragment_General::Cmd_Signal(const CCommandBuffer::SCommand_Signal *pCommand)
+{
+	pCommand->m_pSemaphore->signal();
+}
+
+bool CCommandProcessorFragment_General::RunCommand(const CCommandBuffer::SCommand * pBaseCommand)
+{
+	switch(pBaseCommand->m_Cmd)
+	{
+	case CCommandBuffer::CMD_NOP: break;
+	case CCommandBuffer::CMD_SIGNAL: Cmd_Signal(static_cast<const CCommandBuffer::SCommand_Signal *>(pBaseCommand)); break;
+	default: return false;
+	}
+
+	return true;
+}
+
+// ------------ CCommandProcessorFragment_OpenGL
+
+int CCommandProcessorFragment_OpenGL::TexFormatToOpenGLFormat(int TexFormat)
+{
+	if(TexFormat == CCommandBuffer::TEXFORMAT_RGB) return GL_RGB;
+	if(TexFormat == CCommandBuffer::TEXFORMAT_ALPHA) return GL_ALPHA;
+	if(TexFormat == CCommandBuffer::TEXFORMAT_RGBA) return GL_RGBA;
+	return GL_RGBA;
+}
+
+void CCommandProcessorFragment_OpenGL::SetState(const CCommandBuffer::SState &State)
+{
+	// blend
+	switch(State.m_BlendMode)
+	{
+	case CCommandBuffer::BLEND_NONE:
+		glDisable(GL_BLEND);
+		break;
+	case CCommandBuffer::BLEND_ALPHA:
+		glEnable(GL_BLEND);
+		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+		break;
+	case CCommandBuffer::BLEND_ADDITIVE:
+		glEnable(GL_BLEND);
+		glBlendFunc(GL_SRC_ALPHA, GL_ONE);
+		break;
+	default:
+		dbg_msg("render", "unknown blendmode %d\n", State.m_BlendMode);
+	};
+
+	// clip
+	if(State.m_ClipEnable)
+	{
+		glScissor(State.m_ClipX, State.m_ClipY, State.m_ClipW, State.m_ClipH);
+		glEnable(GL_SCISSOR_TEST);
+	}
+	else
+		glDisable(GL_SCISSOR_TEST);
+	
+	// texture
+	if(State.m_Texture >= 0 && State.m_Texture < CCommandBuffer::MAX_TEXTURES)
+	{
+		glEnable(GL_TEXTURE_2D);
+		glBindTexture(GL_TEXTURE_2D, m_aTextures[State.m_Texture]);
+	}
+	else
+		glDisable(GL_TEXTURE_2D);
+
+	switch(State.m_WrapMode)
+	{
+	case CCommandBuffer::WRAP_REPEAT:
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
+		break;
+	case CCommandBuffer::WRAP_CLAMP:
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+		break;
+	default:
+		dbg_msg("render", "unknown wrapmode %d\n", State.m_WrapMode);
+	};
+
+	// screen mapping
+	glMatrixMode(GL_PROJECTION);
+	glLoadIdentity();
+	glOrtho(State.m_ScreenTL.x, State.m_ScreenBR.x, State.m_ScreenBR.y, State.m_ScreenTL.y, 1.0f, 10.f);
+}
+
+void CCommandProcessorFragment_OpenGL::Cmd_Texture_Update(const CCommandBuffer::SCommand_Texture_Update *pCommand)
+{
+	glBindTexture(GL_TEXTURE_2D, m_aTextures[pCommand->m_Slot]);
+	glTexSubImage2D(GL_TEXTURE_2D, 0, pCommand->m_X, pCommand->m_Y, pCommand->m_Width, pCommand->m_Height,
+		TexFormatToOpenGLFormat(pCommand->m_Format), GL_UNSIGNED_BYTE, pCommand->m_pData);
+	mem_free(pCommand->m_pData);
+}
+
+void CCommandProcessorFragment_OpenGL::Cmd_Texture_Destroy(const CCommandBuffer::SCommand_Texture_Destroy *pCommand)
+{
+	glDeleteTextures(1, &m_aTextures[pCommand->m_Slot]);
+}
+
+void CCommandProcessorFragment_OpenGL::Cmd_Texture_Create(const CCommandBuffer::SCommand_Texture_Create *pCommand)
+{
+	int Oglformat = TexFormatToOpenGLFormat(pCommand->m_Format);
+	int StoreOglformat = TexFormatToOpenGLFormat(pCommand->m_StoreFormat);
+
+	glGenTextures(1, &m_aTextures[pCommand->m_Slot]);
+	glBindTexture(GL_TEXTURE_2D, m_aTextures[pCommand->m_Slot]);
+
+	if(pCommand->m_Flags&CCommandBuffer::TEXFLAG_NOMIPMAPS)
+	{
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+		glTexImage2D(GL_TEXTURE_2D, 0, StoreOglformat, pCommand->m_Width, pCommand->m_Height, 0, Oglformat, GL_UNSIGNED_BYTE, pCommand->m_pData);
+	}
+	else
+	{
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
+		gluBuild2DMipmaps(GL_TEXTURE_2D, StoreOglformat, pCommand->m_Width, pCommand->m_Height, Oglformat, GL_UNSIGNED_BYTE, pCommand->m_pData);
+	}
+
+	mem_free(pCommand->m_pData);
+}
+
+void CCommandProcessorFragment_OpenGL::Cmd_Clear(const CCommandBuffer::SCommand_Clear *pCommand)
+{
+	glClearColor(pCommand->m_Color.r, pCommand->m_Color.g, pCommand->m_Color.b, 0.0f);
+	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+}
+
+void CCommandProcessorFragment_OpenGL::Cmd_Render(const CCommandBuffer::SCommand_Render *pCommand)
+{
+	SetState(pCommand->m_State);
+	
+	glVertexPointer(3, GL_FLOAT, sizeof(CCommandBuffer::SVertex), (char*)pCommand->m_pVertices);
+	glTexCoordPointer(2, GL_FLOAT, sizeof(CCommandBuffer::SVertex), (char*)pCommand->m_pVertices + sizeof(float)*3);
+	glColorPointer(4, GL_FLOAT, sizeof(CCommandBuffer::SVertex), (char*)pCommand->m_pVertices + sizeof(float)*5);
+	glEnableClientState(GL_VERTEX_ARRAY);
+	glEnableClientState(GL_TEXTURE_COORD_ARRAY);
+	glEnableClientState(GL_COLOR_ARRAY);
+
+	switch(pCommand->m_PrimType)
+	{
+	case CCommandBuffer::PRIMTYPE_QUADS:
+		glDrawArrays(GL_QUADS, 0, pCommand->m_PrimCount*4);
+		break;
+	case CCommandBuffer::PRIMTYPE_LINES:
+		glDrawArrays(GL_LINES, 0, pCommand->m_PrimCount*2);
+		break;
+	default:
+		dbg_msg("render", "unknown primtype %d\n", pCommand->m_Cmd);
+	};
+}
+
+void CCommandProcessorFragment_OpenGL::Cmd_Screenshot(const CCommandBuffer::SCommand_Screenshot *pCommand)
+{
+	// fetch image data
+	GLint aViewport[4] = {0,0,0,0};
+	glGetIntegerv(GL_VIEWPORT, aViewport);
+
+	int w = aViewport[2];
+	int h = aViewport[3];
+
+	// we allocate one more row to use when we are flipping the texture
+	unsigned char *pPixelData = (unsigned char *)mem_alloc(w*(h+1)*3, 1);
+	unsigned char *pTempRow = pPixelData+w*h*3;
+
+	// fetch the pixels
+	GLint Alignment;
+	glGetIntegerv(GL_PACK_ALIGNMENT, &Alignment);
+	glPixelStorei(GL_PACK_ALIGNMENT, 1);
+	glReadPixels(0,0, w, h, GL_RGB, GL_UNSIGNED_BYTE, pPixelData);
+	glPixelStorei(GL_PACK_ALIGNMENT, Alignment);
+
+	// flip the pixel because opengl works from bottom left corner
+	for(int y = 0; y < h/2; y++)
+	{
+		mem_copy(pTempRow, pPixelData+y*w*3, w*3);
+		mem_copy(pPixelData+y*w*3, pPixelData+(h-y-1)*w*3, w*3);
+		mem_copy(pPixelData+(h-y-1)*w*3, pTempRow,w*3);
+	}
+
+	// fill in the information
+	pCommand->m_pImage->m_Width = w;
+	pCommand->m_pImage->m_Height = h;
+	pCommand->m_pImage->m_Format = CImageInfo::FORMAT_RGB;
+	pCommand->m_pImage->m_pData = pPixelData;
+}
+
+CCommandProcessorFragment_OpenGL::CCommandProcessorFragment_OpenGL()
+{
+	mem_zero(m_aTextures, sizeof(m_aTextures));
+}
+
+bool CCommandProcessorFragment_OpenGL::RunCommand(const CCommandBuffer::SCommand * pBaseCommand)
+{
+	switch(pBaseCommand->m_Cmd)
+	{
+	case CCommandBuffer::CMD_TEXTURE_CREATE: Cmd_Texture_Create(static_cast<const CCommandBuffer::SCommand_Texture_Create *>(pBaseCommand)); break;
+	case CCommandBuffer::CMD_TEXTURE_DESTROY: Cmd_Texture_Destroy(static_cast<const CCommandBuffer::SCommand_Texture_Destroy *>(pBaseCommand)); break;
+	case CCommandBuffer::CMD_TEXTURE_UPDATE: Cmd_Texture_Update(static_cast<const CCommandBuffer::SCommand_Texture_Update *>(pBaseCommand)); break;
+	case CCommandBuffer::CMD_CLEAR: Cmd_Clear(static_cast<const CCommandBuffer::SCommand_Clear *>(pBaseCommand)); break;
+	case CCommandBuffer::CMD_RENDER: Cmd_Render(static_cast<const CCommandBuffer::SCommand_Render *>(pBaseCommand)); break;
+	case CCommandBuffer::CMD_SCREENSHOT: Cmd_Screenshot(static_cast<const CCommandBuffer::SCommand_Screenshot *>(pBaseCommand)); break;
+	default: return false;
+	}
+
+	return true;
+}
+
+
+// ------------ CCommandProcessorFragment_SDL
+
+void CCommandProcessorFragment_SDL::Cmd_Init(const SCommand_Init *pCommand)
+{
+	m_GLContext = pCommand->m_Context;
+	GL_MakeCurrent(m_GLContext);
+
+	// set some default settings
+	glEnable(GL_BLEND);
+	glDisable(GL_CULL_FACE);
+	glDisable(GL_DEPTH_TEST);
+	glMatrixMode(GL_MODELVIEW);
+	glLoadIdentity();
+
+	glAlphaFunc(GL_GREATER, 0);
+	glEnable(GL_ALPHA_TEST);
+	glDepthMask(0);
+}
+
+void CCommandProcessorFragment_SDL::Cmd_Shutdown(const SCommand_Shutdown *pCommand)
+{
+	GL_ReleaseContext(m_GLContext);
+}
+
+void CCommandProcessorFragment_SDL::Cmd_Swap(const CCommandBuffer::SCommand_Swap *pCommand)
+{
+	GL_SwapBuffers(m_GLContext);
+
+	if(pCommand->m_Finish)
+		glFinish();
+}
+
+void CCommandProcessorFragment_SDL::Cmd_VideoModes(const CCommandBuffer::SCommand_VideoModes *pCommand)
+{
+	// TODO: fix this code on osx or windows
+	SDL_Rect **ppModes = SDL_ListModes(NULL, SDL_OPENGL|SDL_GL_DOUBLEBUFFER|SDL_FULLSCREEN);
+	if(ppModes == NULL)
+	{
+		// no modes
+		*pCommand->m_pNumModes = 0;
+	}
+	else if(ppModes == (SDL_Rect**)-1)
+	{
+		// no modes
+		*pCommand->m_pNumModes = 0;
+	}
+	else
+	{
+		int NumModes = 0;
+		for(int i = 0; ppModes[i]; ++i)
+		{
+			if(NumModes == pCommand->m_MaxModes)
+				break;
+			pCommand->m_pModes[NumModes].m_Width = ppModes[i]->w;
+			pCommand->m_pModes[NumModes].m_Height = ppModes[i]->h;
+			pCommand->m_pModes[NumModes].m_Red = 8;
+			pCommand->m_pModes[NumModes].m_Green = 8;
+			pCommand->m_pModes[NumModes].m_Blue = 8;
+			NumModes++;
+		}
+
+		*pCommand->m_pNumModes = NumModes;
+	}
+}
+
+CCommandProcessorFragment_SDL::CCommandProcessorFragment_SDL()
+{
+}
+
+bool CCommandProcessorFragment_SDL::RunCommand(const CCommandBuffer::SCommand *pBaseCommand)
+{
+	switch(pBaseCommand->m_Cmd)
+	{
+	case CCommandBuffer::CMD_SWAP: Cmd_Swap(static_cast<const CCommandBuffer::SCommand_Swap *>(pBaseCommand)); break;
+	case CCommandBuffer::CMD_VIDEOMODES: Cmd_VideoModes(static_cast<const CCommandBuffer::SCommand_VideoModes *>(pBaseCommand)); break;
+	case CMD_INIT: Cmd_Init(static_cast<const SCommand_Init *>(pBaseCommand)); break;
+	case CMD_SHUTDOWN: Cmd_Shutdown(static_cast<const SCommand_Shutdown *>(pBaseCommand)); break;
+	default: return false;
+	}
+
+	return true;
+}
+
+// ------------ CCommandProcessor_SDL_OpenGL
+
+void CCommandProcessor_SDL_OpenGL::RunBuffer(CCommandBuffer *pBuffer)
+{
+	unsigned CmdIndex = 0;
+	while(1)
+	{
+		const CCommandBuffer::SCommand *pBaseCommand = pBuffer->GetCommand(&CmdIndex);
+		if(pBaseCommand == 0x0)
+			break;
+		
+		if(m_OpenGL.RunCommand(pBaseCommand))
+			continue;
+		
+		if(m_SDL.RunCommand(pBaseCommand))
+			continue;
+
+		if(m_General.RunCommand(pBaseCommand))
+			continue;
+		
+		dbg_msg("graphics", "unknown command %d", pBaseCommand->m_Cmd);
+	}
+}
+
+// ------------ CGraphicsBackend_SDL_OpenGL
+
+int CGraphicsBackend_SDL_OpenGL::Init(const char *pName, int Width, int Height, int FsaaSamples, int Flags)
+{
+	if(!SDL_WasInit(SDL_INIT_VIDEO))
+	{
+		if(SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
+		{
+			dbg_msg("gfx", "unable to init SDL video: %s", SDL_GetError());
+			return -1;
+		}
+
+		#ifdef CONF_FAMILY_WINDOWS
+			if(!getenv("SDL_VIDEO_WINDOW_POS") && !getenv("SDL_VIDEO_CENTERED")) // ignore_convention
+				putenv("SDL_VIDEO_WINDOW_POS=8,27"); // ignore_convention
+		#endif
+	}
+
+	const SDL_VideoInfo *pInfo = SDL_GetVideoInfo();
+	SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE); // prevent stuck mouse cursor sdl-bug when loosing fullscreen focus in windows
+
+	// set flags
+	int SdlFlags = SDL_OPENGL;
+	if(Flags&IGraphicsBackend::INITFLAG_RESIZABLE)
+		SdlFlags |= SDL_RESIZABLE;
+
+	if(pInfo->hw_available) // ignore_convention
+		SdlFlags |= SDL_HWSURFACE;
+	else
+		SdlFlags |= SDL_SWSURFACE;
+
+	if(pInfo->blit_hw) // ignore_convention
+		SdlFlags |= SDL_HWACCEL;
+
+	if(Flags&IGraphicsBackend::INITFLAG_FULLSCREEN)
+		SdlFlags |= SDL_FULLSCREEN;
+
+	// set gl attributes
+	if(FsaaSamples)
+	{
+		SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
+		SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, FsaaSamples);
+	}
+	else
+	{
+		SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 0);
+		SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 0);
+	}
+
+	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
+	SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, Flags&CCommandBuffer::INITFLAG_VSYNC ? 1 : 0);
+
+	// set caption
+	SDL_WM_SetCaption(pName, pName);
+
+	// create window
+	m_pScreenSurface = SDL_SetVideoMode(Width, Height, 0, SdlFlags);
+	if(!m_pScreenSurface)
+	{
+		dbg_msg("gfx", "unable to set video mode: %s", SDL_GetError());
+		//*pCommand->m_pResult = -1;
+		return -1;
+	}		
+
+	SDL_ShowCursor(0);
+
+	// fetch gl contexts and release the context from this thread
+	m_GLContext = GL_GetCurrentContext();
+	GL_ReleaseContext(m_GLContext);
+
+	// start the command processor
+	m_pProcessor = new CCommandProcessor_SDL_OpenGL;
+	StartProcessor(m_pProcessor);
+
+	// issue a init command
+	CCommandBuffer CmdBuffer(1024, 512);
+	CCommandProcessorFragment_SDL::SCommand_Init Cmd;
+	Cmd.m_Context = m_GLContext;
+	CmdBuffer.AddCommand(Cmd);
+	RunBuffer(&CmdBuffer);
+	WaitForIdle();
+
+	// return
+	return 0;
+}
+
+int CGraphicsBackend_SDL_OpenGL::Shutdown()
+{
+	// issue a shutdown command
+	CCommandBuffer CmdBuffer(1024, 512);
+	CCommandProcessorFragment_SDL::SCommand_Shutdown Cmd;
+	CmdBuffer.AddCommand(Cmd);
+	RunBuffer(&CmdBuffer);
+	WaitForIdle();
+			
+	// stop and delete the processor
+	StopProcessor();
+	delete m_pProcessor;
+	m_pProcessor = 0;
+
+	SDL_QuitSubSystem(SDL_INIT_VIDEO);
+	return 0;
+}
+
+void CGraphicsBackend_SDL_OpenGL::Minimize()
+{
+	SDL_WM_IconifyWindow();
+}
+
+void CGraphicsBackend_SDL_OpenGL::Maximize()
+{
+	// TODO: SDL
+}
+
+int CGraphicsBackend_SDL_OpenGL::WindowActive()
+{
+	return SDL_GetAppState()&SDL_APPINPUTFOCUS;
+}
+
+int CGraphicsBackend_SDL_OpenGL::WindowOpen()
+{
+	return SDL_GetAppState()&SDL_APPACTIVE;
+
+}
+
+
+IGraphicsBackend *CreateGraphicsBackend() { return new CGraphicsBackend_SDL_OpenGL; }
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/client/backend_sdl.h alien-rc4/src//engine/client/backend_sdl.h
--- teeworlds-b177-r50edfd37-source/src//engine/client/backend_sdl.h	1970-01-01 01:00:00.000000000 +0100
+++ alien-rc4/src//engine/client/backend_sdl.h	2012-06-14 23:57:39.000000000 +0200
@@ -0,0 +1,198 @@
+
+#include "SDL.h"
+#include "SDL_opengl.h"
+
+#include "graphics_threaded.h"
+
+
+
+// platform dependent implementations for transfering render context from the main thread to the graphics thread
+// TODO: when SDL 1.3 comes, this can be removed
+#if defined(CONF_FAMILY_WINDOWS)
+	struct SGLContext
+	{
+		HDC m_hDC;
+		HGLRC m_hGLRC;
+	};
+
+	static SGLContext GL_GetCurrentContext()
+	{
+		SGLContext Context;
+		Context.m_hDC = wglGetCurrentDC();
+		Context.m_hGLRC = wglGetCurrentContext();
+		return Context;
+	}
+
+	static void GL_MakeCurrent(const SGLContext &Context) { wglMakeCurrent(Context.m_hDC, Context.m_hGLRC); }
+	static void GL_ReleaseContext(const SGLContext &Context) { wglMakeCurrent(NULL, NULL); }
+	static void GL_SwapBuffers(const SGLContext &Context) { SwapBuffers(Context.m_hDC); }
+#elif defined(CONF_PLATFORM_MACOSX)
+
+	#include <AGL/agl.h>
+
+	struct SGLContext
+	{
+		AGLContext m_Context;
+	};
+
+	static SGLContext GL_GetCurrentContext()
+	{
+		SGLContext Context;
+		Context.m_Context = aglGetCurrentContext();
+		return Context;
+	}
+
+	static void GL_MakeCurrent(const SGLContext &Context) { aglSetCurrentContext(Context.m_Context); }
+	static void GL_ReleaseContext(const SGLContext &Context) { aglSetCurrentContext(NULL); }
+	static void GL_SwapBuffers(const SGLContext &Context) { aglSwapBuffers(Context.m_Context); }
+		
+#elif defined(CONF_FAMILY_UNIX)
+
+	#include <GL/glx.h>
+
+	struct SGLContext
+	{
+		Display *m_pDisplay;
+		GLXDrawable m_Drawable;
+		GLXContext m_Context;
+	};
+
+	static SGLContext GL_GetCurrentContext()
+	{
+		SGLContext Context;
+		Context.m_pDisplay = glXGetCurrentDisplay();
+		Context.m_Drawable = glXGetCurrentDrawable();
+		Context.m_Context = glXGetCurrentContext();
+		return Context;
+	}
+
+	static void GL_MakeCurrent(const SGLContext &Context) { glXMakeCurrent(Context.m_pDisplay, Context.m_Drawable, Context.m_Context); }
+	static void GL_ReleaseContext(const SGLContext &Context) { glXMakeCurrent(Context.m_pDisplay, None, 0x0); }
+	static void GL_SwapBuffers(const SGLContext &Context) { glXSwapBuffers(Context.m_pDisplay, Context.m_Drawable); }
+#else
+	#error missing implementation
+#endif
+
+
+// basic threaded backend, abstract, missing init and shutdown functions
+class CGraphicsBackend_Threaded : public IGraphicsBackend
+{
+public:
+	// constructed on the main thread, the rest of the functions is runned on the render thread
+	class ICommandProcessor
+	{
+	public:
+		virtual ~ICommandProcessor() {}
+		virtual void RunBuffer(CCommandBuffer *pBuffer) = 0;
+	};
+
+	CGraphicsBackend_Threaded();
+
+	virtual void RunBuffer(CCommandBuffer *pBuffer);
+	virtual bool IsIdle() const;
+	virtual void WaitForIdle();
+		
+protected:
+	void StartProcessor(ICommandProcessor *pProcessor);
+	void StopProcessor();
+
+private:
+	ICommandProcessor *m_pProcessor;
+	CCommandBuffer * volatile m_pBuffer;
+	volatile bool m_Shutdown;
+	semaphore m_Activity;
+	semaphore m_BufferDone;
+	void *m_pThread;
+
+	static void ThreadFunc(void *pUser);
+};
+
+// takes care of implementation independent operations
+class CCommandProcessorFragment_General
+{
+	void Cmd_Nop();
+	void Cmd_Signal(const CCommandBuffer::SCommand_Signal *pCommand);
+public:
+	bool RunCommand(const CCommandBuffer::SCommand * pBaseCommand);
+};
+
+// takes care of opengl related rendering
+class CCommandProcessorFragment_OpenGL
+{
+	GLuint m_aTextures[CCommandBuffer::MAX_TEXTURES];
+	static int TexFormatToOpenGLFormat(int TexFormat);
+
+	void SetState(const CCommandBuffer::SState &State);
+
+	void Cmd_Texture_Update(const CCommandBuffer::SCommand_Texture_Update *pCommand);
+	void Cmd_Texture_Destroy(const CCommandBuffer::SCommand_Texture_Destroy *pCommand);
+	void Cmd_Texture_Create(const CCommandBuffer::SCommand_Texture_Create *pCommand);
+	void Cmd_Clear(const CCommandBuffer::SCommand_Clear *pCommand);
+	void Cmd_Render(const CCommandBuffer::SCommand_Render *pCommand);
+	void Cmd_Screenshot(const CCommandBuffer::SCommand_Screenshot *pCommand);
+
+public:
+	CCommandProcessorFragment_OpenGL();
+
+	bool RunCommand(const CCommandBuffer::SCommand * pBaseCommand);
+};
+
+// takes care of sdl related commands
+class CCommandProcessorFragment_SDL
+{
+	// SDL stuff
+	SGLContext m_GLContext;
+public:
+	enum
+	{
+		CMD_INIT = CCommandBuffer::CMDGROUP_PLATFORM,
+		CMD_SHUTDOWN,
+	};
+
+	struct SCommand_Init : public CCommandBuffer::SCommand
+	{
+		SCommand_Init() : SCommand(CMD_INIT) {}
+		SGLContext m_Context;
+	};
+
+	struct SCommand_Shutdown : public CCommandBuffer::SCommand
+	{
+		SCommand_Shutdown() : SCommand(CMD_SHUTDOWN) {}
+	};
+
+private:
+	void Cmd_Init(const SCommand_Init *pCommand);
+	void Cmd_Shutdown(const SCommand_Shutdown *pCommand);
+	void Cmd_Swap(const CCommandBuffer::SCommand_Swap *pCommand);
+	void Cmd_VideoModes(const CCommandBuffer::SCommand_VideoModes *pCommand);
+public:
+	CCommandProcessorFragment_SDL();
+
+	bool RunCommand(const CCommandBuffer::SCommand *pBaseCommand);
+};
+
+// command processor impelementation, uses the fragments to combine into one processor
+class CCommandProcessor_SDL_OpenGL : public CGraphicsBackend_Threaded::ICommandProcessor
+{
+ 	CCommandProcessorFragment_OpenGL m_OpenGL;
+ 	CCommandProcessorFragment_SDL m_SDL;
+ 	CCommandProcessorFragment_General m_General;
+ public:
+	virtual void RunBuffer(CCommandBuffer *pBuffer);
+};
+
+// graphics backend implemented with SDL and OpenGL
+class CGraphicsBackend_SDL_OpenGL : public CGraphicsBackend_Threaded
+{
+	SDL_Surface *m_pScreenSurface;
+	ICommandProcessor *m_pProcessor;
+	SGLContext m_GLContext;
+public:
+	virtual int Init(const char *pName, int Width, int Height, int FsaaSamples, int Flags);
+	virtual int Shutdown();
+
+	virtual void Minimize();
+	virtual void Maximize();
+	virtual int WindowActive();
+	virtual int WindowOpen();
+};
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/client/client.cpp alien-rc4/src//engine/client/client.cpp
--- teeworlds-b177-r50edfd37-source/src//engine/client/client.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/client/client.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -7,6 +7,7 @@
 
 #include <base/math.h>
 #include <base/system.h>
+#include <base/tl/threading.h>
 
 #include <engine/client.h>
 #include <engine/config.h>
@@ -35,6 +36,8 @@
 #include <engine/shared/ringbuffer.h>
 #include <engine/shared/snapshot.h>
 
+#include <game/version.h>
+
 #include <mastersrv/mastersrv.h>
 #include <versionsrv/versionsrv.h>
 
@@ -48,6 +51,10 @@
 	#include <windows.h>
 #endif
 
+#include "SDL.h"
+#ifdef main
+#undef main
+#endif
 
 void CGraph::Init(float Min, float Max)
 {
@@ -243,10 +250,11 @@ CClient::CClient() : m_DemoPlayer(&m_Sna
 	m_pMap = 0;
 	m_pConsole = 0;
 
-	m_FrameTime = 0.0001f;
-	m_FrameTimeLow = 1.0f;
-	m_FrameTimeHigh = 0.0f;
-	m_Frames = 0;
+	m_RenderFrameTime = 0.0001f;
+	m_RenderFrameTimeLow = 1.0f;
+	m_RenderFrameTimeHigh = 0.0f;
+	m_RenderFrames = 0;
+	m_LastRenderTime = time_get();
 
 	m_GameTickSpeed = SERVER_TICK_SPEED;
 
@@ -455,6 +463,9 @@ int *CClient::GetInput(int Tick)
 // ------ state handling -----
 void CClient::SetState(int s)
 {
+	if(m_State == IClient::STATE_QUITING)
+		return;
+
 	int Old = m_State;
 	if(g_Config.m_Debug)
 	{
@@ -546,6 +557,7 @@ void CClient::DisconnectWithReason(const
 
 	//
 	m_RconAuthed = 0;
+	m_UseTempRconCommands = 0;
 	m_pConsole->DeregisterTempAll();
 	m_NetClient.Disconnect(pReason);
 	SetState(IClient::STATE_OFFLINE);
@@ -680,13 +692,13 @@ void CClient::DebugRender()
 		udp = 8
 		total = 42
 	*/
-	FrameTimeAvg = FrameTimeAvg*0.9f + m_FrameTime*0.1f;
+	FrameTimeAvg = FrameTimeAvg*0.9f + m_RenderFrameTime*0.1f;
 	str_format(aBuffer, sizeof(aBuffer), "ticks: %8d %8d mem %dk %d gfxmem: %dk fps: %3d",
 		m_CurGameTick, m_PredTick,
 		mem_stats()->allocated/1024,
 		mem_stats()->total_allocations,
 		Graphics()->MemoryUsage()/1024,
-		(int)(1.0f/FrameTimeAvg));
+		(int)(1.0f/FrameTimeAvg + 0.5f));
 	Graphics()->QuadsText(2, 2, 16, 1,1,1,1, aBuffer);
 
 
@@ -849,23 +861,26 @@ void CClient::ProcessConnlessPacket(CNet
 	if(m_VersionInfo.m_State == CVersionInfo::STATE_READY && net_addr_comp(&pPacket->m_Address, &m_VersionInfo.m_VersionServeraddr.m_Addr) == 0)
 	{
 		// version info
-		if(pPacket->m_DataSize == (int)(sizeof(VERSIONSRV_VERSION) + sizeof(VERSION_DATA)) &&
+		if(pPacket->m_DataSize == (int)(sizeof(VERSIONSRV_VERSION) + sizeof(GAME_RELEASE_VERSION)) &&
 			mem_comp(pPacket->m_pData, VERSIONSRV_VERSION, sizeof(VERSIONSRV_VERSION)) == 0)
 
 		{
-			unsigned char *pVersionData = (unsigned char*)pPacket->m_pData + sizeof(VERSIONSRV_VERSION);
-			int VersionMatch = !mem_comp(pVersionData, VERSION_DATA, sizeof(VERSION_DATA));
+			char *pVersionData = (char*)pPacket->m_pData + sizeof(VERSIONSRV_VERSION);
+			int VersionMatch = !mem_comp(pVersionData, GAME_RELEASE_VERSION, sizeof(GAME_RELEASE_VERSION));
+
+			char aVersion[sizeof(GAME_RELEASE_VERSION)];
+			str_copy(aVersion, pVersionData, sizeof(aVersion));
 
 			char aBuf[256];
-			str_format(aBuf, sizeof(aBuf), "version does %s (%d.%d.%d)",
+			str_format(aBuf, sizeof(aBuf), "version does %s (%s)",
 				VersionMatch ? "match" : "NOT match",
-				pVersionData[1], pVersionData[2], pVersionData[3]);
+				aVersion);
 			m_pConsole->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "client/version", aBuf);
 
 			// assume version is out of date when version-data doesn't match
-			if (!VersionMatch)
+			if(!VersionMatch)
 			{
-				str_format(m_aVersionStr, sizeof(m_aVersionStr), "%d.%d.%d", pVersionData[1], pVersionData[2], pVersionData[3]);
+				str_copy(m_aVersionStr, aVersion, sizeof(m_aVersionStr));
 			}
 
 			// request the map version list now
@@ -964,7 +979,7 @@ void CClient::ProcessConnlessPacket(CNet
 			Info.m_NumPlayers < 0 || Info.m_NumPlayers > Info.m_NumClients || Info.m_MaxPlayers < 0 || Info.m_MaxPlayers > Info.m_MaxClients)
 			return;
 
-		net_addr_str(&pPacket->m_Address, Info.m_aAddress, sizeof(Info.m_aAddress));
+		net_addr_str(&pPacket->m_Address, Info.m_aAddress, sizeof(Info.m_aAddress), true);
 
 		for(int i = 0; i < Info.m_NumClients; i++)
 		{
@@ -1153,9 +1168,12 @@ void CClient::ProcessServerPacket(CNetCh
 			int Result = Unpacker.GetInt();
 			if(Unpacker.Error() == 0)
 				m_RconAuthed = Result;
+			int Old = m_UseTempRconCommands;
 			m_UseTempRconCommands = Unpacker.GetInt();
 			if(Unpacker.Error() != 0)
 				m_UseTempRconCommands = 0;
+			if(Old != 0 && m_UseTempRconCommands == 0)
+				m_pConsole->DeregisterTempAll();
 		}
 		else if(Msg == NETMSG_RCON_LINE)
 		{
@@ -1675,7 +1693,7 @@ void CClient::InitInterfaces()
 	// fetch interfaces
 	m_pEngine = Kernel()->RequestInterface<IEngine>();
 	m_pEditor = Kernel()->RequestInterface<IEditor>();
-	m_pGraphics = Kernel()->RequestInterface<IEngineGraphics>();
+	//m_pGraphics = Kernel()->RequestInterface<IEngineGraphics>();
 	m_pSound = Kernel()->RequestInterface<IEngineSound>();
 	m_pGameClient = Kernel()->RequestInterface<IGameClient>();
 	m_pInput = Kernel()->RequestInterface<IEngineInput>();
@@ -1690,21 +1708,49 @@ void CClient::InitInterfaces()
 
 void CClient::Run()
 {
-	int64 ReportTime = time_get();
-	int64 ReportInterval = time_freq()*1;
-
 	m_LocalStartTime = time_get();
 	m_SnapshotParts = 0;
 
+	// init SDL
+	{
+		if(SDL_Init(0) < 0)
+		{
+			dbg_msg("client", "unable to init SDL base: %s", SDL_GetError());
+			return;
+		}
+
+		atexit(SDL_Quit); // ignore_convention
+	}
+
 	// init graphics
-	if(m_pGraphics->Init() != 0)
-		return;
+	{
+		if(g_Config.m_GfxThreaded)
+			m_pGraphics = CreateEngineGraphicsThreaded();
+		else
+			m_pGraphics = CreateEngineGraphics();
+
+		bool RegisterFail = false;
+		RegisterFail = RegisterFail || !Kernel()->RegisterInterface(static_cast<IEngineGraphics*>(m_pGraphics)); // register graphics as both
+		RegisterFail = RegisterFail || !Kernel()->RegisterInterface(static_cast<IGraphics*>(m_pGraphics));
+
+		if(RegisterFail || m_pGraphics->Init() != 0)
+		{
+			dbg_msg("client", "couldn't init graphics");
+			return;
+		}
+	}
+
+	// init sound, allowed to fail
+	m_SoundInitFailed = Sound()->Init() != 0;
 
 	// open socket
 	{
 		NETADDR BindAddr;
-		mem_zero(&BindAddr, sizeof(BindAddr));
-		BindAddr.type = NETTYPE_ALL;
+		if(g_Config.m_Bindaddr[0] == 0 || net_host_lookup(g_Config.m_Bindaddr, &BindAddr, NETTYPE_ALL) != 0)
+		{
+			mem_zero(&BindAddr, sizeof(BindAddr));
+			BindAddr.type = NETTYPE_ALL;
+		}
 		if(!m_NetClient.Open(BindAddr, 0))
 		{
 			dbg_msg("client", "couldn't start network");
@@ -1724,14 +1770,13 @@ void CClient::Run()
 	// init the editor
 	m_pEditor->Init();
 
-	// init sound, allowed to fail
-	m_SoundInitFailed = Sound()->Init() != 0;
 
 	// load data
 	if(!LoadData())
 		return;
 
 	GameClient()->OnInit();
+
 	char aBuf[256];
 	str_format(aBuf, sizeof(aBuf), "version %s", GameClient()->NetVersion());
 	m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "client", aBuf);
@@ -1756,9 +1801,6 @@ void CClient::Run()
 
 	while (1)
 	{
-		int64 FrameStartTime = time_get();
-		m_Frames++;
-
 		//
 		VersionUpdate();
 
@@ -1808,7 +1850,10 @@ void CClient::Run()
 
 		// panic quit button
 		if(Input()->KeyPressed(KEY_LCTRL) && Input()->KeyPressed(KEY_LSHIFT) && Input()->KeyPressed('q'))
+		{
+			Quit();
 			break;
+		}
 
 		if(Input()->KeyPressed(KEY_LCTRL) && Input()->KeyPressed(KEY_LSHIFT) && Input()->KeyDown('d'))
 			g_Config.m_Debug ^= 1;
@@ -1828,39 +1873,61 @@ void CClient::Run()
 		*/
 
 		// render
-		if(g_Config.m_ClEditor)
 		{
-			if(!m_EditorActive)
+			if(g_Config.m_ClEditor)
 			{
-				GameClient()->OnActivateEditor();
-				m_EditorActive = true;
+				if(!m_EditorActive)
+				{
+					GameClient()->OnActivateEditor();
+					m_EditorActive = true;
+				}
 			}
-
-			Update();
-			m_pEditor->UpdateAndRender();
-			DebugRender();
-			m_pGraphics->Swap();
-		}
-		else
-		{
-			if(m_EditorActive)
+			else if(m_EditorActive)
 				m_EditorActive = false;
 
 			Update();
-
-			if(g_Config.m_DbgStress)
+			
+			if(!g_Config.m_GfxAsyncRender || m_pGraphics->IsIdle())
 			{
-				if((m_Frames%10) == 0)
+				m_RenderFrames++;
+
+				// update frametime
+				int64 Now = time_get();
+				m_RenderFrameTime = (Now - m_LastRenderTime) / (float)time_freq();
+				if(m_RenderFrameTime < m_RenderFrameTimeLow)
+					m_RenderFrameTimeLow = m_RenderFrameTime;
+				if(m_RenderFrameTime > m_RenderFrameTimeHigh)
+					m_RenderFrameTimeHigh = m_RenderFrameTime;
+				m_FpsGraph.Add(1.0f/m_RenderFrameTime, 1,1,1);
+
+				m_LastRenderTime = Now;
+
+				if(g_Config.m_DbgStress)
 				{
-					Render();
+					if((m_RenderFrames%10) == 0)
+					{
+						if(!m_EditorActive)
+							Render();
+						else
+						{
+							m_pEditor->UpdateAndRender();
+							DebugRender();
+						}
+						m_pGraphics->Swap();
+					}
+				}
+				else
+				{
+					if(!m_EditorActive)
+						Render();
+					else
+					{
+						m_pEditor->UpdateAndRender();
+						DebugRender();
+					}
 					m_pGraphics->Swap();
 				}
 			}
-			else
-			{
-				Render();
-				m_pGraphics->Swap();
-			}
 		}
 
 		AutoScreenshot_Cleanup();
@@ -1881,32 +1948,25 @@ void CClient::Run()
 			g_Config.m_DbgHitch = 0;
 		}
 
+		/*
 		if(ReportTime < time_get())
 		{
 			if(0 && g_Config.m_Debug)
 			{
 				dbg_msg("client/report", "fps=%.02f (%.02f %.02f) netstate=%d",
 					m_Frames/(float)(ReportInterval/time_freq()),
-					1.0f/m_FrameTimeHigh,
-					1.0f/m_FrameTimeLow,
+					1.0f/m_RenderFrameTimeHigh,
+					1.0f/m_RenderFrameTimeLow,
 					m_NetClient.State());
 			}
-			m_FrameTimeLow = 1;
-			m_FrameTimeHigh = 0;
-			m_Frames = 0;
+			m_RenderFrameTimeLow = 1;
+			m_RenderFrameTimeHigh = 0;
+			m_RenderFrames = 0;
 			ReportTime += ReportInterval;
-		}
-
-		// update frametime
-		m_FrameTime = (time_get()-FrameStartTime)/(float)time_freq();
-		if(m_FrameTime < m_FrameTimeLow)
-			m_FrameTimeLow = m_FrameTime;
-		if(m_FrameTime > m_FrameTimeHigh)
-			m_FrameTimeHigh = m_FrameTime;
+		}*/
 
+		// update local time
 		m_LocalTime = (time_get()-m_LocalStartTime)/(float)time_freq();
-
-		m_FpsGraph.Add(1.0f/m_FrameTime, 1,1,1);
 	}
 
 	GameClient()->OnShutdown();
@@ -1914,6 +1974,11 @@ void CClient::Run()
 
 	m_pGraphics->Shutdown();
 	m_pSound->Shutdown();
+
+	// shutdown SDL
+	{
+		SDL_Quit();
+	}
 }
 
 
@@ -2104,6 +2169,11 @@ void CClient::DemoRecorder_Stop()
 	m_DemoRecorder.Stop();
 }
 
+void CClient::DemoRecorder_AddDemoMarker()
+{
+	m_DemoRecorder.AddDemoMarker();
+}
+
 void CClient::Con_Record(IConsole::IResult *pResult, void *pUserData)
 {
 	CClient *pSelf = (CClient *)pUserData;
@@ -2119,6 +2189,12 @@ void CClient::Con_StopRecord(IConsole::I
 	pSelf->DemoRecorder_Stop();
 }
 
+void CClient::Con_AddDemoMarker(IConsole::IResult *pResult, void *pUserData)
+{
+	CClient *pSelf = (CClient *)pUserData;
+	pSelf->DemoRecorder_AddDemoMarker();
+}
+
 void CClient::ServerBrowserUpdate()
 {
 	m_ResortServerBrowser = true;
@@ -2154,9 +2230,10 @@ void CClient::RegisterCommands()
 	m_pConsole->Register("screenshot", "", CFGFLAG_CLIENT, Con_Screenshot, this, "Take a screenshot");
 	m_pConsole->Register("rcon", "r", CFGFLAG_CLIENT, Con_Rcon, this, "Send specified command to rcon");
 	m_pConsole->Register("rcon_auth", "s", CFGFLAG_CLIENT, Con_RconAuth, this, "Authenticate to rcon");
-	m_pConsole->Register("play", "r", CFGFLAG_CLIENT, Con_Play, this, "Play the file specified");
+	m_pConsole->Register("play", "r", CFGFLAG_CLIENT|CFGFLAG_STORE, Con_Play, this, "Play the file specified");
 	m_pConsole->Register("record", "?s", CFGFLAG_CLIENT, Con_Record, this, "Record to the file");
 	m_pConsole->Register("stoprecord", "", CFGFLAG_CLIENT, Con_StopRecord, this, "Stop recording");
+	m_pConsole->Register("add_demomarker", "", CFGFLAG_CLIENT, Con_AddDemoMarker, this, "Add demo timeline marker");
 	m_pConsole->Register("add_favorite", "s", CFGFLAG_CLIENT, Con_AddFavorite, this, "Add a server as a favorite");
 	m_pConsole->Register("remove_favorite", "s", CFGFLAG_CLIENT, Con_RemoveFavorite, this, "Remove a server from favorites");
 
@@ -2186,11 +2263,13 @@ static CClient *CreateClient()
 */
 
 #if defined(CONF_PLATFORM_MACOSX)
-extern "C" int SDL_main(int argc, const char **argv) // ignore_convention
+extern "C" int SDL_main(int argc, char **argv_) // ignore_convention
+{
+	const char **argv = const_cast<const char **>(argv_);
 #else
 int main(int argc, const char **argv) // ignore_convention
-#endif
 {
+#endif
 #if defined(CONF_FAMILY_WINDOWS)
 	for(int i = 1; i < argc; i++) // ignore_convention
 	{
@@ -2210,9 +2289,8 @@ int main(int argc, const char **argv) //
 	// create the components
 	IEngine *pEngine = CreateEngine("Teeworlds");
 	IConsole *pConsole = CreateConsole(CFGFLAG_CLIENT);
-	IStorage *pStorage = CreateStorage("Teeworlds", argc, argv); // ignore_convention
+	IStorage *pStorage = CreateStorage("Teeworlds", IStorage::STORAGETYPE_CLIENT, argc, argv); // ignore_convention
 	IConfig *pConfig = CreateConfig();
-	IEngineGraphics *pEngineGraphics = CreateEngineGraphics();
 	IEngineSound *pEngineSound = CreateEngineSound();
 	IEngineInput *pEngineInput = CreateEngineInput();
 	IEngineTextRender *pEngineTextRender = CreateEngineTextRender();
@@ -2226,9 +2304,6 @@ int main(int argc, const char **argv) //
 		RegisterFail = RegisterFail || !pKernel->RegisterInterface(pConsole);
 		RegisterFail = RegisterFail || !pKernel->RegisterInterface(pConfig);
 
-		RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineGraphics*>(pEngineGraphics)); // register graphics as both
-		RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IGraphics*>(pEngineGraphics));
-
 		RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<IEngineSound*>(pEngineSound)); // register as both
 		RegisterFail = RegisterFail || !pKernel->RegisterInterface(static_cast<ISound*>(pEngineSound));
 
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/client/client.h alien-rc4/src//engine/client/client.h
--- teeworlds-b177-r50edfd37-source/src//engine/client/client.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/client/client.h	2012-06-14 23:57:39.000000000 +0200
@@ -84,9 +84,12 @@ class CClient : public IClient, public C
 	int64 m_LocalStartTime;
 
 	int m_DebugFont;
-	float m_FrameTimeLow;
-	float m_FrameTimeHigh;
-	int m_Frames;
+	
+	int64 m_LastRenderTime;
+	float m_RenderFrameTimeLow;
+	float m_RenderFrameTimeHigh;
+	int m_RenderFrames;
+
 	NETADDR m_ServerAddress;
 	int m_WindowMustRefocus;
 	int m_SnapCrcErrors;
@@ -172,6 +175,12 @@ class CClient : public IClient, public C
 		class CHostLookup m_VersionServeraddr;
 	} m_VersionInfo;
 
+	semaphore m_GfxRenderSemaphore;
+	semaphore m_GfxStateSemaphore;
+	volatile int m_GfxState;
+	static void GraphicsThreadProxy(void *pThis) { ((CClient*)pThis)->GraphicsThread(); }
+	void GraphicsThread();
+
 public:
 	IEngine *Engine() { return m_pEngine; }
 	IEngineGraphics *Graphics() { return m_pGraphics; }
@@ -280,6 +289,7 @@ public:
 	static void Con_Play(IConsole::IResult *pResult, void *pUserData);
 	static void Con_Record(IConsole::IResult *pResult, void *pUserData);
 	static void Con_StopRecord(IConsole::IResult *pResult, void *pUserData);
+	static void Con_AddDemoMarker(IConsole::IResult *pResult, void *pUserData);
 	static void ConchainServerBrowserUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData);
 
 	void RegisterCommands();
@@ -288,6 +298,7 @@ public:
 	void DemoRecorder_Start(const char *pFilename, bool WithTimestamp);
 	void DemoRecorder_HandleAutoStart();
 	void DemoRecorder_Stop();
+	void DemoRecorder_AddDemoMarker();
 
 	void AutoScreenshot_Start();
 	void AutoScreenshot_Cleanup();
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/client/graphics.cpp alien-rc4/src//engine/client/graphics.cpp
--- teeworlds-b177-r50edfd37-source/src//engine/client/graphics.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/client/graphics.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -3,21 +3,10 @@
 
 #include <base/detect.h>
 #include <base/math.h>
+#include <base/tl/threading.h>
 
 #include "SDL.h"
-
-#ifdef CONF_FAMILY_WINDOWS
-	#define WIN32_LEAN_AND_MEAN
-	#include <windows.h>
-#endif
-
-#ifdef CONF_PLATFORM_MACOSX
-	#include <OpenGL/gl.h>
-	#include <OpenGL/glu.h>
-#else
-	#include <GL/gl.h>
-	#include <GL/glu.h>
-#endif
+#include "SDL_opengl.h"
 
 #include <base/system.h>
 #include <engine/external/pnglite/pnglite.h>
@@ -32,13 +21,6 @@
 
 #include "graphics.h"
 
-// compressed textures
-#define GL_COMPRESSED_RGB_ARB 0x84ED
-#define GL_COMPRESSED_RGBA_ARB 0x84EE
-#define GL_COMPRESSED_ALPHA_ARB 0x84E9
-
-#define TEXTURE_MAX_ANISOTROPY_EXT 0x84FE
-
 
 static CVideoMode g_aFakeModes[] = {
 	{320,240,8,8,8}, {400,300,8,8,8}, {640,480,8,8,8},
@@ -216,6 +198,18 @@ void CGraphics_OpenGL::BlendAdditive()
 	glBlendFunc(GL_SRC_ALPHA, GL_ONE);
 }
 
+void CGraphics_OpenGL::WrapNormal()
+{
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
+}
+
+void CGraphics_OpenGL::WrapClamp()
+{
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
+	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
+}
+
 int CGraphics_OpenGL::MemoryUsage() const
 {
 	return m_TextureMemoryUsage;
@@ -289,6 +283,18 @@ int CGraphics_OpenGL::UnloadTexture(int
 	return 0;
 }
 
+int CGraphics_OpenGL::LoadTextureRawSub(int TextureID, int x, int y, int Width, int Height, int Format, const void *pData)
+{
+	int Oglformat = GL_RGBA;
+	if(Format == CImageInfo::FORMAT_RGB)
+		Oglformat = GL_RGB;
+	else if(Format == CImageInfo::FORMAT_ALPHA)
+		Oglformat = GL_ALPHA;
+
+	glBindTexture(GL_TEXTURE_2D, m_aTextures[TextureID].m_Tex);
+	glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, Width, Height, Oglformat, GL_UNSIGNED_BYTE, pData);
+	return 0;
+}
 
 int CGraphics_OpenGL::LoadTextureRaw(int Width, int Height, int Format, const void *pData, int StoreFormat, int Flags)
 {
@@ -355,9 +361,19 @@ int CGraphics_OpenGL::LoadTextureRaw(int
 
 	glGenTextures(1, &m_aTextures[Tex].m_Tex);
 	glBindTexture(GL_TEXTURE_2D, m_aTextures[Tex].m_Tex);
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
-	gluBuild2DMipmaps(GL_TEXTURE_2D, StoreOglformat, Width, Height, Oglformat, GL_UNSIGNED_BYTE, pTexData);
+
+	if(Flags&TEXLOAD_NOMIPMAPS)
+	{
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+		glTexImage2D(GL_TEXTURE_2D, 0, StoreOglformat, Width, Height, 0, Oglformat, GL_UNSIGNED_BYTE, pData);
+	}
+	else
+	{
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
+		gluBuild2DMipmaps(GL_TEXTURE_2D, StoreOglformat, Width, Height, Oglformat, GL_UNSIGNED_BYTE, pTexData);
+	}
 
 	// calculate memory usage
 	{
@@ -400,6 +416,8 @@ int CGraphics_OpenGL::LoadTexture(const
 
 		ID = LoadTextureRaw(Img.m_Width, Img.m_Height, Img.m_Format, Img.m_pData, StoreFormat, Flags);
 		mem_free(Img.m_pData);
+		if(ID != m_InvalidTexture && g_Config.m_Debug)
+			dbg_msg("graphics/texture", "loaded %s", pFilename);
 		return ID;
 	}
 
@@ -702,7 +720,7 @@ void CGraphics_OpenGL::QuadsText(float x
 	QuadsEnd();
 }
 
-bool CGraphics_OpenGL::Init()
+int CGraphics_OpenGL::Init()
 {
 	m_pStorage = Kernel()->RequestInterface<IStorage>();
 	m_pConsole = Kernel()->RequestInterface<IConsole>();
@@ -738,24 +756,19 @@ bool CGraphics_OpenGL::Init()
 
 	m_InvalidTexture = LoadTextureRaw(4,4,CImageInfo::FORMAT_RGBA,aNullTextureData,CImageInfo::FORMAT_RGBA,TEXLOAD_NORESAMPLE);
 
-	return true;
+	return 0;
 }
 
 int CGraphics_SDL::TryInit()
 {
-	const SDL_VideoInfo *pInfo;
-	int Flags = SDL_OPENGL;
-
 	m_ScreenWidth = g_Config.m_GfxScreenWidth;
 	m_ScreenHeight = g_Config.m_GfxScreenHeight;
 
-	pInfo = SDL_GetVideoInfo();
-	SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
+	const SDL_VideoInfo *pInfo = SDL_GetVideoInfo();
+	SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE); // prevent stuck mouse cursor sdl-bug when loosing fullscreen focus in windows
 
 	// set flags
-	Flags = SDL_OPENGL;
-	Flags |= SDL_GL_DOUBLEBUFFER;
-	Flags |= SDL_HWPALETTE;
+	int Flags = SDL_OPENGL;
 	if(g_Config.m_DbgResizable)
 		Flags |= SDL_RESIZABLE;
 
@@ -841,7 +854,7 @@ CGraphics_SDL::CGraphics_SDL()
 	m_pScreenSurface = 0;
 }
 
-bool CGraphics_SDL::Init()
+int CGraphics_SDL::Init()
 {
 	{
 		int Systems = SDL_INIT_VIDEO;
@@ -855,7 +868,7 @@ bool CGraphics_SDL::Init()
 		if(SDL_Init(Systems) < 0)
 		{
 			dbg_msg("gfx", "unable to init SDL: %s", SDL_GetError());
-			return true;
+			return -1;
 		}
 	}
 
@@ -867,14 +880,14 @@ bool CGraphics_SDL::Init()
 	#endif
 
 	if(InitWindow() != 0)
-		return true;
+		return -1;
 
 	SDL_ShowCursor(0);
 
 	CGraphics_OpenGL::Init();
 
 	MapScreen(0,0,g_Config.m_GfxScreenWidth, g_Config.m_GfxScreenHeight);
-	return false;
+	return 0;
 }
 
 void CGraphics_SDL::Shutdown()
@@ -972,4 +985,19 @@ int CGraphics_SDL::GetVideoModes(CVideoM
 	return NumModes;
 }
 
+// syncronization
+void CGraphics_SDL::InsertSignal(semaphore *pSemaphore)
+{
+	pSemaphore->signal();
+}
+
+bool CGraphics_SDL::IsIdle()
+{
+	return true;
+}
+
+void CGraphics_SDL::WaitForIdle()
+{
+}
+
 extern IEngineGraphics *CreateEngineGraphics() { return new CGraphics_SDL(); }
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/client/graphics.h alien-rc4/src//engine/client/graphics.h
--- teeworlds-b177-r50edfd37-source/src//engine/client/graphics.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/client/graphics.h	2012-06-14 23:57:39.000000000 +0200
@@ -78,6 +78,9 @@ public:
 	virtual void BlendNormal();
 	virtual void BlendAdditive();
 
+	virtual void WrapNormal();
+	virtual void WrapClamp();
+
 	virtual int MemoryUsage() const;
 
 	virtual void MapScreen(float TopLeftX, float TopLeftY, float BottomRightX, float BottomRightY);
@@ -89,6 +92,7 @@ public:
 
 	virtual int UnloadTexture(int Index);
 	virtual int LoadTextureRaw(int Width, int Height, int Format, const void *pData, int StoreFormat, int Flags);
+	virtual int LoadTextureRawSub(int TextureID, int x, int y, int Width, int Height, int Format, const void *pData);
 
 	// simple uncompressed RGBA loaders
 	virtual int LoadTexture(const char *pFilename, int StorageType, int StoreFormat, int Flags);
@@ -117,7 +121,7 @@ public:
 	virtual void QuadsDrawFreeform(const CFreeformItem *pArray, int Num);
 	virtual void QuadsText(float x, float y, float Size, float r, float g, float b, float a, const char *pText);
 
-	virtual bool Init();
+	virtual int Init();
 };
 
 class CGraphics_SDL : public CGraphics_OpenGL
@@ -129,7 +133,7 @@ class CGraphics_SDL : public CGraphics_O
 public:
 	CGraphics_SDL();
 
-	virtual bool Init();
+	virtual int Init();
 	virtual void Shutdown();
 
 	virtual void Minimize();
@@ -143,6 +147,10 @@ public:
 
 	virtual int GetVideoModes(CVideoMode *pModes, int MaxModes);
 
+	// syncronization
+	virtual void InsertSignal(semaphore *pSemaphore);
+	virtual bool IsIdle();
+	virtual void WaitForIdle();
 };
 
 #endif
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/client/graphics_threaded.cpp alien-rc4/src//engine/client/graphics_threaded.cpp
--- teeworlds-b177-r50edfd37-source/src//engine/client/graphics_threaded.cpp	1970-01-01 01:00:00.000000000 +0100
+++ alien-rc4/src//engine/client/graphics_threaded.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -0,0 +1,905 @@
+/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
+/* If you are missing that file, acquire a complete release at teeworlds.com.                */
+
+#include <base/detect.h>
+#include <base/math.h>
+#include <base/tl/threading.h>
+
+#include <base/system.h>
+#include <engine/external/pnglite/pnglite.h>
+
+#include <engine/shared/config.h>
+#include <engine/graphics.h>
+#include <engine/storage.h>
+#include <engine/keys.h>
+#include <engine/console.h>
+
+#include <math.h> // cosf, sinf
+
+#include "graphics_threaded.h"
+
+static CVideoMode g_aFakeModes[] = {
+	{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},
+	{1280,768,8,8,8}, {1280,800,8,8,8}, {1280,960,8,8,8},
+	{1280,1024,8,8,8}, {1368,768,8,8,8}, {1400,1050,8,8,8},
+	{1440,900,8,8,8}, {1440,1050,8,8,8}, {1600,1000,8,8,8},
+	{1600,1200,8,8,8}, {1680,1050,8,8,8}, {1792,1344,8,8,8},
+	{1800,1440,8,8,8}, {1856,1392,8,8,8}, {1920,1080,8,8,8},
+	{1920,1200,8,8,8}, {1920,1440,8,8,8}, {1920,2400,8,8,8},
+	{2048,1536,8,8,8},
+
+	{320,240,5,6,5}, {400,300,5,6,5}, {640,480,5,6,5},
+	{720,400,5,6,5}, {768,576,5,6,5}, {800,600,5,6,5},
+	{1024,600,5,6,5}, {1024,768,5,6,5}, {1152,864,5,6,5},
+	{1280,768,5,6,5}, {1280,800,5,6,5}, {1280,960,5,6,5},
+	{1280,1024,5,6,5}, {1368,768,5,6,5}, {1400,1050,5,6,5},
+	{1440,900,5,6,5}, {1440,1050,5,6,5}, {1600,1000,5,6,5},
+	{1600,1200,5,6,5}, {1680,1050,5,6,5}, {1792,1344,5,6,5},
+	{1800,1440,5,6,5}, {1856,1392,5,6,5}, {1920,1080,5,6,5},
+	{1920,1200,5,6,5}, {1920,1440,5,6,5}, {1920,2400,5,6,5},
+	{2048,1536,5,6,5}
+};
+
+void CGraphics_Threaded::FlushVertices()
+{
+	if(m_NumVertices == 0)
+		return;
+
+	int NumVerts = m_NumVertices;
+	m_NumVertices = 0;
+
+	CCommandBuffer::SCommand_Render Cmd;
+	Cmd.m_State = m_State;
+
+	if(m_Drawing == DRAWING_QUADS)
+	{
+		Cmd.m_PrimType = CCommandBuffer::PRIMTYPE_QUADS;
+		Cmd.m_PrimCount = NumVerts/4;
+	}
+	else if(m_Drawing == DRAWING_LINES)
+	{
+		Cmd.m_PrimType = CCommandBuffer::PRIMTYPE_LINES;
+		Cmd.m_PrimCount = NumVerts/2;
+	}
+	else
+		return;
+
+	Cmd.m_pVertices = (CCommandBuffer::SVertex *)m_pCommandBuffer->AllocData(sizeof(CCommandBuffer::SVertex)*NumVerts);
+	if(Cmd.m_pVertices == 0x0)
+	{
+		// kick command buffer and try again
+		KickCommandBuffer();
+
+		Cmd.m_pVertices = (CCommandBuffer::SVertex *)m_pCommandBuffer->AllocData(sizeof(CCommandBuffer::SVertex)*NumVerts);
+		if(Cmd.m_pVertices == 0x0)
+		{
+			dbg_msg("graphics", "failed to allocate data for vertices");
+			return;
+		}
+	}
+
+	mem_copy(Cmd.m_pVertices, m_aVertices, sizeof(CCommandBuffer::SVertex)*NumVerts);
+	m_pCommandBuffer->AddCommand(Cmd);
+}
+
+void CGraphics_Threaded::AddVertices(int Count)
+{
+	m_NumVertices += Count;
+	if((m_NumVertices + Count) >= MAX_VERTICES)
+		FlushVertices();
+}
+
+void CGraphics_Threaded::Rotate4(const CCommandBuffer::SPoint &rCenter, CCommandBuffer::SVertex *pPoints)
+{
+	float c = cosf(m_Rotation);
+	float s = sinf(m_Rotation);
+	float x, y;
+	int i;
+
+	for(i = 0; i < 4; i++)
+	{
+		x = pPoints[i].m_Pos.x - rCenter.x;
+		y = pPoints[i].m_Pos.y - rCenter.y;
+		pPoints[i].m_Pos.x = x * c - y * s + rCenter.x;
+		pPoints[i].m_Pos.y = x * s + y * c + rCenter.y;
+	}
+}
+
+unsigned char CGraphics_Threaded::Sample(int w, int h, const unsigned char *pData, int u, int v, int Offset, int ScaleW, int ScaleH, int Bpp)
+{
+	int Value = 0;
+	for(int x = 0; x < ScaleW; x++)
+		for(int y = 0; y < ScaleH; y++)
+			Value += pData[((v+y)*w+(u+x))*Bpp+Offset];
+	return Value/(ScaleW*ScaleH);
+}
+
+unsigned char *CGraphics_Threaded::Rescale(int Width, int Height, int NewWidth, int NewHeight, int Format, const unsigned char *pData)
+{
+	unsigned char *pTmpData;
+	int ScaleW = Width/NewWidth;
+	int ScaleH = Height/NewHeight;
+
+	int Bpp = 3;
+	if(Format == CImageInfo::FORMAT_RGBA)
+		Bpp = 4;
+
+	pTmpData = (unsigned char *)mem_alloc(NewWidth*NewHeight*Bpp, 1);
+
+	int c = 0;
+	for(int y = 0; y < NewHeight; y++)
+		for(int x = 0; x < NewWidth; x++, c++)
+		{
+			pTmpData[c*Bpp] = Sample(Width, Height, pData, x*ScaleW, y*ScaleH, 0, ScaleW, ScaleH, Bpp);
+			pTmpData[c*Bpp+1] = Sample(Width, Height, pData, x*ScaleW, y*ScaleH, 1, ScaleW, ScaleH, Bpp);
+			pTmpData[c*Bpp+2] = Sample(Width, Height, pData, x*ScaleW, y*ScaleH, 2, ScaleW, ScaleH, Bpp);
+			if(Bpp == 4)
+				pTmpData[c*Bpp+3] = Sample(Width, Height, pData, x*ScaleW, y*ScaleH, 3, ScaleW, ScaleH, Bpp);
+		}
+
+	return pTmpData;
+}
+
+CGraphics_Threaded::CGraphics_Threaded()
+{
+	m_State.m_ScreenTL.x = 0;
+	m_State.m_ScreenTL.y = 0;
+	m_State.m_ScreenBR.x = 0;
+	m_State.m_ScreenBR.y = 0;
+	m_State.m_ClipEnable = false;
+	m_State.m_ClipX = 0;
+	m_State.m_ClipY = 0;
+	m_State.m_ClipW = 0;
+	m_State.m_ClipH = 0;
+	m_State.m_Texture = -1;
+	m_State.m_BlendMode = CCommandBuffer::BLEND_NONE;
+	m_State.m_WrapMode = CCommandBuffer::WRAP_REPEAT;
+
+	m_CurrentCommandBuffer = 0;
+	m_pCommandBuffer = 0x0;
+	m_apCommandBuffers[0] = 0x0;
+	m_apCommandBuffers[1] = 0x0;
+
+	m_NumVertices = 0;
+
+	m_ScreenWidth = -1;
+	m_ScreenHeight = -1;
+
+	m_Rotation = 0;
+	m_Drawing = 0;
+	m_InvalidTexture = 0;
+
+	m_TextureMemoryUsage = 0;
+
+	m_RenderEnable = true;
+	m_DoScreenshot = false;
+}
+
+void CGraphics_Threaded::ClipEnable(int x, int y, int w, int h)
+{
+	if(x < 0)
+		w += x;
+	if(y < 0)
+		h += y;
+
+	x = clamp(x, 0, ScreenWidth());
+	y = clamp(y, 0, ScreenHeight());
+	w = clamp(w, 0, ScreenWidth()-x);
+	h = clamp(h, 0, ScreenHeight()-y);
+
+	m_State.m_ClipEnable = true;
+	m_State.m_ClipX = x;
+	m_State.m_ClipY = ScreenHeight()-(y+h);
+	m_State.m_ClipW = w;
+	m_State.m_ClipH = h;
+}
+
+void CGraphics_Threaded::ClipDisable()
+{
+	m_State.m_ClipEnable = false;
+}
+
+void CGraphics_Threaded::BlendNone()
+{
+	m_State.m_BlendMode = CCommandBuffer::BLEND_NONE;
+}
+
+void CGraphics_Threaded::BlendNormal()
+{
+	m_State.m_BlendMode = CCommandBuffer::BLEND_ALPHA;
+}
+
+void CGraphics_Threaded::BlendAdditive()
+{
+	m_State.m_BlendMode = CCommandBuffer::BLEND_ADDITIVE;
+}
+
+void CGraphics_Threaded::WrapNormal()
+{
+	m_State.m_WrapMode = CCommandBuffer::WRAP_REPEAT;
+}
+
+void CGraphics_Threaded::WrapClamp()
+{
+	m_State.m_WrapMode = CCommandBuffer::WRAP_CLAMP;
+}
+
+int CGraphics_Threaded::MemoryUsage() const
+{
+	return m_TextureMemoryUsage;
+}
+
+void CGraphics_Threaded::MapScreen(float TopLeftX, float TopLeftY, float BottomRightX, float BottomRightY)
+{
+	m_State.m_ScreenTL.x = TopLeftX;
+	m_State.m_ScreenTL.y = TopLeftY;
+	m_State.m_ScreenBR.x = BottomRightX;
+	m_State.m_ScreenBR.y = BottomRightY;
+}
+
+void CGraphics_Threaded::GetScreen(float *pTopLeftX, float *pTopLeftY, float *pBottomRightX, float *pBottomRightY)
+{
+	*pTopLeftX = m_State.m_ScreenTL.x;
+	*pTopLeftY = m_State.m_ScreenTL.y;
+	*pBottomRightX = m_State.m_ScreenBR.x;
+	*pBottomRightY = m_State.m_ScreenBR.y;
+}
+
+void CGraphics_Threaded::LinesBegin()
+{
+	dbg_assert(m_Drawing == 0, "called Graphics()->LinesBegin twice");
+	m_Drawing = DRAWING_LINES;
+	SetColor(1,1,1,1);
+}
+
+void CGraphics_Threaded::LinesEnd()
+{
+	dbg_assert(m_Drawing == DRAWING_LINES, "called Graphics()->LinesEnd without begin");
+	FlushVertices();
+	m_Drawing = 0;
+}
+
+void CGraphics_Threaded::LinesDraw(const CLineItem *pArray, int Num)
+{
+	dbg_assert(m_Drawing == DRAWING_LINES, "called Graphics()->LinesDraw without begin");
+
+	for(int i = 0; i < Num; ++i)
+	{
+		m_aVertices[m_NumVertices + 2*i].m_Pos.x = pArray[i].m_X0;
+		m_aVertices[m_NumVertices + 2*i].m_Pos.y = pArray[i].m_Y0;
+		m_aVertices[m_NumVertices + 2*i].m_Tex = m_aTexture[0];
+		m_aVertices[m_NumVertices + 2*i].m_Color = m_aColor[0];
+
+		m_aVertices[m_NumVertices + 2*i + 1].m_Pos.x = pArray[i].m_X1;
+		m_aVertices[m_NumVertices + 2*i + 1].m_Pos.y = pArray[i].m_Y1;
+		m_aVertices[m_NumVertices + 2*i + 1].m_Tex = m_aTexture[1];
+		m_aVertices[m_NumVertices + 2*i + 1].m_Color = m_aColor[1];
+	}
+
+	AddVertices(2*Num);
+}
+
+int CGraphics_Threaded::UnloadTexture(int Index)
+{
+	if(Index == m_InvalidTexture)
+		return 0;
+
+	if(Index < 0)
+		return 0;
+
+	CCommandBuffer::SCommand_Texture_Destroy Cmd;
+	Cmd.m_Slot = Index;
+	m_pCommandBuffer->AddCommand(Cmd);
+
+	m_aTextures[Index].m_Next = m_FirstFreeTexture;
+	m_TextureMemoryUsage -= m_aTextures[Index].m_MemSize;
+	m_FirstFreeTexture = Index;
+	return 0;
+}
+
+static int ImageFormatToTexFormat(int Format)
+{
+	if(Format == CImageInfo::FORMAT_RGB) return CCommandBuffer::TEXFORMAT_RGB;
+	if(Format == CImageInfo::FORMAT_RGBA) return CCommandBuffer::TEXFORMAT_RGBA;
+	if(Format == CImageInfo::FORMAT_ALPHA) return CCommandBuffer::TEXFORMAT_ALPHA;
+	return CCommandBuffer::TEXFORMAT_RGBA;
+}
+
+
+int CGraphics_Threaded::LoadTextureRawSub(int TextureID, int x, int y, int Width, int Height, int Format, const void *pData)
+{
+	CCommandBuffer::SCommand_Texture_Update Cmd;
+	Cmd.m_Slot = TextureID;
+	Cmd.m_X = x;
+	Cmd.m_Y = y;
+	Cmd.m_Width = Width;
+	Cmd.m_Height = Height;
+	Cmd.m_Format = ImageFormatToTexFormat(Format);
+
+	// calculate memory usage
+	int PixelSize = 4;
+	if(Format == CImageInfo::FORMAT_RGB)
+		PixelSize = 3;
+	else if(Format == CImageInfo::FORMAT_ALPHA)
+		PixelSize = 1;
+
+	int MemSize = Width*Height*PixelSize;
+
+	// copy texture data
+	void *pTmpData = mem_alloc(MemSize, sizeof(void*));
+	mem_copy(pTmpData, pData, MemSize);
+	Cmd.m_pData = pTmpData;
+
+	//
+	m_pCommandBuffer->AddCommand(Cmd);
+	return 0;
+}
+
+int CGraphics_Threaded::LoadTextureRaw(int Width, int Height, int Format, const void *pData, int StoreFormat, int Flags)
+{
+	// don't waste memory on texture if we are stress testing
+	if(g_Config.m_DbgStress)
+		return m_InvalidTexture;
+
+	// grab texture
+	int Tex = m_FirstFreeTexture;
+	m_FirstFreeTexture = m_aTextures[Tex].m_Next;
+	m_aTextures[Tex].m_Next = -1;
+
+	CCommandBuffer::SCommand_Texture_Create Cmd;
+	Cmd.m_Slot = Tex;
+	Cmd.m_Width = Width;
+	Cmd.m_Height = Height;
+	Cmd.m_Format = ImageFormatToTexFormat(Format);
+	Cmd.m_StoreFormat = ImageFormatToTexFormat(StoreFormat);
+
+	// flags
+	Cmd.m_Flags = 0;
+	if(Flags&IGraphics::TEXLOAD_NOMIPMAPS)
+		Cmd.m_Flags |= CCommandBuffer::TEXFLAG_NOMIPMAPS;
+
+	// calculate memory usage
+	int PixelSize = 4;
+	if(Format == CImageInfo::FORMAT_RGB)
+		PixelSize = 3;
+	else if(Format == CImageInfo::FORMAT_ALPHA)
+		PixelSize = 1;
+
+	int MemSize = Width*Height*PixelSize;
+
+	// copy texture data
+	void *pTmpData = mem_alloc(MemSize, sizeof(void*));
+	mem_copy(pTmpData, pData, MemSize);
+	Cmd.m_pData = pTmpData;
+
+	//
+	m_pCommandBuffer->AddCommand(Cmd);
+
+	// calculate memory usage
+	int MemUsage = MemSize;
+	while(Width > 2 && Height > 2)
+	{
+		Width>>=1;
+		Height>>=1;
+		MemUsage += Width*Height*PixelSize;
+	}
+
+	m_TextureMemoryUsage += MemUsage;
+	//mem_free(pTmpData);
+	return Tex;
+}
+
+// simple uncompressed RGBA loaders
+int CGraphics_Threaded::LoadTexture(const char *pFilename, int StorageType, int StoreFormat, int Flags)
+{
+	int l = str_length(pFilename);
+	int ID;
+	CImageInfo Img;
+
+	if(l < 3)
+		return -1;
+	if(LoadPNG(&Img, pFilename, StorageType))
+	{
+		if (StoreFormat == CImageInfo::FORMAT_AUTO)
+			StoreFormat = Img.m_Format;
+
+		ID = LoadTextureRaw(Img.m_Width, Img.m_Height, Img.m_Format, Img.m_pData, StoreFormat, Flags);
+		mem_free(Img.m_pData);
+		if(ID != m_InvalidTexture && g_Config.m_Debug)
+			dbg_msg("graphics/texture", "loaded %s", pFilename);
+		return ID;
+	}
+
+	return m_InvalidTexture;
+}
+
+int CGraphics_Threaded::LoadPNG(CImageInfo *pImg, const char *pFilename, int StorageType)
+{
+	char aCompleteFilename[512];
+	unsigned char *pBuffer;
+	png_t Png; // ignore_convention
+
+	// open file for reading
+	png_init(0,0); // ignore_convention
+
+	IOHANDLE File = m_pStorage->OpenFile(pFilename, IOFLAG_READ, StorageType, aCompleteFilename, sizeof(aCompleteFilename));
+	if(File)
+		io_close(File);
+	else
+	{
+		dbg_msg("game/png", "failed to open file. filename='%s'", pFilename);
+		return 0;
+	}
+
+	int Error = png_open_file(&Png, aCompleteFilename); // ignore_convention
+	if(Error != PNG_NO_ERROR)
+	{
+		dbg_msg("game/png", "failed to open file. filename='%s'", aCompleteFilename);
+		if(Error != PNG_FILE_ERROR)
+			png_close_file(&Png); // ignore_convention
+		return 0;
+	}
+
+	if(Png.depth != 8 || (Png.color_type != PNG_TRUECOLOR && Png.color_type != PNG_TRUECOLOR_ALPHA)) // ignore_convention
+	{
+		dbg_msg("game/png", "invalid format. filename='%s'", aCompleteFilename);
+		png_close_file(&Png); // ignore_convention
+		return 0;
+	}
+
+	pBuffer = (unsigned char *)mem_alloc(Png.width * Png.height * Png.bpp, 1); // ignore_convention
+	png_get_data(&Png, pBuffer); // ignore_convention
+	png_close_file(&Png); // ignore_convention
+
+	pImg->m_Width = Png.width; // ignore_convention
+	pImg->m_Height = Png.height; // ignore_convention
+	if(Png.color_type == PNG_TRUECOLOR) // ignore_convention
+		pImg->m_Format = CImageInfo::FORMAT_RGB;
+	else if(Png.color_type == PNG_TRUECOLOR_ALPHA) // ignore_convention
+		pImg->m_Format = CImageInfo::FORMAT_RGBA;
+	pImg->m_pData = pBuffer;
+	return 1;
+}
+
+void CGraphics_Threaded::KickCommandBuffer()
+{
+	m_pBackend->RunBuffer(m_pCommandBuffer);
+
+	// swap buffer
+	m_CurrentCommandBuffer ^= 1;
+	m_pCommandBuffer = m_apCommandBuffers[m_CurrentCommandBuffer];
+	m_pCommandBuffer->Reset();
+}
+
+void CGraphics_Threaded::ScreenshotDirect(const char *pFilename)
+{
+	// add swap command
+	CImageInfo Image;
+	mem_zero(&Image, sizeof(Image));
+
+	CCommandBuffer::SCommand_Screenshot Cmd;
+	Cmd.m_pImage = &Image;
+	m_pCommandBuffer->AddCommand(Cmd);
+
+	// kick the buffer and wait for the result
+	KickCommandBuffer();
+	WaitForIdle();
+
+	if(Image.m_pData)
+	{
+		// find filename
+		char aWholePath[1024];
+		png_t Png; // ignore_convention
+
+		IOHANDLE File = m_pStorage->OpenFile(pFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE, aWholePath, sizeof(aWholePath));
+		if(File)
+			io_close(File);
+
+		// save png
+		char aBuf[256];
+		str_format(aBuf, sizeof(aBuf), "saved screenshot to '%s'", aWholePath);
+		m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "client", aBuf);
+		png_open_file_write(&Png, aWholePath); // ignore_convention
+		png_set_data(&Png, Image.m_Width, Image.m_Height, 8, PNG_TRUECOLOR, (unsigned char *)Image.m_pData); // ignore_convention
+		png_close_file(&Png); // ignore_convention
+
+		mem_free(Image.m_pData);
+	}
+}
+
+void CGraphics_Threaded::TextureSet(int TextureID)
+{
+	dbg_assert(m_Drawing == 0, "called Graphics()->TextureSet within begin");
+	m_State.m_Texture = TextureID;
+}
+
+void CGraphics_Threaded::Clear(float r, float g, float b)
+{
+	CCommandBuffer::SCommand_Clear Cmd;
+	Cmd.m_Color.r = r;
+	Cmd.m_Color.g = g;
+	Cmd.m_Color.b = b;
+	Cmd.m_Color.a = 0;
+	m_pCommandBuffer->AddCommand(Cmd);
+}
+
+void CGraphics_Threaded::QuadsBegin()
+{
+	dbg_assert(m_Drawing == 0, "called Graphics()->QuadsBegin twice");
+	m_Drawing = DRAWING_QUADS;
+
+	QuadsSetSubset(0,0,1,1);
+	QuadsSetRotation(0);
+	SetColor(1,1,1,1);
+}
+
+void CGraphics_Threaded::QuadsEnd()
+{
+	dbg_assert(m_Drawing == DRAWING_QUADS, "called Graphics()->QuadsEnd without begin");
+	FlushVertices();
+	m_Drawing = 0;
+}
+
+void CGraphics_Threaded::QuadsSetRotation(float Angle)
+{
+	dbg_assert(m_Drawing == DRAWING_QUADS, "called Graphics()->QuadsSetRotation without begin");
+	m_Rotation = Angle;
+}
+
+void CGraphics_Threaded::SetColorVertex(const CColorVertex *pArray, int Num)
+{
+	dbg_assert(m_Drawing != 0, "called Graphics()->SetColorVertex without begin");
+
+	for(int i = 0; i < Num; ++i)
+	{
+		m_aColor[pArray[i].m_Index].r = pArray[i].m_R;
+		m_aColor[pArray[i].m_Index].g = pArray[i].m_G;
+		m_aColor[pArray[i].m_Index].b = pArray[i].m_B;
+		m_aColor[pArray[i].m_Index].a = pArray[i].m_A;
+	}
+}
+
+void CGraphics_Threaded::SetColor(float r, float g, float b, float a)
+{
+	dbg_assert(m_Drawing != 0, "called Graphics()->SetColor without begin");
+	CColorVertex Array[4] = {
+		CColorVertex(0, r, g, b, a),
+		CColorVertex(1, r, g, b, a),
+		CColorVertex(2, r, g, b, a),
+		CColorVertex(3, r, g, b, a)};
+	SetColorVertex(Array, 4);
+}
+
+void CGraphics_Threaded::QuadsSetSubset(float TlU, float TlV, float BrU, float BrV)
+{
+	dbg_assert(m_Drawing == DRAWING_QUADS, "called Graphics()->QuadsSetSubset without begin");
+
+	m_aTexture[0].u = TlU;	m_aTexture[1].u = BrU;
+	m_aTexture[0].v = TlV;	m_aTexture[1].v = TlV;
+
+	m_aTexture[3].u = TlU;	m_aTexture[2].u = BrU;
+	m_aTexture[3].v = BrV;	m_aTexture[2].v = BrV;
+}
+
+void CGraphics_Threaded::QuadsSetSubsetFree(
+	float x0, float y0, float x1, float y1,
+	float x2, float y2, float x3, float y3)
+{
+	m_aTexture[0].u = x0; m_aTexture[0].v = y0;
+	m_aTexture[1].u = x1; m_aTexture[1].v = y1;
+	m_aTexture[2].u = x2; m_aTexture[2].v = y2;
+	m_aTexture[3].u = x3; m_aTexture[3].v = y3;
+}
+
+void CGraphics_Threaded::QuadsDraw(CQuadItem *pArray, int Num)
+{
+	for(int i = 0; i < Num; ++i)
+	{
+		pArray[i].m_X -= pArray[i].m_Width/2;
+		pArray[i].m_Y -= pArray[i].m_Height/2;
+	}
+
+	QuadsDrawTL(pArray, Num);
+}
+
+void CGraphics_Threaded::QuadsDrawTL(const CQuadItem *pArray, int Num)
+{
+	CCommandBuffer::SPoint Center;
+	Center.z = 0;
+
+	dbg_assert(m_Drawing == DRAWING_QUADS, "called Graphics()->QuadsDrawTL without begin");
+
+	for(int i = 0; i < Num; ++i)
+	{
+		m_aVertices[m_NumVertices + 4*i].m_Pos.x = pArray[i].m_X;
+		m_aVertices[m_NumVertices + 4*i].m_Pos.y = pArray[i].m_Y;
+		m_aVertices[m_NumVertices + 4*i].m_Tex = m_aTexture[0];
+		m_aVertices[m_NumVertices + 4*i].m_Color = m_aColor[0];
+
+		m_aVertices[m_NumVertices + 4*i + 1].m_Pos.x = pArray[i].m_X + pArray[i].m_Width;
+		m_aVertices[m_NumVertices + 4*i + 1].m_Pos.y = pArray[i].m_Y;
+		m_aVertices[m_NumVertices + 4*i + 1].m_Tex = m_aTexture[1];
+		m_aVertices[m_NumVertices + 4*i + 1].m_Color = m_aColor[1];
+
+		m_aVertices[m_NumVertices + 4*i + 2].m_Pos.x = pArray[i].m_X + pArray[i].m_Width;
+		m_aVertices[m_NumVertices + 4*i + 2].m_Pos.y = pArray[i].m_Y + pArray[i].m_Height;
+		m_aVertices[m_NumVertices + 4*i + 2].m_Tex = m_aTexture[2];
+		m_aVertices[m_NumVertices + 4*i + 2].m_Color = m_aColor[2];
+
+		m_aVertices[m_NumVertices + 4*i + 3].m_Pos.x = pArray[i].m_X;
+		m_aVertices[m_NumVertices + 4*i + 3].m_Pos.y = pArray[i].m_Y + pArray[i].m_Height;
+		m_aVertices[m_NumVertices + 4*i + 3].m_Tex = m_aTexture[3];
+		m_aVertices[m_NumVertices + 4*i + 3].m_Color = m_aColor[3];
+
+		if(m_Rotation != 0)
+		{
+			Center.x = pArray[i].m_X + pArray[i].m_Width/2;
+			Center.y = pArray[i].m_Y + pArray[i].m_Height/2;
+
+			Rotate4(Center, &m_aVertices[m_NumVertices + 4*i]);
+		}
+	}
+
+	AddVertices(4*Num);
+}
+
+void CGraphics_Threaded::QuadsDrawFreeform(const CFreeformItem *pArray, int Num)
+{
+	dbg_assert(m_Drawing == DRAWING_QUADS, "called Graphics()->QuadsDrawFreeform without begin");
+
+	for(int i = 0; i < Num; ++i)
+	{
+		m_aVertices[m_NumVertices + 4*i].m_Pos.x = pArray[i].m_X0;
+		m_aVertices[m_NumVertices + 4*i].m_Pos.y = pArray[i].m_Y0;
+		m_aVertices[m_NumVertices + 4*i].m_Tex = m_aTexture[0];
+		m_aVertices[m_NumVertices + 4*i].m_Color = m_aColor[0];
+
+		m_aVertices[m_NumVertices + 4*i + 1].m_Pos.x = pArray[i].m_X1;
+		m_aVertices[m_NumVertices + 4*i + 1].m_Pos.y = pArray[i].m_Y1;
+		m_aVertices[m_NumVertices + 4*i + 1].m_Tex = m_aTexture[1];
+		m_aVertices[m_NumVertices + 4*i + 1].m_Color = m_aColor[1];
+
+		m_aVertices[m_NumVertices + 4*i + 2].m_Pos.x = pArray[i].m_X3;
+		m_aVertices[m_NumVertices + 4*i + 2].m_Pos.y = pArray[i].m_Y3;
+		m_aVertices[m_NumVertices + 4*i + 2].m_Tex = m_aTexture[3];
+		m_aVertices[m_NumVertices + 4*i + 2].m_Color = m_aColor[3];
+
+		m_aVertices[m_NumVertices + 4*i + 3].m_Pos.x = pArray[i].m_X2;
+		m_aVertices[m_NumVertices + 4*i + 3].m_Pos.y = pArray[i].m_Y2;
+		m_aVertices[m_NumVertices + 4*i + 3].m_Tex = m_aTexture[2];
+		m_aVertices[m_NumVertices + 4*i + 3].m_Color = m_aColor[2];
+	}
+
+	AddVertices(4*Num);
+}
+
+void CGraphics_Threaded::QuadsText(float x, float y, float Size, float r, float g, float b, float a, const char *pText)
+{
+	float StartX = x;
+
+	QuadsBegin();
+	SetColor(r,g,b,a);
+
+	while(*pText)
+	{
+		char c = *pText;
+		pText++;
+
+		if(c == '\n')
+		{
+			x = StartX;
+			y += Size;
+		}
+		else
+		{
+			QuadsSetSubset(
+				(c%16)/16.0f,
+				(c/16)/16.0f,
+				(c%16)/16.0f+1.0f/16.0f,
+				(c/16)/16.0f+1.0f/16.0f);
+
+			CQuadItem QuadItem(x, y, Size, Size);
+			QuadsDrawTL(&QuadItem, 1);
+			x += Size/2;
+		}
+	}
+
+	QuadsEnd();
+}
+
+int CGraphics_Threaded::IssueInit()
+{
+	int Flags = 0;
+	if(g_Config.m_GfxFullscreen) Flags |= IGraphicsBackend::INITFLAG_FULLSCREEN;
+	if(g_Config.m_GfxVsync) Flags |= IGraphicsBackend::INITFLAG_VSYNC;
+	if(g_Config.m_DbgResizable) Flags |= IGraphicsBackend::INITFLAG_RESIZABLE;
+
+	return m_pBackend->Init("Teeworlds", g_Config.m_GfxScreenWidth, g_Config.m_GfxScreenHeight, g_Config.m_GfxFsaaSamples, Flags);
+}
+
+int CGraphics_Threaded::InitWindow()
+{
+	if(IssueInit() == 0)
+		return 0;
+
+	// try disabling fsaa
+	while(g_Config.m_GfxFsaaSamples)
+	{
+		g_Config.m_GfxFsaaSamples--;
+
+		if(g_Config.m_GfxFsaaSamples)
+			dbg_msg("gfx", "lowering FSAA to %d and trying again", g_Config.m_GfxFsaaSamples);
+		else
+			dbg_msg("gfx", "disabling FSAA and trying again");
+
+		if(IssueInit() == 0)
+			return 0;
+	}
+
+	// try lowering the resolution
+	if(g_Config.m_GfxScreenWidth != 640 || g_Config.m_GfxScreenHeight != 480)
+	{
+		dbg_msg("gfx", "setting resolution to 640x480 and trying again");
+		g_Config.m_GfxScreenWidth = 640;
+		g_Config.m_GfxScreenHeight = 480;
+
+		if(IssueInit() == 0)
+			return 0;
+	}
+
+	dbg_msg("gfx", "out of ideas. failed to init graphics");
+
+	return -1;
+}
+
+int CGraphics_Threaded::Init()
+{
+	// fetch pointers
+	m_pStorage = Kernel()->RequestInterface<IStorage>();
+	m_pConsole = Kernel()->RequestInterface<IConsole>();
+
+	// Set all z to -5.0f
+	for(int i = 0; i < MAX_VERTICES; i++)
+		m_aVertices[i].m_Pos.z = -5.0f;
+
+	// init textures
+	m_FirstFreeTexture = 0;
+	for(int i = 0; i < MAX_TEXTURES; i++)
+		m_aTextures[i].m_Next = i+1;
+	m_aTextures[MAX_TEXTURES-1].m_Next = -1;
+
+	m_pBackend = CreateGraphicsBackend();
+	if(InitWindow() != 0)
+		return -1;
+
+	// fetch final resolusion
+	m_ScreenWidth = g_Config.m_GfxScreenWidth;
+	m_ScreenHeight = g_Config.m_GfxScreenHeight;
+
+	// create command buffers
+	for(int i = 0; i < NUM_CMDBUFFERS; i++)
+		m_apCommandBuffers[i] = new CCommandBuffer(128*1024, 2*1024*1024);
+	m_pCommandBuffer = m_apCommandBuffers[0];
+
+	// create null texture, will get id=0
+	static const unsigned char aNullTextureData[] = {
+		0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, 0x00,0xff,0x00,0xff, 0x00,0xff,0x00,0xff,
+		0xff,0x00,0x00,0xff, 0xff,0x00,0x00,0xff, 0x00,0xff,0x00,0xff, 0x00,0xff,0x00,0xff,
+		0x00,0x00,0xff,0xff, 0x00,0x00,0xff,0xff, 0xff,0xff,0x00,0xff, 0xff,0xff,0x00,0xff,
+		0x00,0x00,0xff,0xff, 0x00,0x00,0xff,0xff, 0xff,0xff,0x00,0xff, 0xff,0xff,0x00,0xff,
+	};
+
+	m_InvalidTexture = LoadTextureRaw(4,4,CImageInfo::FORMAT_RGBA,aNullTextureData,CImageInfo::FORMAT_RGBA,TEXLOAD_NORESAMPLE);
+	return 0;
+}
+
+void CGraphics_Threaded::Shutdown()
+{
+	// shutdown the backend
+	m_pBackend->Shutdown();
+	delete m_pBackend;
+	m_pBackend = 0x0;
+
+	// delete the command buffers
+	for(int i = 0; i < NUM_CMDBUFFERS; i++)
+		delete m_apCommandBuffers[i];
+}
+
+void CGraphics_Threaded::Minimize()
+{
+	m_pBackend->Minimize();
+}
+
+void CGraphics_Threaded::Maximize()
+{
+	// TODO: SDL
+	m_pBackend->Maximize();
+}
+
+int CGraphics_Threaded::WindowActive()
+{
+	return m_pBackend->WindowActive();
+}
+
+int CGraphics_Threaded::WindowOpen()
+{
+	return m_pBackend->WindowOpen();
+
+}
+
+void CGraphics_Threaded::TakeScreenshot(const char *pFilename)
+{
+	// TODO: screenshot support
+	char aDate[20];
+	str_timestamp(aDate, sizeof(aDate));
+	str_format(m_aScreenshotName, sizeof(m_aScreenshotName), "screenshots/%s_%s.png", pFilename?pFilename:"screenshot", aDate);
+	m_DoScreenshot = true;
+}
+
+void CGraphics_Threaded::Swap()
+{
+	// TODO: screenshot support
+	if(m_DoScreenshot)
+	{
+		ScreenshotDirect(m_aScreenshotName);
+		m_DoScreenshot = false;
+	}
+
+	// add swap command
+	CCommandBuffer::SCommand_Swap Cmd;
+	Cmd.m_Finish = g_Config.m_GfxFinish;
+	m_pCommandBuffer->AddCommand(Cmd);
+
+	// kick the command buffer
+	KickCommandBuffer();
+}
+
+// syncronization
+void CGraphics_Threaded::InsertSignal(semaphore *pSemaphore)
+{
+	CCommandBuffer::SCommand_Signal Cmd;
+	Cmd.m_pSemaphore = pSemaphore;
+	m_pCommandBuffer->AddCommand(Cmd);
+}
+
+bool CGraphics_Threaded::IsIdle()
+{
+	return m_pBackend->IsIdle();
+}
+
+void CGraphics_Threaded::WaitForIdle()
+{
+	m_pBackend->WaitForIdle();
+}
+
+int CGraphics_Threaded::GetVideoModes(CVideoMode *pModes, int MaxModes)
+{
+	if(g_Config.m_GfxDisplayAllModes)
+	{
+		int Count = sizeof(g_aFakeModes)/sizeof(CVideoMode);
+		mem_copy(pModes, g_aFakeModes, sizeof(g_aFakeModes));
+		if(MaxModes < Count)
+			Count = MaxModes;
+		return Count;
+	}
+
+	// add videomodes command
+	CImageInfo Image;
+	mem_zero(&Image, sizeof(Image));
+
+	int NumModes = 0;
+	CCommandBuffer::SCommand_VideoModes Cmd;
+	Cmd.m_pModes = pModes;
+	Cmd.m_MaxModes = MaxModes;
+	Cmd.m_pNumModes = &NumModes;
+	m_pCommandBuffer->AddCommand(Cmd);
+
+	// kick the buffer and wait for the result and return it
+	KickCommandBuffer();
+	WaitForIdle();
+	return NumModes;
+}
+
+extern IEngineGraphics *CreateEngineGraphicsThreaded() { return new CGraphics_Threaded(); }
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/client/graphics_threaded.h alien-rc4/src//engine/client/graphics_threaded.h
--- teeworlds-b177-r50edfd37-source/src//engine/client/graphics_threaded.h	1970-01-01 01:00:00.000000000 +0100
+++ alien-rc4/src//engine/client/graphics_threaded.h	2012-06-14 23:57:39.000000000 +0200
@@ -0,0 +1,453 @@
+#pragma once
+
+#include <engine/graphics.h>
+
+class CCommandBuffer
+{
+	class CBuffer
+	{
+		unsigned char *m_pData;
+		unsigned m_Size;
+		unsigned m_Used;
+	public:
+		CBuffer(unsigned BufferSize)
+		{
+			m_Size = BufferSize;
+			m_pData = new unsigned char[m_Size];
+			m_Used = 0;
+		}
+
+		~CBuffer()
+		{
+			delete [] m_pData;
+			m_pData = 0x0;
+			m_Used = 0;
+			m_Size = 0;
+		}
+
+		void Reset()
+		{
+			m_Used = 0;
+		}
+
+		void *Alloc(unsigned Requested)
+		{
+			if(Requested + m_Used > m_Size)
+				return 0;
+			void *pPtr = &m_pData[m_Used];
+			m_Used += Requested;
+			return pPtr;
+		}
+
+		unsigned char *DataPtr() { return m_pData; }
+		unsigned DataSize() { return m_Size; }
+		unsigned DataUsed() { return m_Used; }
+	};
+
+public:
+	CBuffer m_CmdBuffer;
+	CBuffer m_DataBuffer;
+
+	enum
+	{
+		MAX_TEXTURES=1024*4,
+	};
+
+	enum
+	{
+		// commadn groups
+		CMDGROUP_CORE = 0, // commands that everyone has to implement
+		CMDGROUP_PLATFORM = 10000, // commands specific to a platform
+
+		//
+		CMD_NOP = CMDGROUP_CORE,
+
+		//
+		CMD_RUNBUFFER,
+
+		// syncronization
+		CMD_SIGNAL,
+
+		// texture commands
+		CMD_TEXTURE_CREATE,
+		CMD_TEXTURE_DESTROY,
+		CMD_TEXTURE_UPDATE,
+
+		// rendering
+		CMD_CLEAR,
+		CMD_RENDER,
+
+		// swap
+		CMD_SWAP,
+
+		// misc
+		CMD_SCREENSHOT,
+		CMD_VIDEOMODES,
+
+	};
+
+	enum
+	{
+		TEXFORMAT_INVALID = 0,
+		TEXFORMAT_RGB,
+		TEXFORMAT_RGBA,
+		TEXFORMAT_ALPHA,
+
+		TEXFLAG_NOMIPMAPS = 1,
+	};
+
+	enum
+	{
+		INITFLAG_FULLSCREEN = 1,
+		INITFLAG_VSYNC = 2,
+		INITFLAG_RESIZABLE = 4,
+	};
+
+	enum
+	{
+		//
+		PRIMTYPE_INVALID = 0,
+		PRIMTYPE_LINES,	
+		PRIMTYPE_QUADS,
+	};
+
+	enum
+	{
+		BLEND_NONE = 0,
+		BLEND_ALPHA,
+		BLEND_ADDITIVE,
+	};
+
+	enum
+	{
+		WRAP_REPEAT = 0,
+		WRAP_CLAMP,
+	};
+
+	struct SPoint { float x, y, z; };
+	struct STexCoord { float u, v; };
+	struct SColor { float r, g, b, a; };
+
+	struct SVertex
+	{
+		SPoint m_Pos;
+		STexCoord m_Tex;
+		SColor m_Color;
+	};
+
+	struct SCommand
+	{
+	public:
+		SCommand(unsigned Cmd) : m_Cmd(Cmd), m_Size(0) {}
+		unsigned m_Cmd;
+		unsigned m_Size;
+	};
+
+	struct SState
+	{
+		int m_BlendMode;
+		int m_WrapMode;
+		int m_Texture;
+		SPoint m_ScreenTL;
+		SPoint m_ScreenBR;
+
+		// clip
+		bool m_ClipEnable;
+		int m_ClipX;
+		int m_ClipY;
+		int m_ClipW;
+		int m_ClipH;
+	};
+		
+	struct SCommand_Clear : public SCommand
+	{
+		SCommand_Clear() : SCommand(CMD_CLEAR) {}
+		SColor m_Color;
+	};
+		
+	struct SCommand_Signal : public SCommand
+	{
+		SCommand_Signal() : SCommand(CMD_SIGNAL) {}
+		semaphore *m_pSemaphore;
+	};
+
+	struct SCommand_RunBuffer : public SCommand
+	{
+		SCommand_RunBuffer() : SCommand(CMD_RUNBUFFER) {}
+		CCommandBuffer *m_pOtherBuffer;
+	};
+
+	struct SCommand_Render : public SCommand
+	{
+		SCommand_Render() : SCommand(CMD_RENDER) {}
+		SState m_State;
+		unsigned m_PrimType;
+		unsigned m_PrimCount;
+		SVertex *m_pVertices; // you should use the command buffer data to allocate vertices for this command
+	};
+
+	struct SCommand_Screenshot : public SCommand
+	{
+		SCommand_Screenshot() : SCommand(CMD_SCREENSHOT) {}
+		CImageInfo *m_pImage; // processor will fill this out, the one who adds this command must free the data as well
+	};
+
+	struct SCommand_VideoModes : public SCommand
+	{
+		SCommand_VideoModes() : SCommand(CMD_VIDEOMODES) {}
+
+		CVideoMode *m_pModes; // processor will fill this in
+		int m_MaxModes; // maximum of modes the processor can write to the m_pModes
+		int *m_pNumModes; // processor will write to this pointer
+	};
+
+	struct SCommand_Swap : public SCommand
+	{
+		SCommand_Swap() : SCommand(CMD_SWAP) {}
+
+		int m_Finish;
+	};
+
+	struct SCommand_Texture_Create : public SCommand
+	{
+		SCommand_Texture_Create() : SCommand(CMD_TEXTURE_CREATE) {}
+
+		// texture information
+		int m_Slot;
+
+		int m_Width;
+		int m_Height;
+		int m_Format;
+		int m_StoreFormat;
+		int m_Flags;
+		void *m_pData; // will be freed by the command processor
+	};
+
+	struct SCommand_Texture_Update : public SCommand
+	{
+		SCommand_Texture_Update() : SCommand(CMD_TEXTURE_UPDATE) {}
+
+		// texture information
+		int m_Slot;
+
+		int m_X;
+		int m_Y;
+		int m_Width;
+		int m_Height;
+		int m_Format;
+		void *m_pData; // will be freed by the command processor
+	};
+
+
+	struct SCommand_Texture_Destroy : public SCommand
+	{
+		SCommand_Texture_Destroy() : SCommand(CMD_TEXTURE_DESTROY) {}
+
+		// texture information
+		int m_Slot;
+	};
+	
+	//
+	CCommandBuffer(unsigned CmdBufferSize, unsigned DataBufferSize)
+	: m_CmdBuffer(CmdBufferSize), m_DataBuffer(DataBufferSize)
+	{
+	}
+
+	void *AllocData(unsigned WantedSize)
+	{
+		return m_DataBuffer.Alloc(WantedSize);
+	}
+
+	template<class T>
+	bool AddCommand(const T &Command)
+	{
+		// make sure that we don't do something stupid like ->AddCommand(&Cmd);
+		(void)static_cast<const SCommand *>(&Command);
+
+		// allocate and copy the command into the buffer
+		SCommand *pCmd = (SCommand *)m_CmdBuffer.Alloc(sizeof(Command));
+		if(!pCmd)
+			return false;
+		mem_copy(pCmd, &Command, sizeof(Command));
+		pCmd->m_Size = sizeof(Command);
+		return true;
+	}
+
+	SCommand *GetCommand(unsigned *pIndex)
+	{
+		if(*pIndex >= m_CmdBuffer.DataUsed())
+			return NULL;
+
+		SCommand *pCommand = (SCommand *)&m_CmdBuffer.DataPtr()[*pIndex];
+		*pIndex += pCommand->m_Size;
+		return pCommand;
+	}
+
+	void Reset()
+	{
+		m_CmdBuffer.Reset();
+		m_DataBuffer.Reset();
+	}
+};
+
+// interface for the graphics backend
+// all these functions are called on the main thread
+class IGraphicsBackend
+{
+public:
+	enum
+	{
+		INITFLAG_FULLSCREEN = 1,
+		INITFLAG_VSYNC = 2,
+		INITFLAG_RESIZABLE = 4,
+	};
+
+	virtual int Init(const char *pName, int Width, int Height, int FsaaSamples, int Flags) = 0;
+	virtual int Shutdown() = 0;
+
+	virtual void Minimize() = 0;
+	virtual void Maximize() = 0;
+	virtual int WindowActive() = 0;
+	virtual int WindowOpen() = 0;
+
+	virtual void RunBuffer(CCommandBuffer *pBuffer) = 0;
+	virtual bool IsIdle() const = 0;
+	virtual void WaitForIdle() = 0;
+};
+
+class CGraphics_Threaded : public IEngineGraphics
+{
+	enum
+	{
+		NUM_CMDBUFFERS = 2,
+
+		MAX_VERTICES = 32*1024,
+		MAX_TEXTURES = 1024*4,
+		
+		DRAWING_QUADS=1,
+		DRAWING_LINES=2
+	};
+
+	CCommandBuffer::SState m_State;
+	IGraphicsBackend *m_pBackend;
+
+	CCommandBuffer *m_apCommandBuffers[NUM_CMDBUFFERS];
+	CCommandBuffer *m_pCommandBuffer;
+	unsigned m_CurrentCommandBuffer;
+
+	//
+	class IStorage *m_pStorage;
+	class IConsole *m_pConsole;
+
+	CCommandBuffer::SVertex m_aVertices[MAX_VERTICES];
+	int m_NumVertices;
+
+	CCommandBuffer::SColor m_aColor[4];
+	CCommandBuffer::STexCoord m_aTexture[4];
+
+	bool m_RenderEnable;
+
+	float m_Rotation;
+	int m_Drawing;
+	bool m_DoScreenshot;
+	char m_aScreenshotName[128];
+
+	int m_InvalidTexture;
+
+	struct CTexture
+	{
+		int m_State;
+		int m_MemSize;
+		int m_Flags;
+		int m_Next;
+	};
+
+	CTexture m_aTextures[MAX_TEXTURES];
+	int m_FirstFreeTexture;
+	int m_TextureMemoryUsage;
+
+	void FlushVertices();
+	void AddVertices(int Count);
+	void Rotate4(const CCommandBuffer::SPoint &rCenter, CCommandBuffer::SVertex *pPoints);
+
+	static unsigned char Sample(int w, int h, const unsigned char *pData, int u, int v, int Offset, int ScaleW, int ScaleH, int Bpp);
+	static unsigned char *Rescale(int Width, int Height, int NewWidth, int NewHeight, int Format, const unsigned char *pData);
+
+	void KickCommandBuffer();
+
+	int IssueInit();
+	int InitWindow();
+public:
+	CGraphics_Threaded();
+
+	virtual void ClipEnable(int x, int y, int w, int h);
+	virtual void ClipDisable();
+
+	virtual void BlendNone();
+	virtual void BlendNormal();
+	virtual void BlendAdditive();
+
+	virtual void WrapNormal();
+	virtual void WrapClamp();
+
+	virtual int MemoryUsage() const;
+
+	virtual void MapScreen(float TopLeftX, float TopLeftY, float BottomRightX, float BottomRightY);
+	virtual void GetScreen(float *pTopLeftX, float *pTopLeftY, float *pBottomRightX, float *pBottomRightY);
+
+	virtual void LinesBegin();
+	virtual void LinesEnd();
+	virtual void LinesDraw(const CLineItem *pArray, int Num);
+
+	virtual int UnloadTexture(int Index);
+	virtual int LoadTextureRaw(int Width, int Height, int Format, const void *pData, int StoreFormat, int Flags);
+	virtual int LoadTextureRawSub(int TextureID, int x, int y, int Width, int Height, int Format, const void *pData);
+
+	// simple uncompressed RGBA loaders
+	virtual int LoadTexture(const char *pFilename, int StorageType, int StoreFormat, int Flags);
+	virtual int LoadPNG(CImageInfo *pImg, const char *pFilename, int StorageType);
+
+	void ScreenshotDirect(const char *pFilename);
+
+	virtual void TextureSet(int TextureID);
+
+	virtual void Clear(float r, float g, float b);
+
+	virtual void QuadsBegin();
+	virtual void QuadsEnd();
+	virtual void QuadsSetRotation(float Angle);
+
+	virtual void SetColorVertex(const CColorVertex *pArray, int Num);
+	virtual void SetColor(float r, float g, float b, float a);
+
+	virtual void QuadsSetSubset(float TlU, float TlV, float BrU, float BrV);
+	virtual void QuadsSetSubsetFree(
+		float x0, float y0, float x1, float y1,
+		float x2, float y2, float x3, float y3);
+
+	virtual void QuadsDraw(CQuadItem *pArray, int Num);
+	virtual void QuadsDrawTL(const CQuadItem *pArray, int Num);
+	virtual void QuadsDrawFreeform(const CFreeformItem *pArray, int Num);
+	virtual void QuadsText(float x, float y, float Size, float r, float g, float b, float a, const char *pText);
+
+	virtual void Minimize();
+	virtual void Maximize();
+
+	virtual int WindowActive();
+	virtual int WindowOpen();
+
+	virtual int Init();
+	virtual void Shutdown();
+
+	virtual void TakeScreenshot(const char *pFilename);
+	virtual void Swap();
+
+	virtual int GetVideoModes(CVideoMode *pModes, int MaxModes);
+
+	// syncronization
+	virtual void InsertSignal(semaphore *pSemaphore);
+	virtual bool IsIdle();
+	virtual void WaitForIdle();
+};
+
+extern IGraphicsBackend *CreateGraphicsBackend();
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/client/serverbrowser.cpp alien-rc4/src//engine/client/serverbrowser.cpp
--- teeworlds-b177-r50edfd37-source/src//engine/client/serverbrowser.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/client/serverbrowser.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -1,6 +1,6 @@
 /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
 /* If you are missing that file, acquire a complete release at teeworlds.com.                */
-#include <algorithm> // sort
+#include <algorithm> // sort  TODO: remove this
 
 #include <base/math.h>
 #include <base/system.h>
@@ -26,7 +26,7 @@ class SortWrap
 	CServerBrowser *m_pThis;
 public:
 	SortWrap(CServerBrowser *t, SortFunc f) : m_pfnSort(f), m_pThis(t) {}
-	bool operator()(int a, int b) { return (m_pThis->*m_pfnSort)(a, b); }
+	bool operator()(int a, int b) { return (g_Config.m_BrSortOrder ? (m_pThis->*m_pfnSort)(b, a) : (m_pThis->*m_pfnSort)(a, b)); }
 };
 
 CServerBrowser::CServerBrowser()
@@ -283,27 +283,16 @@ void CServerBrowser::Sort()
 
 	// sort
 	if(g_Config.m_BrSort == IServerBrowser::SORT_NAME)
-		std::sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareName));
+		std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareName));
 	else if(g_Config.m_BrSort == IServerBrowser::SORT_PING)
-		std::sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortComparePing));
+		std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortComparePing));
 	else if(g_Config.m_BrSort == IServerBrowser::SORT_MAP)
-		std::sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareMap));
+		std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareMap));
 	else if(g_Config.m_BrSort == IServerBrowser::SORT_NUMPLAYERS)
-		std::sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this,
+		std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this,
 					g_Config.m_BrFilterSpectators ? &CServerBrowser::SortCompareNumPlayers : &CServerBrowser::SortCompareNumClients));
 	else if(g_Config.m_BrSort == IServerBrowser::SORT_GAMETYPE)
-		std::sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareGametype));
-
-	// invert the list if requested
-	if(g_Config.m_BrSortOrder)
-	{
-		for(i = 0; i < m_NumSortedServers/2; i++)
-		{
-			int Temp = m_pSortedServerlist[i];
-			m_pSortedServerlist[i] = m_pSortedServerlist[m_NumSortedServers-i-1];
-			m_pSortedServerlist[m_NumSortedServers-i-1] = Temp;
-		}
-	}
+		std::stable_sort(m_pSortedServerlist, m_pSortedServerlist+m_NumSortedServers, SortWrap(this, &CServerBrowser::SortCompareGametype));
 
 	// set indexes
 	for(i = 0; i < m_NumSortedServers; i++)
@@ -381,7 +370,6 @@ void CServerBrowser::SetInfo(CServerEntr
 	}*/
 
 	pEntry->m_GotInfo = 1;
-	Sort();
 }
 
 CServerBrowser::CServerEntry *CServerBrowser::Add(const NETADDR &Addr)
@@ -399,7 +387,7 @@ CServerBrowser::CServerEntry *CServerBro
 	pEntry->m_Info.m_NetAddr = Addr;
 
 	pEntry->m_Info.m_Latency = 999;
-	net_addr_str(&Addr, pEntry->m_Info.m_aAddress, sizeof(pEntry->m_Info.m_aAddress));
+	net_addr_str(&Addr, pEntry->m_Info.m_aAddress, sizeof(pEntry->m_Info.m_aAddress), true);
 	str_copy(pEntry->m_Info.m_aName, pEntry->m_Info.m_aAddress, sizeof(pEntry->m_Info.m_aName));
 
 	// check if it's a favorite
@@ -539,7 +527,7 @@ void CServerBrowser::RequestImpl(const N
 	if(g_Config.m_Debug)
 	{
 		char aAddrStr[NETADDR_MAXSTRSIZE];
-		net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr));
+		net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr), true);
 		char aBuf[256];
 		str_format(aBuf, sizeof(aBuf),"requesting server info from %s", aAddrStr);
 		m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client_srvbrowse", aBuf);
@@ -680,7 +668,7 @@ void CServerBrowser::AddFavorite(const N
 	if(g_Config.m_Debug)
 	{
 		char aAddrStr[NETADDR_MAXSTRSIZE];
-		net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr));
+		net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr), true);
 		char aBuf[256];
 		str_format(aBuf, sizeof(aBuf), "added fav, %s", aAddrStr);
 		m_pConsole->Print(IConsole::OUTPUT_LEVEL_DEBUG, "client_srvbrowse", aBuf);
@@ -734,12 +722,11 @@ void CServerBrowser::ConfigSaveCallback(
 {
 	CServerBrowser *pSelf = (CServerBrowser *)pUserData;
 
-	int i;
 	char aAddrStr[128];
 	char aBuffer[256];
-	for(i = 0; i < pSelf->m_NumFavoriteServers; i++)
+	for(int i = 0; i < pSelf->m_NumFavoriteServers; i++)
 	{
-		net_addr_str(&pSelf->m_aFavoriteServers[i], aAddrStr, sizeof(aAddrStr));
+		net_addr_str(&pSelf->m_aFavoriteServers[i], aAddrStr, sizeof(aAddrStr), true);
 		str_format(aBuffer, sizeof(aBuffer), "add_favorite %s", aAddrStr);
 		pConfig->WriteLine(aBuffer);
 	}
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/client/sound.cpp alien-rc4/src//engine/client/sound.cpp
--- teeworlds-b177-r50edfd37-source/src//engine/client/sound.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/client/sound.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -1,8 +1,11 @@
 /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
 /* If you are missing that file, acquire a complete release at teeworlds.com.                */
+#include <base/math.h>
 #include <base/system.h>
+
 #include <engine/graphics.h>
 #include <engine/storage.h>
+
 #include <engine/shared/config.h>
 
 #include "SDL.h"
@@ -19,8 +22,6 @@ enum
 	NUM_SAMPLES = 512,
 	NUM_VOICES = 64,
 	NUM_CHANNELS = 16,
-	
-	MAX_FRAMES = 1024
 };
 
 struct CSample
@@ -63,7 +64,8 @@ static int m_MixingRate = 48000;
 static volatile int m_SoundVolume = 100;
 
 static int m_NextVoice = 0;
-
+static int *m_pMixBuffer = 0;	// buffer only used by the thread callback function
+static unsigned m_MaxFrames = 0;
 
 // TODO: there should be a faster way todo this
 static short Int2Short(int i)
@@ -84,26 +86,27 @@ static int IntAbs(int i)
 
 static void Mix(short *pFinalOut, unsigned Frames)
 {
-	int aMixBuffer[MAX_FRAMES*2] = {0};
 	int MasterVol;
+	mem_zero(m_pMixBuffer, m_MaxFrames*2*sizeof(int));
+	Frames = min(Frames, m_MaxFrames);
 
 	// aquire lock while we are mixing
 	lock_wait(m_SoundLock);
-	
+
 	MasterVol = m_SoundVolume;
-	
+
 	for(unsigned i = 0; i < NUM_VOICES; i++)
 	{
 		if(m_aVoices[i].m_pSample)
 		{
 			// mix voice
 			CVoice *v = &m_aVoices[i];
-			int *pOut = aMixBuffer;
+			int *pOut = m_pMixBuffer;
 
 			int Step = v->m_pSample->m_Channels; // setup input sources
 			short *pInL = &v->m_pSample->m_pData[v->m_Tick*Step];
 			short *pInR = &v->m_pSample->m_pData[v->m_Tick*Step+1];
-			
+
 			unsigned End = v->m_pSample->m_NumFrames-v->m_Tick;
 
 			int Rvol = v->m_pChannel->m_Vol;
@@ -112,7 +115,7 @@ static void Mix(short *pFinalOut, unsign
 			// make sure that we don't go outside the sound data
 			if(Frames < End)
 				End = Frames;
-			
+
 			// check if we have a mono sound
 			if(v->m_pSample->m_Channels == 1)
 				pInR = pInL;
@@ -126,14 +129,14 @@ static void Mix(short *pFinalOut, unsign
 				int dy = v->m_Y - m_CenterY;
 				int Dist = (int)sqrtf((float)dx*dx+dy*dy); // float here. nasty
 				int p = IntAbs(dx);
-				if(Dist < Range)
+				if(Dist >= 0 && Dist < Range)
 				{
 					// panning
 					if(dx > 0)
 						Lvol = ((Range-p)*Lvol)/Range;
 					else
 						Rvol = ((Range-p)*Rvol)/Range;
-					
+
 					// falloff
 					Lvol = (Lvol*(Range-Dist))/Range;
 					Rvol = (Rvol*(Range-Dist))/Range;
@@ -154,7 +157,7 @@ static void Mix(short *pFinalOut, unsign
 				pInR += Step;
 				v->m_Tick++;
 			}
-			
+
 			// free voice if not used any more
 			if(v->m_Tick == v->m_pSample->m_NumFrames)
 			{
@@ -165,8 +168,8 @@ static void Mix(short *pFinalOut, unsign
 			}
 		}
 	}
-	
-	
+
+
 	// release the lock
 	lock_release(m_SoundLock);
 
@@ -176,8 +179,8 @@ static void Mix(short *pFinalOut, unsign
 		for(unsigned i = 0; i < Frames; i++)
 		{
 			int j = i<<1;
-			int vl = ((aMixBuffer[j]*MasterVol)/101)>>8;
-			int vr = ((aMixBuffer[j+1]*MasterVol)/101)>>8;
+			int vl = ((m_pMixBuffer[j]*MasterVol)/101)>>8;
+			int vr = ((m_pMixBuffer[j+1]*MasterVol)/101)>>8;
 
 			pFinalOut[j] = Int2Short(vl);
 			pFinalOut[j+1] = Int2Short(vr);
@@ -201,14 +204,20 @@ int CSound::Init()
 	m_SoundEnabled = 0;
 	m_pGraphics = Kernel()->RequestInterface<IEngineGraphics>();
 	m_pStorage = Kernel()->RequestInterface<IStorage>();
-	
+
 	SDL_AudioSpec Format;
-	
+
 	m_SoundLock = lock_create();
-	
+
 	if(!g_Config.m_SndEnable)
 		return 0;
-	
+
+	if(SDL_InitSubSystem(SDL_INIT_AUDIO) < 0)
+	{
+		dbg_msg("gfx", "unable to init SDL audio: %s", SDL_GetError());
+		return -1;
+	}
+
 	m_MixingRate = g_Config.m_SndRate;
 
 	// Set 16-bit stereo audio at 22Khz
@@ -228,8 +237,11 @@ int CSound::Init()
 	else
 		dbg_msg("client/sound", "sound init successful");
 
+	m_MaxFrames = g_Config.m_SndBufferSize*2;
+	m_pMixBuffer = (int *)mem_alloc(m_MaxFrames*2*sizeof(int), 1);
+
 	SDL_PauseAudio(0);
-	
+
 	m_SoundEnabled = 1;
 	Update(); // update the volume
 	return 0;
@@ -239,24 +251,30 @@ int CSound::Update()
 {
 	// update volume
 	int WantedVolume = g_Config.m_SndVolume;
-	
+
 	if(!m_pGraphics->WindowActive() && g_Config.m_SndNonactiveMute)
 		WantedVolume = 0;
-	
+
 	if(WantedVolume != m_SoundVolume)
 	{
 		lock_wait(m_SoundLock);
 		m_SoundVolume = WantedVolume;
 		lock_release(m_SoundLock);
 	}
-	
+
 	return 0;
 }
 
 int CSound::Shutdown()
 {
 	SDL_CloseAudio();
+	SDL_QuitSubSystem(SDL_INIT_AUDIO);
 	lock_destroy(m_SoundLock);
+	if(m_pMixBuffer)
+	{
+		mem_free(m_pMixBuffer);
+		m_pMixBuffer = 0;
+	}
 	return 0;
 }
 
@@ -277,7 +295,7 @@ void CSound::RateConvert(int SampleID)
 	CSample *pSample = &m_aSamples[SampleID];
 	int NumFrames = 0;
 	short *pNewData = 0;
-	
+
 	// make sure that we need to convert this sound
 	if(!pSample->m_pData || pSample->m_Rate == m_MixingRate)
 		return;
@@ -285,7 +303,7 @@ void CSound::RateConvert(int SampleID)
 	// allocate new data
 	NumFrames = (int)((pSample->m_NumFrames/(float)pSample->m_Rate)*m_MixingRate);
 	pNewData = (short *)mem_alloc(NumFrames*pSample->m_Channels*sizeof(short), 1);
-	
+
 	for(int i = 0; i < NumFrames; i++)
 	{
 		// resample TODO: this should be done better, like linear atleast
@@ -293,7 +311,7 @@ void CSound::RateConvert(int SampleID)
 		int f = (int)(a*pSample->m_NumFrames);
 		if(f >= pSample->m_NumFrames)
 			f = pSample->m_NumFrames-1;
-		
+
 		// set new data
 		if(pSample->m_Channels == 1)
 			pNewData[i] = pSample->m_pData[f];
@@ -303,7 +321,7 @@ void CSound::RateConvert(int SampleID)
 			pNewData[i*2+1] = pSample->m_pData[f*2+1];
 		}
 	}
-	
+
 	// free old data and apply new
 	mem_free(pSample->m_pData);
 	pSample->m_pData = pNewData;
@@ -321,15 +339,15 @@ int CSound::LoadWV(const char *pFilename
 	int SampleID = -1;
 	char aError[100];
 	WavpackContext *pContext;
-	
+
 	// don't waste memory on sound when we are stress testing
 	if(g_Config.m_DbgStress)
 		return -1;
-		
+
 	// no need to load sound when we are running with no sound
 	if(!m_SoundEnabled)
 		return 1;
-		
+
 	if(!m_pStorage)
 		return -1;
 
@@ -372,7 +390,7 @@ int CSound::LoadWV(const char *pFilename
 			dbg_msg("sound/wv", "file is %d Hz, not 44100 Hz. filename='%s'", snd->rate, filename);
 			return -1;
 		}*/
-		
+
 		if(BitsPerSample != 16)
 		{
 			dbg_msg("sound/wv", "bps is %d, not 16, filname='%s'", BitsPerSample, pFilename);
@@ -382,7 +400,7 @@ int CSound::LoadWV(const char *pFilename
 		pData = (int *)mem_alloc(4*m_aSamples*m_aChannels, 1);
 		WavpackUnpackSamples(pContext, pData, m_aSamples); // TODO: check return value
 		pSrc = pData;
-		
+
 		pSample->m_pData = (short *)mem_alloc(2*m_aSamples*m_aChannels, 1);
 		pDst = pSample->m_pData;
 
@@ -428,9 +446,9 @@ int CSound::Play(int ChannelID, int Samp
 {
 	int VoiceID = -1;
 	int i;
-	
+
 	lock_wait(m_SoundLock);
-	
+
 	// search for voice
 	for(i = 0; i < NUM_VOICES; i++)
 	{
@@ -442,7 +460,7 @@ int CSound::Play(int ChannelID, int Samp
 			break;
 		}
 	}
-	
+
 	// voice found, use it
 	if(VoiceID != -1)
 	{
@@ -457,7 +475,7 @@ int CSound::Play(int ChannelID, int Samp
 		m_aVoices[VoiceID].m_X = (int)x;
 		m_aVoices[VoiceID].m_Y = (int)y;
 	}
-	
+
 	lock_release(m_SoundLock);
 	return VoiceID;
 }
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/client/text.cpp alien-rc4/src//engine/client/text.cpp
--- teeworlds-b177-r50edfd37-source/src//engine/client/text.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/client/text.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -9,21 +9,11 @@
 	#include <windows.h>
 #endif
 
-#ifdef CONF_PLATFORM_MACOSX
-	#include <OpenGL/gl.h>
-	#include <OpenGL/glu.h>
-#else
-	#include <GL/gl.h>
-	#include <GL/glu.h>
-#endif
-
 // ft2 texture
 #include <ft2build.h>
 #include FT_FREETYPE_H
 
 // TODO: Refactor: clean this up
-
-
 enum
 {
 	MAX_CHARACTERS = 64,
@@ -54,7 +44,7 @@ struct CFontSizeData
 	int m_FontSize;
 	FT_Face *m_pFace;
 
-	GLuint m_aTextures[2];
+	int m_aTextures[2];
 	int m_TextureWidth;
 	int m_TextureHeight;
 
@@ -107,7 +97,7 @@ class CTextRender : public IEngineTextRe
 	float m_TextOutlineB;
 	float m_TextOutlineA;
 
-	int m_FontTextureFormat;
+	//int m_FontTextureFormat;
 
 	CFont *m_pDefaultFont;
 
@@ -158,26 +148,25 @@ class CTextRender : public IEngineTextRe
 		void *pMem = mem_alloc(Width*Height, 1);
 		mem_zero(pMem, Width*Height);
 
-		if(pSizeData->m_aTextures[0] == 0)
-			glGenTextures(2, pSizeData->m_aTextures);
-		else
-			FontMemoryUsage -= pSizeData->m_TextureWidth*pSizeData->m_TextureHeight*2;
+		for(int i = 0; i < 2; i++)
+		{
+			if(pSizeData->m_aTextures[i] != 0)
+			{
+				Graphics()->UnloadTexture(pSizeData->m_aTextures[i]);
+				FontMemoryUsage -= pSizeData->m_TextureWidth*pSizeData->m_TextureHeight;
+				pSizeData->m_aTextures[i] = 0;
+			}
+
+			pSizeData->m_aTextures[i] = Graphics()->LoadTextureRaw(Width, Height, CImageInfo::FORMAT_ALPHA, pMem, CImageInfo::FORMAT_ALPHA, IGraphics::TEXLOAD_NOMIPMAPS);
+			FontMemoryUsage += Width*Height;
+		}
 
 		pSizeData->m_NumXChars = Xchars;
 		pSizeData->m_NumYChars = Ychars;
 		pSizeData->m_TextureWidth = Width;
 		pSizeData->m_TextureHeight = Height;
 		pSizeData->m_CurrentCharacter = 0;
-
-		for(int i = 0; i < 2; i++)
-		{
-			glBindTexture(GL_TEXTURE_2D, pSizeData->m_aTextures[i]);
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
-			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
-			glTexImage2D(GL_TEXTURE_2D, 0, m_FontTextureFormat, Width, Height, 0, m_FontTextureFormat, GL_UNSIGNED_BYTE, pMem);
-			FontMemoryUsage += Width*Height;
-		}
-
+		
 		dbg_msg("", "pFont memory usage: %d", FontMemoryUsage);
 
 		mem_free(pMem);
@@ -254,11 +243,16 @@ class CTextRender : public IEngineTextRe
 		int x = (SlotID%pSizeData->m_NumXChars) * (pSizeData->m_TextureWidth/pSizeData->m_NumXChars);
 		int y = (SlotID/pSizeData->m_NumXChars) * (pSizeData->m_TextureHeight/pSizeData->m_NumYChars);
 
+		Graphics()->LoadTextureRawSub(pSizeData->m_aTextures[Texnum], x, y,
+			pSizeData->m_TextureWidth/pSizeData->m_NumXChars,
+			pSizeData->m_TextureHeight/pSizeData->m_NumYChars,
+			CImageInfo::FORMAT_ALPHA, pData);
+		/*
 		glBindTexture(GL_TEXTURE_2D, pSizeData->m_aTextures[Texnum]);
 		glTexSubImage2D(GL_TEXTURE_2D, 0, x, y,
 			pSizeData->m_TextureWidth/pSizeData->m_NumXChars,
 			pSizeData->m_TextureHeight/pSizeData->m_NumYChars,
-			m_FontTextureFormat, GL_UNSIGNED_BYTE, pData);
+			m_FontTextureFormat, GL_UNSIGNED_BYTE, pData);*/
 	}
 
 	// 32k of data used for rendering glyphs
@@ -285,7 +279,8 @@ class CTextRender : public IEngineTextRe
 					Oldest = i;
 			}
 
-			if(time_get()-pSizeData->m_aCharacters[Oldest].m_TouchTime < time_freq())
+			if(time_get()-pSizeData->m_aCharacters[Oldest].m_TouchTime < time_freq() &&
+				(pSizeData->m_NumXChars < MAX_CHARACTERS || pSizeData->m_NumYChars < MAX_CHARACTERS))
 			{
 				IncreaseTextureSize(pSizeData);
 				return GetSlot(pSizeData);
@@ -455,7 +450,7 @@ public:
 		m_pDefaultFont = 0;
 
 		// GL_LUMINANCE can be good for debugging
-		m_FontTextureFormat = GL_ALPHA;
+		//m_FontTextureFormat = GL_ALPHA;
 	}
 
 	virtual void Init()
@@ -620,11 +615,10 @@ public:
 			if(pCursor->m_Flags&TEXTFLAG_RENDER)
 			{
 				// TODO: Make this better
-				glEnable(GL_TEXTURE_2D);
 				if (i == 0)
-					glBindTexture(GL_TEXTURE_2D, pSizeData->m_aTextures[1]);
+					Graphics()->TextureSet(pSizeData->m_aTextures[1]);
 				else
-					glBindTexture(GL_TEXTURE_2D, pSizeData->m_aTextures[0]);
+					Graphics()->TextureSet(pSizeData->m_aTextures[0]);
 
 				Graphics()->QuadsBegin();
 				if (i == 0)
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/client.h alien-rc4/src//engine/client.h
--- teeworlds-b177-r50edfd37-source/src//engine/client.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/client.h	2012-06-14 23:57:39.000000000 +0200
@@ -23,7 +23,7 @@ protected:
 	float m_PredIntraTick;
 
 	float m_LocalTime;
-	float m_FrameTime;
+	float m_RenderFrameTime;
 
 	int m_GameTickSpeed;
 public:
@@ -68,7 +68,7 @@ public:
 	inline int GameTickSpeed() const { return m_GameTickSpeed; }
 
 	// other time access
-	inline float FrameTime() const { return m_FrameTime; }
+	inline float RenderFrameTime() const { return m_RenderFrameTime; }
 	inline float LocalTime() const { return m_LocalTime; }
 
 	// actions
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/console.h alien-rc4/src//engine/console.h
--- teeworlds-b177-r50edfd37-source/src//engine/console.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/console.h	2012-06-14 23:57:39.000000000 +0200
@@ -78,6 +78,7 @@ public:
 
 	virtual bool LineIsValid(const char *pStr) = 0;
 	virtual void ExecuteLine(const char *Sptr) = 0;
+	virtual void ExecuteLineFlag(const char *Sptr, int FlasgMask) = 0;
 	virtual void ExecuteLineStroked(int Stroke, const char *pStr) = 0;
 	virtual void ExecuteFile(const char *pFilename) = 0;
 
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/demo.h alien-rc4/src//engine/demo.h
--- teeworlds-b177-r50edfd37-source/src//engine/demo.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/demo.h	2012-06-14 23:57:39.000000000 +0200
@@ -5,6 +5,11 @@
 
 #include "kernel.h"
 
+enum
+{
+	MAX_TIMELINE_MARKERS=64
+};
+
 struct CDemoHeader
 {
 	unsigned char m_aMarker[7];
@@ -16,6 +21,8 @@ struct CDemoHeader
 	char m_aType[8];
 	char m_aLength[4];
 	char m_aTimestamp[20];
+	char m_aNumTimelineMarkers[4];
+	char m_aTimelineMarkers[MAX_TIMELINE_MARKERS][4];
 };
 
 class IDemoPlayer : public IInterface
@@ -31,6 +38,9 @@ public:
 		int m_FirstTick;
 		int m_CurrentTick;
 		int m_LastTick;
+
+		int m_NumTimelineMarkers;
+		int m_aTimelineMarkers[MAX_TIMELINE_MARKERS];
 	};
 
 	enum
@@ -42,7 +52,7 @@ public:
 
 	~IDemoPlayer() {}
 	virtual void SetSpeed(float Speed) = 0;
-	virtual int SetPos(float Precent) = 0;
+	virtual int SetPos(float Percent) = 0;
 	virtual void Pause() = 0;
 	virtual void Unpause() = 0;
 	virtual const CInfo *BaseInfo() const = 0;
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/docs/client_time.txt alien-rc4/src//engine/docs/client_time.txt
--- teeworlds-b177-r50edfd37-source/src//engine/docs/client_time.txt	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/docs/client_time.txt	2012-06-14 23:57:39.000000000 +0200
@@ -6,6 +6,6 @@ predtick, predintratick
  prevtick              tick                 predtick
    4                     8                    14
    |---------------------|---------------------|
-   0 <- intratick    ->  1                     
+   0 <- intratick    ->  1
    0 <- ticktime(in s)-> X
                          0 <- predintratick?-> 1
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/docs/prediction.txt alien-rc4/src//engine/docs/prediction.txt
--- teeworlds-b177-r50edfd37-source/src//engine/docs/prediction.txt	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/docs/prediction.txt	2012-06-14 23:57:39.000000000 +0200
@@ -8,7 +8,7 @@ Predicted input sent to the server can b
 > {
 > 	int tick;
 > 	prediction_reset();
-> 
+>
 > 	for(tick = client_tick()+1; tick <= client_predtick(); tick++)
 > 	{
 > 		MY_INPUT *input = (MY_INPUT *)client_get_input();
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/docs/server_op.txt alien-rc4/src//engine/docs/server_op.txt
--- teeworlds-b177-r50edfd37-source/src//engine/docs/server_op.txt	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/docs/server_op.txt	2012-06-14 23:57:39.000000000 +0200
@@ -25,13 +25,13 @@ while running
 			send snapshot
 		end for
 	end
-	
+
 	process new network messages
 end while
 
 unload map
 (end)
-		
+
 
 
 Section: Reinit
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/docs/snapshots.txt alien-rc4/src//engine/docs/snapshots.txt
--- teeworlds-b177-r50edfd37-source/src//engine/docs/snapshots.txt	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/docs/snapshots.txt	2012-06-14 23:57:39.000000000 +0200
@@ -48,7 +48,7 @@ After a snapshot have been created, comp
 
 Topic: Interval
 
-The interval for how often a client recives a snapshot changes during the course of the connection. There are three different snapshot rates. 
+The interval for how often a client recives a snapshot changes during the course of the connection. There are three different snapshot rates.
 
 - *Init*. 5 snapshots per second. Used when a client is connecting and used until the client has acknowlaged a snapshot. This mechanism is used because the first snapshot because no delta compression can be done.
 
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/external/pnglite/VERSION alien-rc4/src//engine/external/pnglite/VERSION
--- teeworlds-b177-r50edfd37-source/src//engine/external/pnglite/VERSION	1970-01-01 01:00:00.000000000 +0100
+++ alien-rc4/src//engine/external/pnglite/VERSION	2012-06-14 23:57:39.000000000 +0200
@@ -0,0 +1 @@
+0.1.17
\ No newline at end of file
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/external/wavpack/VERSION alien-rc4/src//engine/external/wavpack/VERSION
--- teeworlds-b177-r50edfd37-source/src//engine/external/wavpack/VERSION	1970-01-01 01:00:00.000000000 +0100
+++ alien-rc4/src//engine/external/wavpack/VERSION	2012-06-14 23:57:39.000000000 +0200
@@ -0,0 +1 @@
+4.40
\ No newline at end of file
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/external/zlib/adler32.c alien-rc4/src//engine/external/zlib/adler32.c
--- teeworlds-b177-r50edfd37-source/src//engine/external/zlib/adler32.c	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/external/zlib/adler32.c	2012-06-14 23:57:39.000000000 +0200
@@ -1,12 +1,15 @@
 /* adler32.c -- compute the Adler-32 checksum of a data stream
- * Copyright (C) 1995-2004 Mark Adler
+ * Copyright (C) 1995-2007 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
 /* @(#) $Id$ */
 
-#define ZLIB_INTERNAL
-#include "zlib.h"
+#include "zutil.h"
+
+#define local static
+
+local uLong adler32_combine_(uLong adler1, uLong adler2, z_off64_t len2);
 
 #define BASE 65521UL    /* largest prime smaller than 65536 */
 #define NMAX 5552
@@ -125,10 +128,10 @@ uLong ZEXPORT adler32(adler, buf, len)
 }
 
 /* ========================================================================= */
-uLong ZEXPORT adler32_combine(adler1, adler2, len2)
+local uLong adler32_combine_(adler1, adler2, len2)
     uLong adler1;
     uLong adler2;
-    z_off_t len2;
+    z_off64_t len2;
 {
     unsigned long sum1;
     unsigned long sum2;
@@ -141,9 +144,26 @@ uLong ZEXPORT adler32_combine(adler1, ad
     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;
+    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);
 }
+
+/* ========================================================================= */
+uLong ZEXPORT adler32_combine(adler1, adler2, len2)
+    uLong adler1;
+    uLong adler2;
+    z_off_t len2;
+{
+    return adler32_combine_(adler1, adler2, len2);
+}
+
+uLong ZEXPORT adler32_combine64(adler1, adler2, len2)
+    uLong adler1;
+    uLong adler2;
+    z_off64_t len2;
+{
+    return adler32_combine_(adler1, adler2, len2);
+}
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/external/zlib/compress.c alien-rc4/src//engine/external/zlib/compress.c
--- teeworlds-b177-r50edfd37-source/src//engine/external/zlib/compress.c	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/external/zlib/compress.c	2012-06-14 23:57:39.000000000 +0200
@@ -1,5 +1,5 @@
 /* compress.c -- compress a memory buffer
- * Copyright (C) 1995-2003 Jean-loup Gailly.
+ * Copyright (C) 1995-2005 Jean-loup Gailly.
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -75,5 +75,6 @@ int ZEXPORT compress (dest, destLen, sou
 uLong ZEXPORT compressBound (sourceLen)
     uLong sourceLen;
 {
-    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
+    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
+           (sourceLen >> 25) + 13;
 }
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/external/zlib/crc32.c alien-rc4/src//engine/external/zlib/crc32.c
--- teeworlds-b177-r50edfd37-source/src//engine/external/zlib/crc32.c	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/external/zlib/crc32.c	2012-06-14 23:57:39.000000000 +0200
@@ -1,5 +1,5 @@
 /* crc32.c -- compute the CRC-32 of a data stream
- * Copyright (C) 1995-2005 Mark Adler
+ * Copyright (C) 1995-2006, 2010 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
@@ -53,7 +53,7 @@
 
 /* Definitions for doing the crc four data bytes at a time. */
 #ifdef BYFOUR
-#  define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
+#  define REV(w) ((((w)>>24)&0xff)+(((w)>>8)&0xff00)+ \
                 (((w)&0xff00)<<8)+(((w)&0xff)<<24))
    local unsigned long crc32_little OF((unsigned long,
                         const unsigned char FAR *, unsigned));
@@ -68,6 +68,8 @@
 local unsigned long gf2_matrix_times OF((unsigned long *mat,
                                          unsigned long vec));
 local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
+local uLong crc32_combine_(uLong crc1, uLong crc2, z_off64_t len2);
+
 
 #ifdef DYNAMIC_CRC_TABLE
 
@@ -219,7 +221,7 @@ const unsigned long FAR * ZEXPORT get_cr
 unsigned long ZEXPORT crc32(crc, buf, len)
     unsigned long crc;
     const unsigned char FAR *buf;
-    unsigned len;
+    uInt len;
 {
     if (buf == Z_NULL) return 0UL;
 
@@ -367,22 +369,22 @@ local void gf2_matrix_square(square, mat
 }
 
 /* ========================================================================= */
-uLong ZEXPORT crc32_combine(crc1, crc2, len2)
+local uLong crc32_combine_(crc1, crc2, len2)
     uLong crc1;
     uLong crc2;
-    z_off_t len2;
+    z_off64_t len2;
 {
     int n;
     unsigned long row;
     unsigned long even[GF2_DIM];    /* even-power-of-two zeros operator */
     unsigned long odd[GF2_DIM];     /* odd-power-of-two zeros operator */
 
-    /* degenerate case */
-    if (len2 == 0)
+    /* degenerate case (also disallow negative lengths) */
+    if (len2 <= 0)
         return crc1;
 
     /* put operator for one zero bit in odd */
-    odd[0] = 0xedb88320L;           /* CRC-32 polynomial */
+    odd[0] = 0xedb88320UL;          /* CRC-32 polynomial */
     row = 1;
     for (n = 1; n < GF2_DIM; n++) {
         odd[n] = row;
@@ -421,3 +423,20 @@ uLong ZEXPORT crc32_combine(crc1, crc2,
     crc1 ^= crc2;
     return crc1;
 }
+
+/* ========================================================================= */
+uLong ZEXPORT crc32_combine(crc1, crc2, len2)
+    uLong crc1;
+    uLong crc2;
+    z_off_t len2;
+{
+    return crc32_combine_(crc1, crc2, len2);
+}
+
+uLong ZEXPORT crc32_combine64(crc1, crc2, len2)
+    uLong crc1;
+    uLong crc2;
+    z_off64_t len2;
+{
+    return crc32_combine_(crc1, crc2, len2);
+}
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/external/zlib/deflate.c alien-rc4/src//engine/external/zlib/deflate.c
--- teeworlds-b177-r50edfd37-source/src//engine/external/zlib/deflate.c	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/external/zlib/deflate.c	2012-06-14 23:57:39.000000000 +0200
@@ -1,5 +1,5 @@
 /* deflate.c -- compress data using the deflation algorithm
- * Copyright (C) 1995-2005 Jean-loup Gailly.
+ * Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -52,7 +52,7 @@
 #include "deflate.h"
 
 const char deflate_copyright[] =
-   " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
+   " deflate 1.2.5 Copyright 1995-2010 Jean-loup Gailly and 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
@@ -79,19 +79,18 @@ local block_state deflate_fast   OF((def
 #ifndef FASTEST
 local block_state deflate_slow   OF((deflate_state *s, int flush));
 #endif
+local block_state deflate_rle    OF((deflate_state *s, int flush));
+local block_state deflate_huff   OF((deflate_state *s, int flush));
 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,
@@ -110,11 +109,6 @@ local  void check_match OF((deflate_stat
 #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
@@ -288,6 +282,8 @@ int ZEXPORT deflateInit2_(strm, level, m
     s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));
     s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));
 
+    s->high_water = 0;      /* nothing written to s->window yet */
+
     s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
 
     overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
@@ -332,8 +328,8 @@ int ZEXPORT deflateSetDictionary (strm,
         strm->adler = adler32(strm->adler, dictionary, dictLength);
 
     if (length < MIN_MATCH) return Z_OK;
-    if (length > MAX_DIST(s)) {
-        length = MAX_DIST(s);
+    if (length > s->w_size) {
+        length = s->w_size;
         dictionary += dictLength - length; /* use the tail of the dictionary */
     }
     zmemcpy(s->window, dictionary, length);
@@ -435,9 +431,10 @@ int ZEXPORT deflateParams(strm, level, s
     }
     func = configuration_table[s->level].func;
 
-    if (func != configuration_table[level].func && strm->total_in != 0) {
+    if ((strategy != s->strategy || func != configuration_table[level].func) &&
+        strm->total_in != 0) {
         /* Flush the last buffer: */
-        err = deflate(strm, Z_PARTIAL_FLUSH);
+        err = deflate(strm, Z_BLOCK);
     }
     if (s->level != level) {
         s->level = level;
@@ -481,33 +478,66 @@ int ZEXPORT deflateTune(strm, good_lengt
  * 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.
+ * This function could be more sophisticated to provide closer upper bounds for
+ * every combination of windowBits and memLevel.  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;
+    uLong complen, wraplen;
+    Bytef *str;
 
-    /* conservative upper bound */
-    destLen = sourceLen +
-              ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
+    /* conservative upper bound for compressed data */
+    complen = sourceLen +
+              ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
 
-    /* if can't get parameters, return conservative bound */
+    /* if can't get parameters, return conservative bound plus zlib wrapper */
     if (strm == Z_NULL || strm->state == Z_NULL)
-        return destLen;
+        return complen + 6;
 
-    /* if not default parameters, return conservative bound */
+    /* compute wrapper length */
     s = strm->state;
+    switch (s->wrap) {
+    case 0:                                 /* raw deflate */
+        wraplen = 0;
+        break;
+    case 1:                                 /* zlib wrapper */
+        wraplen = 6 + (s->strstart ? 4 : 0);
+        break;
+    case 2:                                 /* gzip wrapper */
+        wraplen = 18;
+        if (s->gzhead != Z_NULL) {          /* user-supplied gzip header */
+            if (s->gzhead->extra != Z_NULL)
+                wraplen += 2 + s->gzhead->extra_len;
+            str = s->gzhead->name;
+            if (str != Z_NULL)
+                do {
+                    wraplen++;
+                } while (*str++);
+            str = s->gzhead->comment;
+            if (str != Z_NULL)
+                do {
+                    wraplen++;
+                } while (*str++);
+            if (s->gzhead->hcrc)
+                wraplen += 2;
+        }
+        break;
+    default:                                /* for compiler happiness */
+        wraplen = 6;
+    }
+
+    /* if not default parameters, return conservative bound */
     if (s->w_bits != 15 || s->hash_bits != 8 + 7)
-        return destLen;
+        return complen + wraplen;
 
     /* default settings: return tight bound for that case */
-    return compressBound(sourceLen);
+    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
+           (sourceLen >> 25) + 13 - 6 + wraplen;
 }
 
 /* =========================================================================
@@ -557,7 +587,7 @@ int ZEXPORT deflate (strm, flush)
     deflate_state *s;
 
     if (strm == Z_NULL || strm->state == Z_NULL ||
-        flush > Z_FINISH || flush < 0) {
+        flush > Z_BLOCK || flush < 0) {
         return Z_STREAM_ERROR;
     }
     s = strm->state;
@@ -581,7 +611,7 @@ int ZEXPORT deflate (strm, flush)
             put_byte(s, 31);
             put_byte(s, 139);
             put_byte(s, 8);
-            if (s->gzhead == NULL) {
+            if (s->gzhead == Z_NULL) {
                 put_byte(s, 0);
                 put_byte(s, 0);
                 put_byte(s, 0);
@@ -608,7 +638,7 @@ int ZEXPORT deflate (strm, flush)
                             (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
                              4 : 0));
                 put_byte(s, s->gzhead->os & 0xff);
-                if (s->gzhead->extra != NULL) {
+                if (s->gzhead->extra != Z_NULL) {
                     put_byte(s, s->gzhead->extra_len & 0xff);
                     put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
                 }
@@ -650,7 +680,7 @@ int ZEXPORT deflate (strm, flush)
     }
 #ifdef GZIP
     if (s->status == EXTRA_STATE) {
-        if (s->gzhead->extra != NULL) {
+        if (s->gzhead->extra != Z_NULL) {
             uInt beg = s->pending;  /* start of bytes to update crc */
 
             while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
@@ -678,7 +708,7 @@ int ZEXPORT deflate (strm, flush)
             s->status = NAME_STATE;
     }
     if (s->status == NAME_STATE) {
-        if (s->gzhead->name != NULL) {
+        if (s->gzhead->name != Z_NULL) {
             uInt beg = s->pending;  /* start of bytes to update crc */
             int val;
 
@@ -709,7 +739,7 @@ int ZEXPORT deflate (strm, flush)
             s->status = COMMENT_STATE;
     }
     if (s->status == COMMENT_STATE) {
-        if (s->gzhead->comment != NULL) {
+        if (s->gzhead->comment != Z_NULL) {
             uInt beg = s->pending;  /* start of bytes to update crc */
             int val;
 
@@ -787,7 +817,9 @@ int ZEXPORT deflate (strm, flush)
         (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
         block_state bstate;
 
-        bstate = (*(configuration_table[s->level].func))(s, flush);
+        bstate = s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
+                    (s->strategy == Z_RLE ? deflate_rle(s, flush) :
+                        (*(configuration_table[s->level].func))(s, flush));
 
         if (bstate == finish_started || bstate == finish_done) {
             s->status = FINISH_STATE;
@@ -808,13 +840,17 @@ int ZEXPORT deflate (strm, flush)
         if (bstate == block_done) {
             if (flush == Z_PARTIAL_FLUSH) {
                 _tr_align(s);
-            } else { /* FULL_FLUSH or SYNC_FLUSH */
+            } else if (flush != Z_BLOCK) { /* 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 */
+                    if (s->lookahead == 0) {
+                        s->strstart = 0;
+                        s->block_start = 0L;
+                    }
                 }
             }
             flush_pending(strm);
@@ -1167,12 +1203,13 @@ local uInt longest_match(s, cur_match)
     return s->lookahead;
 }
 #endif /* ASMV */
-#endif /* FASTEST */
+
+#else /* FASTEST */
 
 /* ---------------------------------------------------------------------------
- * Optimized version for level == 1 or strategy == Z_RLE only
+ * Optimized version for FASTEST only
  */
-local uInt longest_match_fast(s, cur_match)
+local uInt longest_match(s, cur_match)
     deflate_state *s;
     IPos cur_match;                             /* current match */
 {
@@ -1225,6 +1262,8 @@ local uInt longest_match_fast(s, cur_mat
     return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
 }
 
+#endif /* FASTEST */
+
 #ifdef DEBUG
 /* ===========================================================================
  * Check that the match at match_start is indeed a match.
@@ -1303,7 +1342,6 @@ local void fill_window(s)
                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 {
@@ -1355,27 +1393,61 @@ local void fill_window(s)
          */
 
     } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
+
+    /* If the WIN_INIT bytes after the end of the current data have never been
+     * written, then zero those bytes in order to avoid memory check reports of
+     * the use of uninitialized (or uninitialised as Julian writes) bytes by
+     * the longest match routines.  Update the high water mark for the next
+     * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
+     * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
+     */
+    if (s->high_water < s->window_size) {
+        ulg curr = s->strstart + (ulg)(s->lookahead);
+        ulg init;
+
+        if (s->high_water < curr) {
+            /* Previous high water mark below current data -- zero WIN_INIT
+             * bytes or up to end of window, whichever is less.
+             */
+            init = s->window_size - curr;
+            if (init > WIN_INIT)
+                init = WIN_INIT;
+            zmemzero(s->window + curr, (unsigned)init);
+            s->high_water = curr + init;
+        }
+        else if (s->high_water < (ulg)curr + WIN_INIT) {
+            /* High water mark at or above current data, but below current data
+             * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
+             * to end of window, whichever is less.
+             */
+            init = (ulg)curr + WIN_INIT - s->high_water;
+            if (init > s->window_size - s->high_water)
+                init = s->window_size - s->high_water;
+            zmemzero(s->window + s->high_water, (unsigned)init);
+            s->high_water += init;
+        }
+    }
 }
 
 /* ===========================================================================
  * 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) { \
+#define FLUSH_BLOCK_ONLY(s, last) { \
    _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)); \
+                (last)); \
    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; \
+#define FLUSH_BLOCK(s, last) { \
+   FLUSH_BLOCK_ONLY(s, last); \
+   if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
 }
 
 /* ===========================================================================
@@ -1449,7 +1521,7 @@ local block_state deflate_fast(s, flush)
     deflate_state *s;
     int flush;
 {
-    IPos hash_head = NIL; /* head of the hash chain */
+    IPos hash_head;       /* head of the hash chain */
     int bflush;           /* set if current block must be flushed */
 
     for (;;) {
@@ -1469,6 +1541,7 @@ local block_state deflate_fast(s, flush)
         /* Insert the string window[strstart .. strstart+2] in the
          * dictionary, and set hash_head to the head of the hash chain:
          */
+        hash_head = NIL;
         if (s->lookahead >= MIN_MATCH) {
             INSERT_STRING(s, s->strstart, hash_head);
         }
@@ -1481,19 +1554,8 @@ local block_state deflate_fast(s, flush)
              * 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 */
+            s->match_length = longest_match (s, hash_head);
+            /* longest_match() sets match_start */
         }
         if (s->match_length >= MIN_MATCH) {
             check_match(s, s->strstart, s->match_start, s->match_length);
@@ -1555,7 +1617,7 @@ local block_state deflate_slow(s, flush)
     deflate_state *s;
     int flush;
 {
-    IPos hash_head = NIL;    /* head of hash chain */
+    IPos hash_head;          /* head of hash chain */
     int bflush;              /* set if current block must be flushed */
 
     /* Process the input block. */
@@ -1576,6 +1638,7 @@ local block_state deflate_slow(s, flush)
         /* Insert the string window[strstart .. strstart+2] in the
          * dictionary, and set hash_head to the head of the hash chain:
          */
+        hash_head = NIL;
         if (s->lookahead >= MIN_MATCH) {
             INSERT_STRING(s, s->strstart, hash_head);
         }
@@ -1591,12 +1654,8 @@ local block_state deflate_slow(s, flush)
              * 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 */
+            s->match_length = longest_match (s, hash_head);
+            /* longest_match() sets match_start */
 
             if (s->match_length <= 5 && (s->strategy == Z_FILTERED
 #if TOO_FAR <= 32767
@@ -1674,7 +1733,6 @@ local block_state deflate_slow(s, flush)
 }
 #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
@@ -1684,11 +1742,9 @@ 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 */
+    int bflush;             /* set if current block must be flushed */
+    uInt prev;              /* byte at distance one to match */
+    Bytef *scan, *strend;   /* scan goes up to strend for length of run */
 
     for (;;) {
         /* Make sure that we always have enough lookahead, except
@@ -1704,23 +1760,33 @@ local block_state deflate_rle(s, flush)
         }
 
         /* 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;
+        s->match_length = 0;
+        if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
             scan = s->window + s->strstart - 1;
-            prev = *scan++;
-            do {
-                if (*scan++ != prev)
-                    break;
-            } while (++run < max);
+            prev = *scan;
+            if (prev == *++scan && prev == *++scan && prev == *++scan) {
+                strend = s->window + s->strstart + MAX_MATCH;
+                do {
+                } while (prev == *++scan && prev == *++scan &&
+                         prev == *++scan && prev == *++scan &&
+                         prev == *++scan && prev == *++scan &&
+                         prev == *++scan && prev == *++scan &&
+                         scan < strend);
+                s->match_length = MAX_MATCH - (int)(strend - scan);
+                if (s->match_length > s->lookahead)
+                    s->match_length = s->lookahead;
+            }
         }
 
         /* 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;
+        if (s->match_length >= MIN_MATCH) {
+            check_match(s, s->strstart, s->strstart - 1, s->match_length);
+
+            _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);
+
+            s->lookahead -= s->match_length;
+            s->strstart += s->match_length;
+            s->match_length = 0;
         } else {
             /* No match, output a literal byte */
             Tracevv((stderr,"%c", s->window[s->strstart]));
@@ -1733,4 +1799,36 @@ local block_state deflate_rle(s, flush)
     FLUSH_BLOCK(s, flush == Z_FINISH);
     return flush == Z_FINISH ? finish_done : block_done;
 }
-#endif
+
+/* ===========================================================================
+ * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
+ * (It will be regenerated if this run of deflate switches away from Huffman.)
+ */
+local block_state deflate_huff(s, flush)
+    deflate_state *s;
+    int flush;
+{
+    int bflush;             /* set if current block must be flushed */
+
+    for (;;) {
+        /* Make sure that we have a literal to write. */
+        if (s->lookahead == 0) {
+            fill_window(s);
+            if (s->lookahead == 0) {
+                if (flush == Z_NO_FLUSH)
+                    return need_more;
+                break;      /* flush the current block */
+            }
+        }
+
+        /* Output a literal byte */
+        s->match_length = 0;
+        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;
+}
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/external/zlib/deflate.h alien-rc4/src//engine/external/zlib/deflate.h
--- teeworlds-b177-r50edfd37-source/src//engine/external/zlib/deflate.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/external/zlib/deflate.h	2012-06-14 23:57:39.000000000 +0200
@@ -1,5 +1,5 @@
 /* deflate.h -- internal compression state
- * Copyright (C) 1995-2004 Jean-loup Gailly
+ * Copyright (C) 1995-2010 Jean-loup Gailly
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -260,6 +260,13 @@ typedef struct internal_state {
      * are always zero.
      */
 
+    ulg high_water;
+    /* High water mark offset in window for initialized bytes -- bytes above
+     * this are set to zero in order to avoid memory check warnings when
+     * longest match routines access bytes past the input.  This is then
+     * updated to the new high water mark.
+     */
+
 } FAR deflate_state;
 
 /* Output a byte on the stream.
@@ -278,14 +285,18 @@ typedef struct internal_state {
  * distances are limited to MAX_DIST instead of WSIZE.
  */
 
+#define WIN_INIT MAX_MATCH
+/* Number of bytes after end of data in window to initialize in order to avoid
+   memory checker errors from longest match routines */
+
         /* 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));
+void ZLIB_INTERNAL _tr_init OF((deflate_state *s));
+int ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
+void ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf,
+                        ulg stored_len, int last));
+void ZLIB_INTERNAL _tr_align OF((deflate_state *s));
+void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf,
+                        ulg stored_len, int last));
 
 #define d_code(dist) \
    ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
@@ -298,11 +309,11 @@ void _tr_stored_block OF((deflate_state
 /* Inline versions of _tr_tally for speed: */
 
 #if defined(GEN_TREES_H) || !defined(STDC)
-  extern uch _length_code[];
-  extern uch _dist_code[];
+  extern uch ZLIB_INTERNAL _length_code[];
+  extern uch ZLIB_INTERNAL _dist_code[];
 #else
-  extern const uch _length_code[];
-  extern const uch _dist_code[];
+  extern const uch ZLIB_INTERNAL _length_code[];
+  extern const uch ZLIB_INTERNAL _dist_code[];
 #endif
 
 # define _tr_tally_lit(s, c, flush) \
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/external/zlib/gzio.c alien-rc4/src//engine/external/zlib/gzio.c
--- teeworlds-b177-r50edfd37-source/src//engine/external/zlib/gzio.c	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/external/zlib/gzio.c	1970-01-01 01:00:00.000000000 +0100
@@ -1,1026 +0,0 @@
-/* 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 -rupN teeworlds-b177-r50edfd37-source/src//engine/external/zlib/infback.c alien-rc4/src//engine/external/zlib/infback.c
--- teeworlds-b177-r50edfd37-source/src//engine/external/zlib/infback.c	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/external/zlib/infback.c	2012-06-14 23:57:39.000000000 +0200
@@ -1,5 +1,5 @@
 /* infback.c -- inflate using a call-back interface
- * Copyright (C) 1995-2005 Mark Adler
+ * Copyright (C) 1995-2009 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -55,7 +55,7 @@ int stream_size;
     state->wbits = windowBits;
     state->wsize = 1U << windowBits;
     state->window = window;
-    state->write = 0;
+    state->wnext = 0;
     state->whave = 0;
     return Z_OK;
 }
@@ -253,7 +253,7 @@ void FAR *out_desc;
     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 here;                  /* current decoding table entry */
     code last;                  /* parent table entry */
     unsigned len;               /* length to copy for repeats, bits to drop */
     int ret;                    /* return code */
@@ -389,19 +389,19 @@ void FAR *out_desc;
             state->have = 0;
             while (state->have < state->nlen + state->ndist) {
                 for (;;) {
-                    this = state->lencode[BITS(state->lenbits)];
-                    if ((unsigned)(this.bits) <= bits) break;
+                    here = state->lencode[BITS(state->lenbits)];
+                    if ((unsigned)(here.bits) <= bits) break;
                     PULLBYTE();
                 }
-                if (this.val < 16) {
-                    NEEDBITS(this.bits);
-                    DROPBITS(this.bits);
-                    state->lens[state->have++] = this.val;
+                if (here.val < 16) {
+                    NEEDBITS(here.bits);
+                    DROPBITS(here.bits);
+                    state->lens[state->have++] = here.val;
                 }
                 else {
-                    if (this.val == 16) {
-                        NEEDBITS(this.bits + 2);
-                        DROPBITS(this.bits);
+                    if (here.val == 16) {
+                        NEEDBITS(here.bits + 2);
+                        DROPBITS(here.bits);
                         if (state->have == 0) {
                             strm->msg = (char *)"invalid bit length repeat";
                             state->mode = BAD;
@@ -411,16 +411,16 @@ void FAR *out_desc;
                         copy = 3 + BITS(2);
                         DROPBITS(2);
                     }
-                    else if (this.val == 17) {
-                        NEEDBITS(this.bits + 3);
-                        DROPBITS(this.bits);
+                    else if (here.val == 17) {
+                        NEEDBITS(here.bits + 3);
+                        DROPBITS(here.bits);
                         len = 0;
                         copy = 3 + BITS(3);
                         DROPBITS(3);
                     }
                     else {
-                        NEEDBITS(this.bits + 7);
-                        DROPBITS(this.bits);
+                        NEEDBITS(here.bits + 7);
+                        DROPBITS(here.bits);
                         len = 0;
                         copy = 11 + BITS(7);
                         DROPBITS(7);
@@ -438,7 +438,16 @@ void FAR *out_desc;
             /* handle error breaks in while */
             if (state->mode == BAD) break;
 
-            /* build code tables */
+            /* check for end-of-block code (better have one) */
+            if (state->lens[256] == 0) {
+                strm->msg = (char *)"invalid code -- missing end-of-block";
+                state->mode = BAD;
+                break;
+            }
+
+            /* build code tables -- note: do not change the lenbits or distbits
+               values here (9 and 6) without reading the comments in inftrees.h
+               concerning the ENOUGH constants, which depend on those values */
             state->next = state->codes;
             state->lencode = (code const FAR *)(state->next);
             state->lenbits = 9;
@@ -474,28 +483,28 @@ void FAR *out_desc;
 
             /* get a literal, length, or end-of-block code */
             for (;;) {
-                this = state->lencode[BITS(state->lenbits)];
-                if ((unsigned)(this.bits) <= bits) break;
+                here = state->lencode[BITS(state->lenbits)];
+                if ((unsigned)(here.bits) <= bits) break;
                 PULLBYTE();
             }
-            if (this.op && (this.op & 0xf0) == 0) {
-                last = this;
+            if (here.op && (here.op & 0xf0) == 0) {
+                last = here;
                 for (;;) {
-                    this = state->lencode[last.val +
+                    here = state->lencode[last.val +
                             (BITS(last.bits + last.op) >> last.bits)];
-                    if ((unsigned)(last.bits + this.bits) <= bits) break;
+                    if ((unsigned)(last.bits + here.bits) <= bits) break;
                     PULLBYTE();
                 }
                 DROPBITS(last.bits);
             }
-            DROPBITS(this.bits);
-            state->length = (unsigned)this.val;
+            DROPBITS(here.bits);
+            state->length = (unsigned)here.val;
 
             /* process literal */
-            if (this.op == 0) {
-                Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
+            if (here.op == 0) {
+                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
                         "inflate:         literal '%c'\n" :
-                        "inflate:         literal 0x%02x\n", this.val));
+                        "inflate:         literal 0x%02x\n", here.val));
                 ROOM();
                 *put++ = (unsigned char)(state->length);
                 left--;
@@ -504,21 +513,21 @@ void FAR *out_desc;
             }
 
             /* process end of block */
-            if (this.op & 32) {
+            if (here.op & 32) {
                 Tracevv((stderr, "inflate:         end of block\n"));
                 state->mode = TYPE;
                 break;
             }
 
             /* invalid code */
-            if (this.op & 64) {
+            if (here.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;
+            state->extra = (unsigned)(here.op) & 15;
             if (state->extra != 0) {
                 NEEDBITS(state->extra);
                 state->length += BITS(state->extra);
@@ -528,30 +537,30 @@ void FAR *out_desc;
 
             /* get distance code */
             for (;;) {
-                this = state->distcode[BITS(state->distbits)];
-                if ((unsigned)(this.bits) <= bits) break;
+                here = state->distcode[BITS(state->distbits)];
+                if ((unsigned)(here.bits) <= bits) break;
                 PULLBYTE();
             }
-            if ((this.op & 0xf0) == 0) {
-                last = this;
+            if ((here.op & 0xf0) == 0) {
+                last = here;
                 for (;;) {
-                    this = state->distcode[last.val +
+                    here = state->distcode[last.val +
                             (BITS(last.bits + last.op) >> last.bits)];
-                    if ((unsigned)(last.bits + this.bits) <= bits) break;
+                    if ((unsigned)(last.bits + here.bits) <= bits) break;
                     PULLBYTE();
                 }
                 DROPBITS(last.bits);
             }
-            DROPBITS(this.bits);
-            if (this.op & 64) {
+            DROPBITS(here.bits);
+            if (here.op & 64) {
                 strm->msg = (char *)"invalid distance code";
                 state->mode = BAD;
                 break;
             }
-            state->offset = (unsigned)this.val;
+            state->offset = (unsigned)here.val;
 
             /* get distance extra bits, if any */
-            state->extra = (unsigned)(this.op) & 15;
+            state->extra = (unsigned)(here.op) & 15;
             if (state->extra != 0) {
                 NEEDBITS(state->extra);
                 state->offset += BITS(state->extra);
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/external/zlib/inffast.c alien-rc4/src//engine/external/zlib/inffast.c
--- teeworlds-b177-r50edfd37-source/src//engine/external/zlib/inffast.c	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/external/zlib/inffast.c	2012-06-14 23:57:39.000000000 +0200
@@ -1,5 +1,5 @@
 /* inffast.c -- fast decoding
- * Copyright (C) 1995-2004 Mark Adler
+ * Copyright (C) 1995-2008, 2010 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -64,7 +64,7 @@
       requires strm->avail_out >= 258 for each loop to avoid checking for
       output space.
  */
-void inflate_fast(strm, start)
+void ZLIB_INTERNAL inflate_fast(strm, start)
 z_streamp strm;
 unsigned start;         /* inflate()'s starting value for strm->avail_out */
 {
@@ -79,7 +79,7 @@ unsigned start;         /* inflate()'s s
 #endif
     unsigned wsize;             /* window size or zero if not using window */
     unsigned whave;             /* valid bytes in the window */
-    unsigned write;             /* window write index */
+    unsigned wnext;             /* window write index */
     unsigned char FAR *window;  /* allocated sliding window, if wsize != 0 */
     unsigned long hold;         /* local strm->hold */
     unsigned bits;              /* local strm->bits */
@@ -87,7 +87,7 @@ unsigned start;         /* inflate()'s s
     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 */
+    code here;                  /* retrieved table entry */
     unsigned op;                /* code bits, operation, extra bits, or */
                                 /*  window position, window bytes to copy */
     unsigned len;               /* match length, unused bytes */
@@ -106,7 +106,7 @@ unsigned start;         /* inflate()'s s
 #endif
     wsize = state->wsize;
     whave = state->whave;
-    write = state->write;
+    wnext = state->wnext;
     window = state->window;
     hold = state->hold;
     bits = state->bits;
@@ -124,20 +124,20 @@ unsigned start;         /* inflate()'s s
             hold += (unsigned long)(PUP(in)) << bits;
             bits += 8;
         }
-        this = lcode[hold & lmask];
+        here = lcode[hold & lmask];
       dolen:
-        op = (unsigned)(this.bits);
+        op = (unsigned)(here.bits);
         hold >>= op;
         bits -= op;
-        op = (unsigned)(this.op);
+        op = (unsigned)(here.op);
         if (op == 0) {                          /* literal */
-            Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
+            Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
                     "inflate:         literal '%c'\n" :
-                    "inflate:         literal 0x%02x\n", this.val));
-            PUP(out) = (unsigned char)(this.val);
+                    "inflate:         literal 0x%02x\n", here.val));
+            PUP(out) = (unsigned char)(here.val);
         }
         else if (op & 16) {                     /* length base */
-            len = (unsigned)(this.val);
+            len = (unsigned)(here.val);
             op &= 15;                           /* number of extra bits */
             if (op) {
                 if (bits < op) {
@@ -155,14 +155,14 @@ unsigned start;         /* inflate()'s s
                 hold += (unsigned long)(PUP(in)) << bits;
                 bits += 8;
             }
-            this = dcode[hold & dmask];
+            here = dcode[hold & dmask];
           dodist:
-            op = (unsigned)(this.bits);
+            op = (unsigned)(here.bits);
             hold >>= op;
             bits -= op;
-            op = (unsigned)(this.op);
+            op = (unsigned)(here.op);
             if (op & 16) {                      /* distance base */
-                dist = (unsigned)(this.val);
+                dist = (unsigned)(here.val);
                 op &= 15;                       /* number of extra bits */
                 if (bits < op) {
                     hold += (unsigned long)(PUP(in)) << bits;
@@ -187,12 +187,34 @@ unsigned start;         /* inflate()'s s
                 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;
+                        if (state->sane) {
+                            strm->msg =
+                                (char *)"invalid distance too far back";
+                            state->mode = BAD;
+                            break;
+                        }
+#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
+                        if (len <= op - whave) {
+                            do {
+                                PUP(out) = 0;
+                            } while (--len);
+                            continue;
+                        }
+                        len -= op - whave;
+                        do {
+                            PUP(out) = 0;
+                        } while (--op > whave);
+                        if (op == 0) {
+                            from = out - dist;
+                            do {
+                                PUP(out) = PUP(from);
+                            } while (--len);
+                            continue;
+                        }
+#endif
                     }
                     from = window - OFF;
-                    if (write == 0) {           /* very common case */
+                    if (wnext == 0) {           /* very common case */
                         from += wsize - op;
                         if (op < len) {         /* some from window */
                             len -= op;
@@ -202,17 +224,17 @@ unsigned start;         /* inflate()'s s
                             from = out - dist;  /* rest from output */
                         }
                     }
-                    else if (write < op) {      /* wrap around window */
-                        from += wsize + write - op;
-                        op -= write;
+                    else if (wnext < op) {      /* wrap around window */
+                        from += wsize + wnext - op;
+                        op -= wnext;
                         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;
+                            if (wnext < len) {  /* some from start of window */
+                                op = wnext;
                                 len -= op;
                                 do {
                                     PUP(out) = PUP(from);
@@ -222,7 +244,7 @@ unsigned start;         /* inflate()'s s
                         }
                     }
                     else {                      /* contiguous in window */
-                        from += write - op;
+                        from += wnext - op;
                         if (op < len) {         /* some from window */
                             len -= op;
                             do {
@@ -259,7 +281,7 @@ unsigned start;         /* inflate()'s s
                 }
             }
             else if ((op & 64) == 0) {          /* 2nd level distance code */
-                this = dcode[this.val + (hold & ((1U << op) - 1))];
+                here = dcode[here.val + (hold & ((1U << op) - 1))];
                 goto dodist;
             }
             else {
@@ -269,7 +291,7 @@ unsigned start;         /* inflate()'s s
             }
         }
         else if ((op & 64) == 0) {              /* 2nd level length code */
-            this = lcode[this.val + (hold & ((1U << op) - 1))];
+            here = lcode[here.val + (hold & ((1U << op) - 1))];
             goto dolen;
         }
         else if (op & 32) {                     /* end-of-block */
@@ -305,7 +327,7 @@ unsigned start;         /* inflate()'s s
    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
+   - Three separate decoding do-loops for direct, window, and wnext == 0
    - Special case for distance > 1 copies to do overlapped load and store copy
    - Explicit branch predictions (based on measured branch probabilities)
    - Deferring match copy and interspersed it with decoding subsequent codes
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/external/zlib/inffast.h alien-rc4/src//engine/external/zlib/inffast.h
--- teeworlds-b177-r50edfd37-source/src//engine/external/zlib/inffast.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/external/zlib/inffast.h	2012-06-14 23:57:39.000000000 +0200
@@ -1,5 +1,5 @@
 /* inffast.h -- header to use inffast.c
- * Copyright (C) 1995-2003 Mark Adler
+ * Copyright (C) 1995-2003, 2010 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -8,4 +8,4 @@
    subject to change. Applications should only use zlib.h.
  */
 
-void inflate_fast OF((z_streamp strm, unsigned start));
+void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start));
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/external/zlib/inflate.c alien-rc4/src//engine/external/zlib/inflate.c
--- teeworlds-b177-r50edfd37-source/src//engine/external/zlib/inflate.c	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/external/zlib/inflate.c	2012-06-14 23:57:39.000000000 +0200
@@ -1,5 +1,5 @@
 /* inflate.c -- zlib decompression
- * Copyright (C) 1995-2005 Mark Adler
+ * Copyright (C) 1995-2010 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -45,7 +45,7 @@
  * - 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()
+ * - Pull out common wnext == 0 case for speed in inflate_fast()
  * - Make op and len in inflate_fast() unsigned for consistency
  * - Add FAR to lcode and dcode declarations in inflate_fast()
  * - Simplified bad distance check in inflate_fast()
@@ -117,28 +117,52 @@ z_streamp strm;
     state->head = Z_NULL;
     state->wsize = 0;
     state->whave = 0;
-    state->write = 0;
+    state->wnext = 0;
     state->hold = 0;
     state->bits = 0;
     state->lencode = state->distcode = state->next = state->codes;
+    state->sane = 1;
+    state->back = -1;
     Tracev((stderr, "inflate: reset\n"));
     return Z_OK;
 }
 
-int ZEXPORT inflatePrime(strm, bits, value)
+int ZEXPORT inflateReset2(strm, windowBits)
 z_streamp strm;
-int bits;
-int value;
+int windowBits;
 {
+    int wrap;
     struct inflate_state FAR *state;
 
+    /* get the 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;
+
+    /* extract wrap request from windowBits parameter */
+    if (windowBits < 0) {
+        wrap = 0;
+        windowBits = -windowBits;
+    }
+    else {
+        wrap = (windowBits >> 4) + 1;
+#ifdef GUNZIP
+        if (windowBits < 48)
+            windowBits &= 15;
+#endif
+    }
+
+    /* set number of window bits, free window if different */
+    if (windowBits && (windowBits < 8 || windowBits > 15))
+        return Z_STREAM_ERROR;
+    if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) {
+        ZFREE(strm, state->window);
+        state->window = Z_NULL;
+    }
+
+    /* update state and reset the rest of it */
+    state->wrap = wrap;
+    state->wbits = (unsigned)windowBits;
+    return inflateReset(strm);
 }
 
 int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size)
@@ -147,6 +171,7 @@ int windowBits;
 const char *version;
 int stream_size;
 {
+    int ret;
     struct inflate_state FAR *state;
 
     if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
@@ -164,24 +189,13 @@ int stream_size;
     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) {
+    state->window = Z_NULL;
+    ret = inflateReset2(strm, windowBits);
+    if (ret != Z_OK) {
         ZFREE(strm, state);
         strm->state = Z_NULL;
-        return Z_STREAM_ERROR;
     }
-    state->wbits = (unsigned)windowBits;
-    state->window = Z_NULL;
-    return inflateReset(strm);
+    return ret;
 }
 
 int ZEXPORT inflateInit_(strm, version, stream_size)
@@ -192,6 +206,27 @@ int stream_size;
     return inflateInit2_(strm, DEF_WBITS, version, stream_size);
 }
 
+int ZEXPORT inflatePrime(strm, bits, value)
+z_streamp strm;
+int bits;
+int value;
+{
+    struct inflate_state FAR *state;
+
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    if (bits < 0) {
+        state->hold = 0;
+        state->bits = 0;
+        return Z_OK;
+    }
+    if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
+    value &= (1L << bits) - 1;
+    state->hold += value << state->bits;
+    state->bits += bits;
+    return Z_OK;
+}
+
 /*
    Return state with length and distance decoding tables and index sizes set to
    fixed code decoding.  Normally this returns fixed tables from inffixed.h.
@@ -340,7 +375,7 @@ unsigned out;
     /* if window not in use yet, initialize */
     if (state->wsize == 0) {
         state->wsize = 1U << state->wbits;
-        state->write = 0;
+        state->wnext = 0;
         state->whave = 0;
     }
 
@@ -348,22 +383,22 @@ unsigned out;
     copy = out - strm->avail_out;
     if (copy >= state->wsize) {
         zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
-        state->write = 0;
+        state->wnext = 0;
         state->whave = state->wsize;
     }
     else {
-        dist = state->wsize - state->write;
+        dist = state->wsize - state->wnext;
         if (dist > copy) dist = copy;
-        zmemcpy(state->window + state->write, strm->next_out - copy, dist);
+        zmemcpy(state->window + state->wnext, strm->next_out - copy, dist);
         copy -= dist;
         if (copy) {
             zmemcpy(state->window, strm->next_out - copy, copy);
-            state->write = copy;
+            state->wnext = copy;
             state->whave = state->wsize;
         }
         else {
-            state->write += dist;
-            if (state->write == state->wsize) state->write = 0;
+            state->wnext += dist;
+            if (state->wnext == state->wsize) state->wnext = 0;
             if (state->whave < state->wsize) state->whave += dist;
         }
     }
@@ -564,7 +599,7 @@ int flush;
     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 here;                  /* current decoding table entry */
     code last;                  /* parent table entry */
     unsigned len;               /* length to copy for repeats, bits to drop */
     int ret;                    /* return code */
@@ -619,7 +654,9 @@ int flush;
             }
             DROPBITS(4);
             len = BITS(4) + 8;
-            if (len > state->wbits) {
+            if (state->wbits == 0)
+                state->wbits = len;
+            else if (len > state->wbits) {
                 strm->msg = (char *)"invalid window size";
                 state->mode = BAD;
                 break;
@@ -771,7 +808,7 @@ int flush;
             strm->adler = state->check = adler32(0L, Z_NULL, 0);
             state->mode = TYPE;
         case TYPE:
-            if (flush == Z_BLOCK) goto inf_leave;
+            if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave;
         case TYPEDO:
             if (state->last) {
                 BYTEBITS();
@@ -791,7 +828,11 @@ int flush;
                 fixedtables(state);
                 Tracev((stderr, "inflate:     fixed codes block%s\n",
                         state->last ? " (last)" : ""));
-                state->mode = LEN;              /* decode codes */
+                state->mode = LEN_;             /* decode codes */
+                if (flush == Z_TREES) {
+                    DROPBITS(2);
+                    goto inf_leave;
+                }
                 break;
             case 2:                             /* dynamic block */
                 Tracev((stderr, "inflate:     dynamic codes block%s\n",
@@ -816,6 +857,9 @@ int flush;
             Tracev((stderr, "inflate:       stored length %u\n",
                     state->length));
             INITBITS();
+            state->mode = COPY_;
+            if (flush == Z_TREES) goto inf_leave;
+        case COPY_:
             state->mode = COPY;
         case COPY:
             copy = state->length;
@@ -876,19 +920,19 @@ int flush;
         case CODELENS:
             while (state->have < state->nlen + state->ndist) {
                 for (;;) {
-                    this = state->lencode[BITS(state->lenbits)];
-                    if ((unsigned)(this.bits) <= bits) break;
+                    here = state->lencode[BITS(state->lenbits)];
+                    if ((unsigned)(here.bits) <= bits) break;
                     PULLBYTE();
                 }
-                if (this.val < 16) {
-                    NEEDBITS(this.bits);
-                    DROPBITS(this.bits);
-                    state->lens[state->have++] = this.val;
+                if (here.val < 16) {
+                    NEEDBITS(here.bits);
+                    DROPBITS(here.bits);
+                    state->lens[state->have++] = here.val;
                 }
                 else {
-                    if (this.val == 16) {
-                        NEEDBITS(this.bits + 2);
-                        DROPBITS(this.bits);
+                    if (here.val == 16) {
+                        NEEDBITS(here.bits + 2);
+                        DROPBITS(here.bits);
                         if (state->have == 0) {
                             strm->msg = (char *)"invalid bit length repeat";
                             state->mode = BAD;
@@ -898,16 +942,16 @@ int flush;
                         copy = 3 + BITS(2);
                         DROPBITS(2);
                     }
-                    else if (this.val == 17) {
-                        NEEDBITS(this.bits + 3);
-                        DROPBITS(this.bits);
+                    else if (here.val == 17) {
+                        NEEDBITS(here.bits + 3);
+                        DROPBITS(here.bits);
                         len = 0;
                         copy = 3 + BITS(3);
                         DROPBITS(3);
                     }
                     else {
-                        NEEDBITS(this.bits + 7);
-                        DROPBITS(this.bits);
+                        NEEDBITS(here.bits + 7);
+                        DROPBITS(here.bits);
                         len = 0;
                         copy = 11 + BITS(7);
                         DROPBITS(7);
@@ -925,7 +969,16 @@ int flush;
             /* handle error breaks in while */
             if (state->mode == BAD) break;
 
-            /* build code tables */
+            /* check for end-of-block code (better have one) */
+            if (state->lens[256] == 0) {
+                strm->msg = (char *)"invalid code -- missing end-of-block";
+                state->mode = BAD;
+                break;
+            }
+
+            /* build code tables -- note: do not change the lenbits or distbits
+               values here (9 and 6) without reading the comments in inftrees.h
+               concerning the ENOUGH constants, which depend on those values */
             state->next = state->codes;
             state->lencode = (code const FAR *)(state->next);
             state->lenbits = 9;
@@ -946,88 +999,102 @@ int flush;
                 break;
             }
             Tracev((stderr, "inflate:       codes ok\n"));
+            state->mode = LEN_;
+            if (flush == Z_TREES) goto inf_leave;
+        case LEN_:
             state->mode = LEN;
         case LEN:
             if (have >= 6 && left >= 258) {
                 RESTORE();
                 inflate_fast(strm, out);
                 LOAD();
+                if (state->mode == TYPE)
+                    state->back = -1;
                 break;
             }
+            state->back = 0;
             for (;;) {
-                this = state->lencode[BITS(state->lenbits)];
-                if ((unsigned)(this.bits) <= bits) break;
+                here = state->lencode[BITS(state->lenbits)];
+                if ((unsigned)(here.bits) <= bits) break;
                 PULLBYTE();
             }
-            if (this.op && (this.op & 0xf0) == 0) {
-                last = this;
+            if (here.op && (here.op & 0xf0) == 0) {
+                last = here;
                 for (;;) {
-                    this = state->lencode[last.val +
+                    here = state->lencode[last.val +
                             (BITS(last.bits + last.op) >> last.bits)];
-                    if ((unsigned)(last.bits + this.bits) <= bits) break;
+                    if ((unsigned)(last.bits + here.bits) <= bits) break;
                     PULLBYTE();
                 }
                 DROPBITS(last.bits);
+                state->back += last.bits;
             }
-            DROPBITS(this.bits);
-            state->length = (unsigned)this.val;
-            if ((int)(this.op) == 0) {
-                Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
+            DROPBITS(here.bits);
+            state->back += here.bits;
+            state->length = (unsigned)here.val;
+            if ((int)(here.op) == 0) {
+                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
                         "inflate:         literal '%c'\n" :
-                        "inflate:         literal 0x%02x\n", this.val));
+                        "inflate:         literal 0x%02x\n", here.val));
                 state->mode = LIT;
                 break;
             }
-            if (this.op & 32) {
+            if (here.op & 32) {
                 Tracevv((stderr, "inflate:         end of block\n"));
+                state->back = -1;
                 state->mode = TYPE;
                 break;
             }
-            if (this.op & 64) {
+            if (here.op & 64) {
                 strm->msg = (char *)"invalid literal/length code";
                 state->mode = BAD;
                 break;
             }
-            state->extra = (unsigned)(this.op) & 15;
+            state->extra = (unsigned)(here.op) & 15;
             state->mode = LENEXT;
         case LENEXT:
             if (state->extra) {
                 NEEDBITS(state->extra);
                 state->length += BITS(state->extra);
                 DROPBITS(state->extra);
+                state->back += state->extra;
             }
             Tracevv((stderr, "inflate:         length %u\n", state->length));
+            state->was = state->length;
             state->mode = DIST;
         case DIST:
             for (;;) {
-                this = state->distcode[BITS(state->distbits)];
-                if ((unsigned)(this.bits) <= bits) break;
+                here = state->distcode[BITS(state->distbits)];
+                if ((unsigned)(here.bits) <= bits) break;
                 PULLBYTE();
             }
-            if ((this.op & 0xf0) == 0) {
-                last = this;
+            if ((here.op & 0xf0) == 0) {
+                last = here;
                 for (;;) {
-                    this = state->distcode[last.val +
+                    here = state->distcode[last.val +
                             (BITS(last.bits + last.op) >> last.bits)];
-                    if ((unsigned)(last.bits + this.bits) <= bits) break;
+                    if ((unsigned)(last.bits + here.bits) <= bits) break;
                     PULLBYTE();
                 }
                 DROPBITS(last.bits);
+                state->back += last.bits;
             }
-            DROPBITS(this.bits);
-            if (this.op & 64) {
+            DROPBITS(here.bits);
+            state->back += here.bits;
+            if (here.op & 64) {
                 strm->msg = (char *)"invalid distance code";
                 state->mode = BAD;
                 break;
             }
-            state->offset = (unsigned)this.val;
-            state->extra = (unsigned)(this.op) & 15;
+            state->offset = (unsigned)here.val;
+            state->extra = (unsigned)(here.op) & 15;
             state->mode = DISTEXT;
         case DISTEXT:
             if (state->extra) {
                 NEEDBITS(state->extra);
                 state->offset += BITS(state->extra);
                 DROPBITS(state->extra);
+                state->back += state->extra;
             }
 #ifdef INFLATE_STRICT
             if (state->offset > state->dmax) {
@@ -1036,11 +1103,6 @@ int flush;
                 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:
@@ -1048,12 +1110,32 @@ int flush;
             copy = out - left;
             if (state->offset > copy) {         /* copy from window */
                 copy = state->offset - copy;
-                if (copy > state->write) {
-                    copy -= state->write;
+                if (copy > state->whave) {
+                    if (state->sane) {
+                        strm->msg = (char *)"invalid distance too far back";
+                        state->mode = BAD;
+                        break;
+                    }
+#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
+                    Trace((stderr, "inflate.c too far\n"));
+                    copy -= state->whave;
+                    if (copy > state->length) copy = state->length;
+                    if (copy > left) copy = left;
+                    left -= copy;
+                    state->length -= copy;
+                    do {
+                        *put++ = 0;
+                    } while (--copy);
+                    if (state->length == 0) state->mode = LEN;
+                    break;
+#endif
+                }
+                if (copy > state->wnext) {
+                    copy -= state->wnext;
                     from = state->window + (state->wsize - copy);
                 }
                 else
-                    from = state->window + (state->write - copy);
+                    from = state->window + (state->wnext - copy);
                 if (copy > state->length) copy = state->length;
             }
             else {                              /* copy from output */
@@ -1146,7 +1228,8 @@ int flush;
         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);
+                      (state->mode == TYPE ? 128 : 0) +
+                      (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0);
     if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
         ret = Z_BUF_ERROR;
     return ret;
@@ -1366,3 +1449,32 @@ z_streamp source;
     dest->state = (struct internal_state FAR *)copy;
     return Z_OK;
 }
+
+int ZEXPORT inflateUndermine(strm, subvert)
+z_streamp strm;
+int subvert;
+{
+    struct inflate_state FAR *state;
+
+    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    state->sane = !subvert;
+#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
+    return Z_OK;
+#else
+    state->sane = 1;
+    return Z_DATA_ERROR;
+#endif
+}
+
+long ZEXPORT inflateMark(strm)
+z_streamp strm;
+{
+    struct inflate_state FAR *state;
+
+    if (strm == Z_NULL || strm->state == Z_NULL) return -1L << 16;
+    state = (struct inflate_state FAR *)strm->state;
+    return ((long)(state->back) << 16) +
+        (state->mode == COPY ? state->length :
+            (state->mode == MATCH ? state->was - state->length : 0));
+}
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/external/zlib/inflate.h alien-rc4/src//engine/external/zlib/inflate.h
--- teeworlds-b177-r50edfd37-source/src//engine/external/zlib/inflate.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/external/zlib/inflate.h	2012-06-14 23:57:39.000000000 +0200
@@ -1,5 +1,5 @@
 /* inflate.h -- internal inflate state definition
- * Copyright (C) 1995-2004 Mark Adler
+ * Copyright (C) 1995-2009 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -32,11 +32,13 @@ typedef enum {
         TYPE,       /* i: waiting for type bits, including last-flag bit */
         TYPEDO,     /* i: same, but skip check to exit inflate on new block */
         STORED,     /* i: waiting for stored size (length and complement) */
+        COPY_,      /* i/o: same as COPY below, but only first time in */
         COPY,       /* i/o: waiting for input or output to copy stored block */
         TABLE,      /* i: waiting for dynamic block table lengths */
         LENLENS,    /* i: waiting for code length code lengths */
         CODELENS,   /* i: waiting for length/lit and distance code lengths */
-            LEN,        /* i: waiting for length/lit code */
+            LEN_,       /* i: same as LEN below, but only first time in */
+            LEN,        /* i: waiting for length/lit/eob code */
             LENEXT,     /* i: waiting for length extra bits */
             DIST,       /* i: waiting for distance code */
             DISTEXT,    /* i: waiting for distance extra bits */
@@ -53,19 +55,21 @@ typedef enum {
 /*
     State transitions between above modes -
 
-    (most modes can go to the BAD or MEM mode -- not shown for clarity)
+    (most modes can go to BAD or MEM on error -- not shown for clarity)
 
     Process header:
-        HEAD -> (gzip) or (zlib)
-        (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
-        NAME -> COMMENT -> HCRC -> TYPE
+        HEAD -> (gzip) or (zlib) or (raw)
+        (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT ->
+                  HCRC -> TYPE
         (zlib) -> DICTID or TYPE
         DICTID -> DICT -> TYPE
+        (raw) -> TYPEDO
     Read deflate blocks:
-            TYPE -> STORED or TABLE or LEN or CHECK
-            STORED -> COPY -> TYPE
-            TABLE -> LENLENS -> CODELENS -> LEN
-    Read deflate codes:
+            TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK
+            STORED -> COPY_ -> COPY -> TYPE
+            TABLE -> LENLENS -> CODELENS -> LEN_
+            LEN_ -> LEN
+    Read deflate codes in fixed or dynamic block:
                 LEN -> LENEXT or LIT or TYPE
                 LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
                 LIT -> LEN
@@ -73,7 +77,7 @@ typedef enum {
         CHECK -> LENGTH -> DONE
  */
 
-/* state maintained between inflate() calls.  Approximately 7K bytes. */
+/* state maintained between inflate() calls.  Approximately 10K bytes. */
 struct inflate_state {
     inflate_mode mode;          /* current inflate mode */
     int last;                   /* true if processing last block */
@@ -88,7 +92,7 @@ struct inflate_state {
     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 wnext;             /* window write index */
     unsigned char FAR *window;  /* allocated sliding window, if needed */
         /* bit accumulator */
     unsigned long hold;         /* input bit accumulator */
@@ -112,4 +116,7 @@ struct inflate_state {
     unsigned short lens[320];   /* temporary storage for code lengths */
     unsigned short work[288];   /* work area for code table building */
     code codes[ENOUGH];         /* space for code tables */
+    int sane;                   /* if false, allow invalid distance too far */
+    int back;                   /* bits back of last unprocessed length/lit */
+    unsigned was;               /* initial length of match */
 };
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/external/zlib/inftrees.c alien-rc4/src//engine/external/zlib/inftrees.c
--- teeworlds-b177-r50edfd37-source/src//engine/external/zlib/inftrees.c	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/external/zlib/inftrees.c	2012-06-14 23:57:39.000000000 +0200
@@ -1,5 +1,5 @@
 /* inftrees.c -- generate Huffman trees for efficient decoding
- * Copyright (C) 1995-2005 Mark Adler
+ * Copyright (C) 1995-2010 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -9,7 +9,7 @@
 #define MAXBITS 15
 
 const char inflate_copyright[] =
-   " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
+   " inflate 1.2.5 Copyright 1995-2010 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
@@ -29,7 +29,7 @@ const char inflate_copyright[] =
    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)
+int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work)
 codetype type;
 unsigned short FAR *lens;
 unsigned codes;
@@ -50,7 +50,7 @@ unsigned short FAR *work;
     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 here;                  /* table entry for duplication */
     code FAR *next;             /* next available space in table */
     const unsigned short FAR *base;     /* base value table to use */
     const unsigned short FAR *extra;    /* extra bits table to use */
@@ -62,7 +62,7 @@ unsigned short FAR *work;
         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};
+        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 73, 195};
     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,
@@ -115,15 +115,15 @@ unsigned short FAR *work;
         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;
+        here.op = (unsigned char)64;    /* invalid code marker */
+        here.bits = (unsigned char)1;
+        here.val = (unsigned short)0;
+        *(*table)++ = here;             /* make a table to force an error */
+        *(*table)++ = here;
         *bits = 1;
         return 0;     /* no symbols, but wait for decoding to report error */
     }
-    for (min = 1; min <= MAXBITS; min++)
+    for (min = 1; min < max; min++)
         if (count[min] != 0) break;
     if (root < min) root = min;
 
@@ -166,11 +166,10 @@ unsigned short FAR *work;
        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.
+       provided *table space.  It is checked for LENS and DIST tables against
+       the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
+       the initial root table size constants.  See the comments in inftrees.h
+       for more information.
 
        sym increments through all symbols, and the loop terminates when
        all codes of length max, i.e. all codes, have been processed.  This
@@ -209,24 +208,25 @@ unsigned short FAR *work;
     mask = used - 1;            /* mask for comparing low */
 
     /* check available table space */
-    if (type == LENS && used >= ENOUGH - MAXD)
+    if ((type == LENS && used >= ENOUGH_LENS) ||
+        (type == DISTS && used >= ENOUGH_DISTS))
         return 1;
 
     /* process all codes and make table entries */
     for (;;) {
         /* create table entry */
-        this.bits = (unsigned char)(len - drop);
+        here.bits = (unsigned char)(len - drop);
         if ((int)(work[sym]) < end) {
-            this.op = (unsigned char)0;
-            this.val = work[sym];
+            here.op = (unsigned char)0;
+            here.val = work[sym];
         }
         else if ((int)(work[sym]) > end) {
-            this.op = (unsigned char)(extra[work[sym]]);
-            this.val = base[work[sym]];
+            here.op = (unsigned char)(extra[work[sym]]);
+            here.val = base[work[sym]];
         }
         else {
-            this.op = (unsigned char)(32 + 64);         /* end of block */
-            this.val = 0;
+            here.op = (unsigned char)(32 + 64);         /* end of block */
+            here.val = 0;
         }
 
         /* replicate for those indices with low len bits equal to huff */
@@ -235,7 +235,7 @@ unsigned short FAR *work;
         min = fill;                 /* save offset to next table */
         do {
             fill -= incr;
-            next[(huff >> drop) + fill] = this;
+            next[(huff >> drop) + fill] = here;
         } while (fill != 0);
 
         /* backwards increment the len-bit code huff */
@@ -277,7 +277,8 @@ unsigned short FAR *work;
 
             /* check for enough space */
             used += 1U << curr;
-            if (type == LENS && used >= ENOUGH - MAXD)
+            if ((type == LENS && used >= ENOUGH_LENS) ||
+                (type == DISTS && used >= ENOUGH_DISTS))
                 return 1;
 
             /* point entry in root table to sub-table */
@@ -295,20 +296,20 @@ unsigned short FAR *work;
        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;
+    here.op = (unsigned char)64;                /* invalid code marker */
+    here.bits = (unsigned char)(len - drop);
+    here.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;
+            here.bits = (unsigned char)len;
         }
 
         /* put invalid code marker in table */
-        next[huff >> drop] = this;
+        next[huff >> drop] = here;
 
         /* backwards increment the len-bit code huff */
         incr = 1U << (len - 1);
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/external/zlib/inftrees.h alien-rc4/src//engine/external/zlib/inftrees.h
--- teeworlds-b177-r50edfd37-source/src//engine/external/zlib/inftrees.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/external/zlib/inftrees.h	2012-06-14 23:57:39.000000000 +0200
@@ -1,5 +1,5 @@
 /* inftrees.h -- header to use inftrees.c
- * Copyright (C) 1995-2005 Mark Adler
+ * Copyright (C) 1995-2005, 2010 Mark Adler
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -35,21 +35,28 @@ typedef struct {
     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
+/* Maximum size of the dynamic table.  The maximum number of code structures is
+   1444, which is the sum of 852 for literal/length codes and 592 for distance
+   codes.  These values were found by exhaustive searches using the program
+   examples/enough.c found in the zlib distribtution.  The arguments to that
+   program are the number of symbols, the initial root table size, and the
+   maximum bit length of a code.  "enough 286 9 15" for literal/length codes
+   returns returns 852, and "enough 30 6 15" for distance codes returns 592.
+   The initial root table size (9 or 6) is found in the fifth argument of the
+   inflate_table() calls in inflate.c and infback.c.  If the root table size is
+   changed, then these maximum sizes would be need to be recalculated and
+   updated. */
+#define ENOUGH_LENS 852
+#define ENOUGH_DISTS 592
+#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS)
 
-/* Type of code to build for inftable() */
+/* Type of code to build for inflate_table() */
 typedef enum {
     CODES,
     LENS,
     DISTS
 } codetype;
 
-extern int inflate_table OF((codetype type, unsigned short FAR *lens,
+int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens,
                              unsigned codes, code FAR * FAR *table,
                              unsigned FAR *bits, unsigned short FAR *work));
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/external/zlib/trees.c alien-rc4/src//engine/external/zlib/trees.c
--- teeworlds-b177-r50edfd37-source/src//engine/external/zlib/trees.c	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/external/zlib/trees.c	2012-06-14 23:57:39.000000000 +0200
@@ -1,5 +1,6 @@
 /* trees.c -- output deflated data using Huffman coding
- * Copyright (C) 1995-2005 Jean-loup Gailly
+ * Copyright (C) 1995-2010 Jean-loup Gailly
+ * detect_data_type() function provided freely by Cosmin Truta, 2006
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -152,7 +153,7 @@ local void send_all_trees OF((deflate_st
                               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 int  detect_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));
@@ -203,12 +204,12 @@ local void send_bits(s, value, length)
      * unused bits in value.
      */
     if (s->bi_valid > (int)Buf_size - length) {
-        s->bi_buf |= (value << s->bi_valid);
+        s->bi_buf |= (ush)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_buf |= (ush)value << s->bi_valid;
         s->bi_valid += length;
     }
 }
@@ -218,12 +219,12 @@ local void 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);\
+    s->bi_buf |= (ush)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_buf |= (ush)(value) << s->bi_valid;\
     s->bi_valid += len;\
   }\
 }
@@ -250,11 +251,13 @@ local void tr_static_init()
     if (static_init_done) return;
 
     /* For some embedded targets, global variables are not initialized: */
+#ifdef NO_INIT_GLOBAL_POINTERS
     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;
+#endif
 
     /* Initialize the mapping length (0..255) -> length code (0..28) */
     length = 0;
@@ -348,13 +351,14 @@ void gen_trees_header()
                 static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
     }
 
-    fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
+    fprintf(header, "const uch ZLIB_INTERNAL _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");
+    fprintf(header,
+        "const uch ZLIB_INTERNAL _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));
@@ -379,7 +383,7 @@ void gen_trees_header()
 /* ===========================================================================
  * Initialize the tree data structures for a new zlib stream.
  */
-void _tr_init(s)
+void ZLIB_INTERNAL _tr_init(s)
     deflate_state *s;
 {
     tr_static_init();
@@ -864,13 +868,13 @@ local void send_all_trees(s, lcodes, dco
 /* ===========================================================================
  * Send a stored block
  */
-void _tr_stored_block(s, buf, stored_len, eof)
+void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)
     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 */
+    int last;         /* one if this is the last block for a file */
 {
-    send_bits(s, (STORED_BLOCK<<1)+eof, 3);  /* send block type */
+    send_bits(s, (STORED_BLOCK<<1)+last, 3);    /* send block type */
 #ifdef DEBUG
     s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
     s->compressed_len += (stored_len + 4) << 3;
@@ -889,7 +893,7 @@ void _tr_stored_block(s, buf, stored_len
  * To simplify the code, we assume the worst case of last real code encoded
  * on one bit only.
  */
-void _tr_align(s)
+void ZLIB_INTERNAL _tr_align(s)
     deflate_state *s;
 {
     send_bits(s, STATIC_TREES<<1, 3);
@@ -918,11 +922,11 @@ void _tr_align(s)
  * 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)
+void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)
     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 */
+    int last;         /* one 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 */
@@ -931,8 +935,8 @@ void _tr_flush_block(s, buf, stored_len,
     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);
+        if (s->strm->data_type == Z_UNKNOWN)
+            s->strm->data_type = detect_data_type(s);
 
         /* Construct the literal and distance trees */
         build_tree(s, (tree_desc *)(&(s->l_desc)));
@@ -978,20 +982,20 @@ void _tr_flush_block(s, buf, stored_len,
          * 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);
+        _tr_stored_block(s, buf, stored_len, last);
 
 #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);
+        send_bits(s, (STATIC_TREES<<1)+last, 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_bits(s, (DYN_TREES<<1)+last, 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);
@@ -1005,21 +1009,21 @@ void _tr_flush_block(s, buf, stored_len,
      */
     init_block(s);
 
-    if (eof) {
+    if (last) {
         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));
+           s->compressed_len-7*last));
 }
 
 /* ===========================================================================
  * Save the match info and tally the frequency counts. Return true if
  * the current block must be flushed.
  */
-int _tr_tally (s, dist, lc)
+int ZLIB_INTERNAL _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) */
@@ -1118,24 +1122,45 @@ local void compress_block(s, ltree, dtre
 }
 
 /* ===========================================================================
- * 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.
+ * Check if the data type is TEXT or BINARY, using the following algorithm:
+ * - TEXT if the two conditions below are satisfied:
+ *    a) There are no non-portable control characters belonging to the
+ *       "black list" (0..6, 14..25, 28..31).
+ *    b) There is at least one printable character belonging to the
+ *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
+ * - BINARY otherwise.
+ * - The following partially-portable control characters form a
+ *   "gray list" that is ignored in this detection algorithm:
+ *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  * IN assertion: the fields Freq of dyn_ltree are set.
  */
-local void set_data_type(s)
+local int detect_data_type(s)
     deflate_state *s;
 {
+    /* black_mask is the bit mask of black-listed bytes
+     * set bits 0..6, 14..25, and 28..31
+     * 0xf3ffc07f = binary 11110011111111111100000001111111
+     */
+    unsigned long black_mask = 0xf3ffc07fUL;
     int n;
 
-    for (n = 0; n < 9; n++)
+    /* Check for non-textual ("black-listed") bytes. */
+    for (n = 0; n <= 31; n++, black_mask >>= 1)
+        if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0))
+            return Z_BINARY;
+
+    /* Check for textual ("white-listed") bytes. */
+    if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0
+            || s->dyn_ltree[13].Freq != 0)
+        return Z_TEXT;
+    for (n = 32; n < LITERALS; 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;
+            return Z_TEXT;
+
+    /* There are no "black-listed" or "white-listed" bytes:
+     * this stream either is empty or has tolerated ("gray-listed") bytes only.
+     */
+    return Z_BINARY;
 }
 
 /* ===========================================================================
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/external/zlib/trees.h alien-rc4/src//engine/external/zlib/trees.h
--- teeworlds-b177-r50edfd37-source/src//engine/external/zlib/trees.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/external/zlib/trees.h	2012-06-14 23:57:39.000000000 +0200
@@ -70,7 +70,7 @@ local const ct_data static_dtree[D_CODES
 {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
 };
 
-const uch _dist_code[DIST_CODE_LEN] = {
+const uch ZLIB_INTERNAL _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,
@@ -99,7 +99,7 @@ const uch _dist_code[DIST_CODE_LEN] = {
 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
 };
 
-const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
+const uch ZLIB_INTERNAL _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,
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/external/zlib/uncompr.c alien-rc4/src//engine/external/zlib/uncompr.c
--- teeworlds-b177-r50edfd37-source/src//engine/external/zlib/uncompr.c	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/external/zlib/uncompr.c	2012-06-14 23:57:39.000000000 +0200
@@ -1,5 +1,5 @@
 /* uncompr.c -- decompress a memory buffer
- * Copyright (C) 1995-2003 Jean-loup Gailly.
+ * Copyright (C) 1995-2003, 2010 Jean-loup Gailly.
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -16,8 +16,6 @@
    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
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/external/zlib/VERSION alien-rc4/src//engine/external/zlib/VERSION
--- teeworlds-b177-r50edfd37-source/src//engine/external/zlib/VERSION	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/external/zlib/VERSION	2012-06-14 23:57:39.000000000 +0200
@@ -1 +1 @@
-1.2.3
+1.2.5
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/external/zlib/zconf.h alien-rc4/src//engine/external/zlib/zconf.h
--- teeworlds-b177-r50edfd37-source/src//engine/external/zlib/zconf.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/external/zlib/zconf.h	2012-06-14 23:57:39.000000000 +0200
@@ -1,5 +1,5 @@
 /* zconf.h -- configuration of the zlib compression library
- * Copyright (C) 1995-2005 Jean-loup Gailly.
+ * Copyright (C) 1995-2010 Jean-loup Gailly.
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -11,52 +11,124 @@
 /*
  * If you *really* need a unique prefix for all types and library functions,
  * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
+ * Even better than compiling with -DZ_PREFIX would be to use configure to set
+ * this permanently in zconf.h using "./configure --zprefix".
  */
-#ifdef Z_PREFIX
-#  define deflateInit_          z_deflateInit_
+#ifdef Z_PREFIX     /* may be set to #if 1 by ./configure */
+
+/* all linked symbols */
+#  define _dist_code            z__dist_code
+#  define _length_code          z__length_code
+#  define _tr_align             z__tr_align
+#  define _tr_flush_block       z__tr_flush_block
+#  define _tr_init              z__tr_init
+#  define _tr_stored_block      z__tr_stored_block
+#  define _tr_tally             z__tr_tally
+#  define adler32               z_adler32
+#  define adler32_combine       z_adler32_combine
+#  define adler32_combine64     z_adler32_combine64
+#  define compress              z_compress
+#  define compress2             z_compress2
+#  define compressBound         z_compressBound
+#  define crc32                 z_crc32
+#  define crc32_combine         z_crc32_combine
+#  define crc32_combine64       z_crc32_combine64
 #  define deflate               z_deflate
+#  define deflateBound          z_deflateBound
+#  define deflateCopy           z_deflateCopy
 #  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 deflateInit_          z_deflateInit_
 #  define deflateParams         z_deflateParams
-#  define deflateBound          z_deflateBound
 #  define deflatePrime          z_deflatePrime
+#  define deflateReset          z_deflateReset
+#  define deflateSetDictionary  z_deflateSetDictionary
+#  define deflateSetHeader      z_deflateSetHeader
+#  define deflateTune           z_deflateTune
+#  define deflate_copyright     z_deflate_copyright
+#  define get_crc_table         z_get_crc_table
+#  define gz_error              z_gz_error
+#  define gz_intmax             z_gz_intmax
+#  define gz_strwinerror        z_gz_strwinerror
+#  define gzbuffer              z_gzbuffer
+#  define gzclearerr            z_gzclearerr
+#  define gzclose               z_gzclose
+#  define gzclose_r             z_gzclose_r
+#  define gzclose_w             z_gzclose_w
+#  define gzdirect              z_gzdirect
+#  define gzdopen               z_gzdopen
+#  define gzeof                 z_gzeof
+#  define gzerror               z_gzerror
+#  define gzflush               z_gzflush
+#  define gzgetc                z_gzgetc
+#  define gzgets                z_gzgets
+#  define gzoffset              z_gzoffset
+#  define gzoffset64            z_gzoffset64
+#  define gzopen                z_gzopen
+#  define gzopen64              z_gzopen64
+#  define gzprintf              z_gzprintf
+#  define gzputc                z_gzputc
+#  define gzputs                z_gzputs
+#  define gzread                z_gzread
+#  define gzrewind              z_gzrewind
+#  define gzseek                z_gzseek
+#  define gzseek64              z_gzseek64
+#  define gzsetparams           z_gzsetparams
+#  define gztell                z_gztell
+#  define gztell64              z_gztell64
+#  define gzungetc              z_gzungetc
+#  define gzwrite               z_gzwrite
+#  define inflate               z_inflate
+#  define inflateBack           z_inflateBack
+#  define inflateBackEnd        z_inflateBackEnd
+#  define inflateBackInit_      z_inflateBackInit_
+#  define inflateCopy           z_inflateCopy
+#  define inflateEnd            z_inflateEnd
+#  define inflateGetHeader      z_inflateGetHeader
 #  define inflateInit2_         z_inflateInit2_
+#  define inflateInit_          z_inflateInit_
+#  define inflateMark           z_inflateMark
+#  define inflatePrime          z_inflatePrime
+#  define inflateReset          z_inflateReset
+#  define inflateReset2         z_inflateReset2
 #  define 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 inflateUndermine      z_inflateUndermine
+#  define inflate_copyright     z_inflate_copyright
+#  define inflate_fast          z_inflate_fast
+#  define inflate_table         z_inflate_table
 #  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 zcalloc               z_zcalloc
+#  define zcfree                z_zcfree
+#  define zlibCompileFlags      z_zlibCompileFlags
+#  define zlibVersion           z_zlibVersion
 
+/* all zlib typedefs in zlib.h and zconf.h */
+#  define Byte                  z_Byte
+#  define Bytef                 z_Bytef
 #  define alloc_func            z_alloc_func
+#  define charf                 z_charf
 #  define free_func             z_free_func
+#  define gzFile                z_gzFile
+#  define gz_header             z_gz_header
+#  define gz_headerp            z_gz_headerp
 #  define in_func               z_in_func
+#  define intf                  z_intf
 #  define out_func              z_out_func
-#  define 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 uLong                 z_uLong
 #  define uLongf                z_uLongf
-#  define voidpf                z_voidpf
 #  define voidp                 z_voidp
+#  define voidpc                z_voidpc
+#  define voidpf                z_voidpf
+
+/* all zlib structs in zlib.h and zconf.h */
+#  define gz_header_s           z_gz_header_s
+#  define internal_state        z_internal_state
+
 #endif
 
 #if defined(__MSDOS__) && !defined(MSDOS)
@@ -284,49 +356,73 @@ typedef uLong FAR uLongf;
    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 HAVE_UNISTD_H    /* may be set to #if 1 by ./configure */
+#  define Z_HAVE_UNISTD_H
+#endif
+
+#ifdef STDC
+#  include <sys/types.h>    /* for off_t */
+#endif
+
+/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and
+ * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even
+ * though the former does not conform to the LFS document), but considering
+ * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as
+ * equivalently requesting no 64-bit operations
+ */
+#if -_LARGEFILE64_SOURCE - -1 == 1
+#  undef _LARGEFILE64_SOURCE
+#endif
+
+#if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE)
+#  include <unistd.h>       /* for SEEK_* and off_t */
 #  ifdef VMS
-#    include <unixio.h>   /* for off_t */
+#    include <unixio.h>     /* for off_t */
+#  endif
+#  ifndef z_off_t
+#    define z_off_t 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(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
+#  define z_off64_t off64_t
+#else
+#  define z_off64_t z_off_t
+#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")
+  #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 -rupN teeworlds-b177-r50edfd37-source/src//engine/external/zlib/zconf.in.h alien-rc4/src//engine/external/zlib/zconf.in.h
--- teeworlds-b177-r50edfd37-source/src//engine/external/zlib/zconf.in.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/external/zlib/zconf.in.h	1970-01-01 01:00:00.000000000 +0100
@@ -1,332 +0,0 @@
-/* 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 -rupN teeworlds-b177-r50edfd37-source/src//engine/external/zlib/zlib.h alien-rc4/src//engine/external/zlib/zlib.h
--- teeworlds-b177-r50edfd37-source/src//engine/external/zlib/zlib.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/external/zlib/zlib.h	2012-06-14 23:57:39.000000000 +0200
@@ -1,7 +1,7 @@
 /* zlib.h -- interface of the 'zlib' general purpose compression library
-  version 1.2.3, July 18th, 2005
+  version 1.2.5, April 19th, 2010
 
-  Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler
+  Copyright (C) 1995-2010 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
@@ -37,41 +37,44 @@
 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
+#define ZLIB_VERSION "1.2.5"
+#define ZLIB_VERNUM 0x1250
+#define ZLIB_VER_MAJOR 1
+#define ZLIB_VER_MINOR 2
+#define ZLIB_VER_REVISION 5
+#define ZLIB_VER_SUBREVISION 0
+
+/*
+    The 'zlib' compression library provides in-memory compression and
+  decompression functions, including integrity checks of the uncompressed data.
+  This version of the library supports only one compression method (deflation)
+  but other algorithms will be added later and will have the same stream
+  interface.
+
+    Compression can be done in a single step if the buffers are large enough,
+  or can be done by repeated calls of the compression function.  In the latter
+  case, the application must provide more input and/or consume the output
   (providing more output space) before each call.
 
-     The compressed data format used by default by the in-memory functions is
+    The 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
+    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.
+    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
+    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.
+    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));
@@ -126,45 +129,45 @@ typedef struct gz_header_s {
 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
+     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.
+     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).
+     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_PARTIAL_FLUSH 1
 #define Z_SYNC_FLUSH    2
 #define Z_FULL_FLUSH    3
 #define Z_FINISH        4
 #define Z_BLOCK         5
+#define Z_TREES         6
 /* Allowed flush values; see deflate() and inflate() below for details */
 
 #define Z_OK            0
@@ -176,8 +179,8 @@ typedef gz_header FAR *gz_headerp;
 #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.
+/* 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
@@ -207,119 +210,140 @@ typedef gz_header FAR *gz_headerp;
 #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.
+   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.
+     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).
+   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,
+     deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_STREAM_ERROR if level is not a valid compression level, or
    Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
-   with the version assumed by the caller (ZLIB_VERSION).
-   msg is set to null if there is no error message.  deflateInit does not
-   perform any compression: this will be done by deflate().
+   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
+  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
+    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
+    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.
+    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.
+    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.
+    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
+  decide how much data to accumulate before producing output, in order to
   maximize compression.
 
     If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
   flushed to the output buffer and the output is aligned on a byte boundary, so
-  that the decompressor can get all input data available so far. (In particular
-  avail_in is zero after the call if enough output space has been provided
-  before the call.)  Flushing may degrade compression for some compression
-  algorithms and so it should be used only when necessary.
+  that the decompressor can get all input data available so far.  (In
+  particular avail_in is zero after the call if enough output space has been
+  provided before the call.) Flushing may degrade compression for some
+  compression algorithms and so it should be used only when necessary.  This
+  completes the current deflate block and follows it with an empty stored block
+  that is three bits plus filler bits to the next byte, followed by four bytes
+  (00 00 ff ff).
+
+    If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the
+  output buffer, but the output is not aligned to a byte boundary.  All of the
+  input data so far will be available to the decompressor, as for Z_SYNC_FLUSH.
+  This completes the current deflate block and follows it with an empty fixed
+  codes block that is 10 bits long.  This assures that enough bytes are output
+  in order for the decompressor to finish the block before the empty fixed code
+  block.
+
+    If flush is set to Z_BLOCK, a deflate block is completed and emitted, as
+  for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to
+  seven bits of the current block are held to be written as the next byte after
+  the next deflate block is completed.  In this case, the decompressor may not
+  be provided enough bits at this point in order to complete decompression of
+  the data provided so far to the compressor.  It may need to wait for the next
+  block to be emitted.  This is for advanced applications that need to control
+  the emission of deflate blocks.
 
     If flush is set to Z_FULL_FLUSH, all output is flushed as with
   Z_SYNC_FLUSH, and the compression state is reset so that decompression can
   restart from this point if previous compressed data has been damaged or if
-  random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
+  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).  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
+  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.
+  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
+  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.
+  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
+  if next_in or next_out was Z_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.
 */
@@ -328,13 +352,13 @@ ZEXTERN int ZEXPORT deflate OF((z_stream
 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.
+   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
+   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).
 */
 
@@ -342,10 +366,10 @@ ZEXTERN int ZEXPORT deflateEnd OF((z_str
 /*
 ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
 
-     Initializes the internal stream state for decompression. The fields
+     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
+   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
@@ -353,95 +377,108 @@ ZEXTERN int ZEXPORT inflateInit OF((z_st
 
      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.)
+   version assumed by the caller, or Z_STREAM_ERROR if the parameters are
+   invalid, such as a null pointer to the structure.  msg is set to null if
+   there is no error message.  inflateInit does not perform any decompression
+   apart from possibly reading the zlib header if present: actual decompression
+   will be done by inflate().  (So next_in and avail_in may be modified, but
+   next_out and avail_out are unused and unchanged.) The current implementation
+   of inflateInit() does not process any header information -- that is deferred
+   until inflate() is called.
 */
 
 
 ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
 /*
     inflate decompresses as much data as possible, and stops when the input
-  buffer becomes empty or the output buffer becomes full. It may introduce
+  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
+  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().
+    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.
+    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,
+  Z_BLOCK, or Z_TREES.  Z_SYNC_FLUSH requests that inflate() flush as much
+  output as possible to the output buffer.  Z_BLOCK requests that inflate()
+  stop if and when it gets to the next deflate block boundary.  When decoding
+  the zlib or gzip format, this will cause inflate() to return immediately
+  after the header and before the first block.  When doing a raw inflate,
+  inflate() will go ahead and process the first block, and will return when it
+  gets to the end of that block, or when it runs out of data.
 
     The Z_BLOCK option assists in appending to or combining deflate streams.
   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.
+  number of unused bits in the last byte taken from strm->next_in, plus 64 if
+  inflate() is currently decoding the last block in the deflate stream, plus
+  128 if inflate() returned immediately after decoding an end-of-block code or
+  decoding the complete header up to just before the first byte of the deflate
+  stream.  The end-of-block will not be indicated until all of the uncompressed
+  data from that block has been written to strm->next_out.  The number of
+  unused bits may in general be greater than seven, except when bit 7 of
+  data_type is set, in which case the number of unused bits will be less than
+  eight.  data_type is set as noted here every time inflate() returns for all
+  flush options, and so can be used to determine the amount of currently
+  consumed input in bits.
+
+    The Z_TREES option behaves as Z_BLOCK does, but it also returns when the
+  end of each deflate block header is reached, before any actual data in that
+  block is decoded.  This allows the caller to determine the length of the
+  deflate block header for later use in random access within a deflate block.
+  256 is added to the value of strm->data_type when inflate() returns
+  immediately after reaching the end of the deflate block header.
 
     inflate() should normally be called until it returns Z_STREAM_END or an
-  error. However if all decompression is to be performed in a single step
-  (a single call of inflate), the parameter flush should be set to
-  Z_FINISH. In this case all pending input is processed and all pending
-  output is flushed; avail_out must be large enough to hold all 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.
+  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
+  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.
+  because Z_BLOCK or Z_TREES 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
+  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() can decompress and check either zlib-wrapped or gzip-wrapped
+  deflate data.  The header type is detected automatically, if requested when
+  initializing with inflateInit2().  Any information contained in the gzip
+  header is not retained, 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
@@ -449,27 +486,28 @@ ZEXTERN int ZEXPORT inflate OF((z_stream
   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,
+  next_in or next_out was Z_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
+  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.
+  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.
+   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
+   was inconsistent.  In the error case, msg may be set but then points to a
    static string (which must not be deallocated).
 */
 
+
                         /* Advanced functions */
 
 /*
@@ -484,55 +522,57 @@ ZEXTERN int ZEXPORT deflateInit2 OF((z_s
                                      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.
+     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
+     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
+   (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
+     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
+     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
+   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.
+   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
+     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
+   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().
+   Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY.  Z_RLE is designed to be almost as
+   fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data.  The
+   strategy parameter only affects the compression ratio but not the
+   correctness of the compressed output even if it is not set appropriately.
+   Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler
+   decoder for special applications.
+
+     deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid
+   method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is
+   incompatible with the version assumed by the caller (ZLIB_VERSION).  msg is
+   set to null if there is no error message.  deflateInit2 does not perform any
+   compression: this will be done by deflate().
 */
 
 ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
@@ -540,37 +580,37 @@ ZEXTERN int ZEXPORT deflateSetDictionary
                                              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
+   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
+   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.
+   discarded, for example if the dictionary is larger than the window size
+   provided in deflateInit or deflateInit2.  Thus the strings most likely to be
+   useful should be put at the end of the dictionary, not at the front.  In
+   addition, the current implementation of deflate will use at most the window
+   size minus 262 bytes of the provided dictionary.
 
      Upon return of this function, strm->adler is set to the 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
+   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
+   parameter is invalid (e.g.  dictionary being Z_NULL) or the stream state is
    inconsistent (for example if deflate has already been called for this stream
-   or if the compression method is bsort). deflateSetDictionary does not
+   or if the compression method is bsort).  deflateSetDictionary does not
    perform any compression: this will be done by deflate().
 */
 
@@ -581,26 +621,26 @@ ZEXTERN int ZEXPORT deflateCopy OF((z_st
 
      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
+   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.
+   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
+   (such as zalloc being Z_NULL).  msg is left unchanged in both source and
    destination.
 */
 
 ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
 /*
      This function is equivalent to deflateEnd followed by deflateInit,
-   but does not free and reallocate all the internal compression state.
-   The stream will keep the same compression level and any other attributes
-   that may have been set by deflateInit2.
+   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).
+     deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent (such as zalloc or state being Z_NULL).
 */
 
 ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
@@ -610,18 +650,18 @@ ZEXTERN int ZEXPORT deflateParams OF((z_
      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().
+   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.
+   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.
+   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,
@@ -645,9 +685,10 @@ ZEXTERN uLong ZEXPORT deflateBound OF((z
                                        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().
+   deflation of sourceLen bytes.  It must be called after deflateInit() or
+   deflateInit2(), and after deflateSetHeader(), if used.  This would be used
+   to allocate an output buffer for deflation in a single pass, and so would be
+   called before deflate().
 */
 
 ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
@@ -655,21 +696,21 @@ ZEXTERN int ZEXPORT deflatePrime OF((z_s
                                      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.
+   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
+     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
+     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
@@ -682,11 +723,11 @@ ZEXTERN int ZEXPORT deflateSetHeader OF(
    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,
+     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
+     deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
    stream state was inconsistent.
 */
 
@@ -694,43 +735,50 @@ ZEXTERN int ZEXPORT deflateSetHeader OF(
 ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
                                      int  windowBits));
 
-     This is another version of inflateInit with an extra parameter. The
+     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
+   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
+   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,
+     windowBits can also be zero to request that inflate use the window size in
+   the zlib header of the compressed stream.
+
+     windowBits can also be -8..-15 for raw inflate.  In this case, -windowBits
+   determines the window size.  inflate() will then process raw deflate data,
    not looking for a zlib or gzip header, not generating a check value, and not
-   looking for any check values for comparison at the end of the stream. This
+   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
+   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
+   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
+     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.
+   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.)
+   memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
+   version assumed by the caller, or Z_STREAM_ERROR if the parameters are
+   invalid, such as a null pointer to the structure.  msg is set to null if
+   there is no error message.  inflateInit2 does not perform any decompression
+   apart from possibly reading the zlib header if present: actual decompression
+   will be done by inflate().  (So next_in and avail_in may be modified, but
+   next_out and avail_out are unused and unchanged.) The current implementation
+   of inflateInit2() does not process any header information -- that is
+   deferred until inflate() is called.
 */
 
 ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
@@ -738,8 +786,8 @@ ZEXTERN int ZEXPORT inflateSetDictionary
                                              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
+   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
@@ -748,26 +796,26 @@ ZEXTERN int ZEXPORT inflateSetDictionary
    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
+   parameter is invalid (e.g.  dictionary being Z_NULL) or the stream state is
    inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
-   expected one (incorrect adler32 value). inflateSetDictionary does not
+   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.
+     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,
@@ -782,18 +830,30 @@ ZEXTERN int ZEXPORT inflateCopy OF((z_st
 
      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
+   (such as zalloc being Z_NULL).  msg is left unchanged in both source and
    destination.
 */
 
 ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
 /*
      This function is equivalent to inflateEnd followed by inflateInit,
-   but does not free and reallocate all the internal decompression state.
-   The stream will keep attributes that may have been set by inflateInit2.
+   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).
+     inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent (such as zalloc or state being Z_NULL).
+*/
+
+ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm,
+                                      int windowBits));
+/*
+     This function is the same as inflateReset, but it also permits changing
+   the wrap and window size requests.  The windowBits parameter is interpreted
+   the same as it is for inflateInit2.
+
+     inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent (such as zalloc or state being Z_NULL), or if
+   the windowBits parameter is invalid.
 */
 
 ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
@@ -801,54 +861,87 @@ ZEXTERN int ZEXPORT inflatePrime OF((z_s
                                      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.
+   that this function is used to start inflating at a bit position in the
+   middle of a byte.  The provided bits will be used before any bytes are used
+   from next_in.  This function should only be used with raw inflate, and
+   should be used before the first inflate() call after inflateInit2() or
+   inflateReset().  bits must be less than or equal to 16, and that many of the
+   least significant bits of value will be inserted in the input.
+
+     If bits is negative, then the input stream bit buffer is emptied.  Then
+   inflatePrime() can be called again to put bits in the buffer.  This is used
+   to clear out bits leftover after feeding inflate a block description prior
+   to feeding inflate codes.
 
-      inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
+     inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
    stream state was inconsistent.
 */
 
+ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm));
+/*
+     This function returns two values, one in the lower 16 bits of the return
+   value, and the other in the remaining upper bits, obtained by shifting the
+   return value down 16 bits.  If the upper value is -1 and the lower value is
+   zero, then inflate() is currently decoding information outside of a block.
+   If the upper value is -1 and the lower value is non-zero, then inflate is in
+   the middle of a stored block, with the lower value equaling the number of
+   bytes from the input remaining to copy.  If the upper value is not -1, then
+   it is the number of bits back from the current bit position in the input of
+   the code (literal or length/distance pair) currently being processed.  In
+   that case the lower value is the number of bytes already emitted for that
+   code.
+
+     A code is being processed if inflate is waiting for more input to complete
+   decoding of the code, or if it has completed decoding but is waiting for
+   more output space to write the literal or match data.
+
+     inflateMark() is used to mark locations in the input data for random
+   access, which may be at bit positions, and to note those cases where the
+   output of a code may span boundaries of random access blocks.  The current
+   location in the input stream can be determined from avail_in and data_type
+   as noted in the description for the Z_BLOCK flush parameter for inflate.
+
+     inflateMark returns the value noted above or -1 << 16 if the provided
+   source stream state was inconsistent.
+*/
+
 ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
                                          gz_headerp head));
 /*
-      inflateGetHeader() requests that gzip header information be stored in the
+     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.
+   no gzip header information forthcoming.  Note that Z_BLOCK or Z_TREES can be
+   used to force inflate() to return immediately after header processing is
+   complete and before any actual data is decompressed.
 
-      The text, time, xflags, and os fields are filled in with the gzip header
+     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
+   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
+   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
+     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
+     inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
    stream state was inconsistent.
 */
 
@@ -869,9 +962,9 @@ ZEXTERN int ZEXPORT inflateBackInit OF((
      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.
+   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 *));
@@ -891,15 +984,15 @@ ZEXTERN int ZEXPORT inflateBack OF((z_st
      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.
+   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
+   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
@@ -925,7 +1018,7 @@ ZEXTERN int ZEXPORT inflateBack OF((z_st
    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].
+   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
@@ -935,15 +1028,15 @@ ZEXTERN int ZEXPORT inflateBack OF((z_st
      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.
+   if in() or out() returned an error, Z_DATA_ERROR if there was a format error
+   in the deflate stream (in which case strm->msg is set to indicate the nature
+   of the error), or Z_STREAM_ERROR if the stream was not properly initialized.
+   In the case of Z_BUF_ERROR, an input or output error can be distinguished
+   using strm->next_in which will be Z_NULL only if in() returned an error.  If
+   strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning
+   non-zero.  (in() will always be called before out(), so strm->next_in is
+   assured to be defined if out() returns non-zero.) Note that inflateBack()
+   cannot return Z_OK.
 */
 
 ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
@@ -999,23 +1092,22 @@ ZEXTERN uLong ZEXPORT zlibCompileFlags O
                         /* 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.
+     The following utility functions are implemented on top of the basic
+   stream-oriented functions.  To simplify the interface, some default options
+   are assumed (compression level and memory usage, standard memory allocation
+   functions).  The source code of these utility functions can be modified if
+   you need special options.
 */
 
 ZEXTERN int ZEXPORT compress OF((Bytef *dest,   uLongf *destLen,
                                  const Bytef *source, uLong sourceLen));
 /*
      Compresses the source buffer into the destination buffer.  sourceLen is
-   the byte length of the source buffer. Upon entry, destLen is the total
-   size of the destination buffer, which must be at least the value returned
-   by compressBound(sourceLen). Upon exit, destLen is the actual size of the
+   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.
@@ -1025,11 +1117,11 @@ ZEXTERN int ZEXPORT compress2 OF((Bytef
                                   const Bytef *source, uLong sourceLen,
                                   int level));
 /*
-     Compresses the source buffer into the destination buffer. The 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
+   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
+   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
@@ -1040,22 +1132,20 @@ ZEXTERN int ZEXPORT compress2 OF((Bytef
 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.
+   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.
+   the byte length of the source buffer.  Upon entry, destLen is the total size
+   of the destination buffer, which must be large enough to hold the entire
+   uncompressed data.  (The size of the uncompressed data must have been saved
+   previously by the compressor and transmitted to the decompressor by some
+   mechanism outside the scope of this compression library.) Upon exit, destLen
+   is the actual size of the uncompressed buffer.
 
      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
@@ -1063,136 +1153,199 @@ ZEXTERN int ZEXPORT uncompress OF((Bytef
 */
 
 
-typedef voidp gzFile;
+                        /* gzip file access functions */
+
+/*
+     This library supports reading and writing files in gzip (.gz) format with
+   an interface similar to that of stdio, using the functions that start with
+   "gz".  The gzip format is different from the zlib format.  gzip is a gzip
+   wrapper, documented in RFC 1952, wrapped around a deflate stream.
+*/
+
+typedef voidp gzFile;       /* opaque gzip file descriptor */
 
-ZEXTERN gzFile ZEXPORT gzopen  OF((const char *path, const char *mode));
 /*
-     Opens a gzip (.gz) file for reading or writing. The mode parameter
-   is as in fopen ("rb" or "wb") but can also include a compression level
-   ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
-   Huffman only compression as in "wb1h", or 'R' for run-length encoding
-   as in "wb1R". (See the description of deflateInit2 for more information
-   about the strategy parameter.)
+ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
+
+     Opens a gzip (.gz) file for reading or writing.  The mode parameter is as
+   in fopen ("rb" or "wb") but can also include a compression level ("wb9") or
+   a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only
+   compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F'
+   for fixed code compression as in "wb9F".  (See the description of
+   deflateInit2 for more information about the strategy parameter.) Also "a"
+   can be used instead of "w" to request that the gzip stream that will be
+   written be appended to the file.  "+" will result in an error, since reading
+   and writing to the same gzip file is not supported.
 
      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.
+     gzopen returns NULL if the file could not be opened, if there was
+   insufficient memory to allocate the gzFile state, or if an invalid mode was
+   specified (an 'r', 'w', or 'a' was not provided, or '+' was provided).
+   errno can be checked to determine if the reason gzopen failed was that the
+   file could not be opened.
+*/
+
+ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
+/*
+     gzdopen associates a gzFile with the file descriptor fd.  File descriptors
+   are obtained from calls like open, dup, creat, pipe or fileno (if the file
+   has been previously opened with fopen).  The mode parameter is as in gzopen.
+
+     The next call of gzclose on the returned gzFile will also close the file
+   descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor
+   fd.  If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd,
+   mode);.  The duplicated descriptor should be saved to avoid a leak, since
+   gzdopen does not close fd if it fails.
+
+     gzdopen returns NULL if there was insufficient memory to allocate the
+   gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not
+   provided, or '+' was provided), or if fd is -1.  The file descriptor is not
+   used until the next gz* read, write, seek, or close operation, so gzdopen
+   will not detect if fd is invalid (unless fd is -1).
+*/
+
+ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size));
+/*
+     Set the internal buffer size used by this library's functions.  The
+   default buffer size is 8192 bytes.  This function must be called after
+   gzopen() or gzdopen(), and before any other calls that read or write the
+   file.  The buffer memory allocation is always deferred to the first read or
+   write.  Two buffers are allocated, either both of the specified size when
+   writing, or one of the specified size and the other twice that size when
+   reading.  A larger buffer size of, for example, 64K or 128K bytes will
+   noticeably increase the speed of decompression (reading).
+
+     The new buffer size also affects the maximum length for gzprintf().
+
+     gzbuffer() returns 0 on success, or -1 on failure, such as being called
+   too late.
 */
 
 ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
 /*
-     Dynamically update the compression level or strategy. See the description
+     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));
+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). */
+     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.
+
+     After reaching the end of a gzip stream in the input, gzread will continue
+   to read, looking for another gzip stream, or failing that, reading the rest
+   of the input file directly without decompression.  The entire input file
+   will be read if gzread is called until it returns less than the requested
+   len.
 
-ZEXTERN int ZEXPORT    gzwrite OF((gzFile file,
-                                   voidpc buf, unsigned len));
+     gzread returns the number of uncompressed bytes actually read, less than
+   len for end of file, or -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).
+   gzwrite returns the number of uncompressed bytes written or 0 in case of
+   error.
 */
 
-ZEXTERN int ZEXPORTVA   gzprintf OF((gzFile file, const char *format, ...));
+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.
+     Converts, formats, and writes the arguments to the compressed file under
+   control of the format string, as in fprintf.  gzprintf returns the number of
+   uncompressed bytes actually written, or 0 in case of error.  The number of
+   uncompressed bytes written is limited to 8191, or one less than the buffer
+   size given to gzbuffer().  The caller should assure that this limit is not
+   exceeded.  If it is exceeded, then gzprintf() will return an error (0) with
+   nothing written.  In this case, there may also be a buffer overflow with
+   unpredictable consequences, which is possible only if zlib was compiled with
+   the insecure functions sprintf() or vsprintf() because the secure snprintf()
+   or vsnprintf() functions were not available.  This can be determined using
+   zlibCompileFlags().
 */
 
 ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
 /*
-      Writes the given null-terminated string to the compressed file, excluding
+     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.
+
+     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.
+     Reads bytes from the compressed file until len-1 characters are read, or a
+   newline character is read and transferred to buf, or an end-of-file
+   condition is encountered.  If any characters are read or if len == 1, the
+   string is terminated with a null character.  If no characters are read due
+   to an end-of-file or len < 1, then the buffer is left untouched.
+
+     gzgets returns buf which is a null-terminated string, or it returns NULL
+   for end-of-file or in case of error.  If there was an error, the contents at
+   buf are indeterminate.
 */
 
-ZEXTERN int ZEXPORT    gzputc OF((gzFile file, int c));
+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.
+     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));
+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.
+     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));
+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().
+     Push one character back onto the stream to be read as the first character
+   on the next read.  At least one character of push-back is allowed.
+   gzungetc() returns the character pushed, or -1 on failure.  gzungetc() will
+   fail if c is -1, and may fail if a character has been pushed but not read
+   yet.  If gzungetc is used immediately after gzopen or gzdopen, at least the
+   output buffer size of pushed characters is allowed.  (See gzbuffer above.)
+   The pushed character will be discarded if the stream is repositioned with
+   gzseek() or gzrewind().
 */
 
-ZEXTERN int ZEXPORT    gzflush OF((gzFile file, int flush));
+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.
+     Flushes all pending output into the compressed file.  The parameter flush
+   is as in the deflate() function.  The return value is the zlib error number
+   (see function gzerror below).  gzflush is only permitted when writing.
+
+     If the flush parameter is Z_FINISH, the remaining data is written and the
+   gzip stream is completed in the output.  If gzwrite() is called again, a new
+   gzip stream will be started in the output.  gzread() is able to read such
+   concatented gzip streams.
+
+     gzflush should be called only when strictly necessary because it will
+   degrade compression if called too often.
 */
 
-ZEXTERN z_off_t ZEXPORT    gzseek OF((gzFile file,
-                                      z_off_t offset, int whence));
 /*
-      Sets the starting position for the next gzread or gzwrite on the
-   given compressed file. The offset represents a number of bytes in the
-   uncompressed data stream. The whence parameter is defined as in lseek(2);
+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
+   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
+     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.
@@ -1202,68 +1355,127 @@ ZEXTERN int ZEXPORT    gzrewind OF((gzFi
 /*
      Rewinds the given file. This function is supported only for reading.
 
-   gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
+     gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
 */
 
+/*
 ZEXTERN z_off_t ZEXPORT    gztell OF((gzFile file));
+
+     Returns the starting position for the next gzread or gzwrite on the given
+   compressed file.  This position represents a number of bytes in the
+   uncompressed data stream, and is zero when starting, even if appending or
+   reading a gzip stream from the middle of a file using gzdopen().
+
+     gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
+*/
+
 /*
-     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.
+ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file));
 
-   gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
+     Returns the current offset in the file being read or written.  This offset
+   includes the count of bytes that precede the gzip stream, for example when
+   appending or when using gzdopen() for reading.  When reading, the offset
+   does not include as yet unused buffered input.  This information can be used
+   for a progress indicator.  On error, gzoffset() returns -1.
 */
 
 ZEXTERN int ZEXPORT gzeof OF((gzFile file));
 /*
-     Returns 1 when EOF has previously been detected reading the given
-   input stream, otherwise zero.
+     Returns true (1) if the end-of-file indicator has been set while reading,
+   false (0) otherwise.  Note that the end-of-file indicator is set only if the
+   read tried to go past the end of the input, but came up short.  Therefore,
+   just like feof(), gzeof() may return false even if there is no more data to
+   read, in the event that the last read request was for the exact number of
+   bytes remaining in the input file.  This will happen if the input file size
+   is an exact multiple of the buffer size.
+
+     If gzeof() returns true, then the read functions will return no more data,
+   unless the end-of-file indicator is reset by gzclearerr() and the input file
+   has grown since the previous end of file was detected.
 */
 
 ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
 /*
-     Returns 1 if file is being read directly without decompression, otherwise
-   zero.
+     Returns true (1) if file is being copied directly while reading, or false
+   (0) if file is a gzip stream being decompressed.  This state can change from
+   false to true while reading the input file if the end of a gzip stream is
+   reached, but is followed by data that is not another gzip stream.
+
+     If the input file is empty, gzdirect() will return true, since the input
+   does not contain a gzip stream.
+
+     If gzdirect() is used immediately after gzopen() or gzdopen() it will
+   cause buffers to be allocated to allow reading the file to determine if it
+   is a gzip file.  Therefore if gzbuffer() is used, it should be called before
+   gzdirect().
 */
 
 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).
+     Flushes all pending output if necessary, closes the compressed file and
+   deallocates the (de)compression state.  Note that once file is closed, you
+   cannot call gzerror with file, since its structures have been deallocated.
+   gzclose must not be called more than once on the same file, just as free
+   must not be called more than once on the same allocation.
+
+     gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a
+   file operation error, or Z_OK on success.
+*/
+
+ZEXTERN int ZEXPORT gzclose_r OF((gzFile file));
+ZEXTERN int ZEXPORT gzclose_w OF((gzFile file));
+/*
+     Same as gzclose(), but gzclose_r() is only for use when reading, and
+   gzclose_w() is only for use when writing or appending.  The advantage to
+   using these instead of gzclose() is that they avoid linking in zlib
+   compression or decompression code that is not used when only reading or only
+   writing respectively.  If gzclose() is used, then both compression and
+   decompression code will be included the application when linking to a static
+   zlib library.
 */
 
 ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
 /*
-     Returns the error message for the last error which occurred on the
-   given compressed file. errnum is set to zlib error number. If an
-   error occurred in the file system and not in the compression library,
-   errnum is set to Z_ERRNO and the application may consult errno
-   to get the exact error code.
+     Returns the error message for the last error which occurred on the given
+   compressed file.  errnum is set to zlib error number.  If an error occurred
+   in the file system and not in the compression library, errnum is set to
+   Z_ERRNO and the application may consult errno to get the exact error code.
+
+     The application must not modify the returned string.  Future calls to
+   this function may invalidate the previously returned string.  If file is
+   closed, then the string previously returned by gzerror will no longer be
+   available.
+
+     gzerror() should be used to distinguish errors from end-of-file for those
+   functions above that do not distinguish those cases in their return values.
 */
 
 ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
 /*
-     Clears the error and end-of-file flags for file. This is analogous to the
-   clearerr() function in stdio. This is useful for continuing to read a gzip
+     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.
+   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:
+   return the updated checksum.  If buf is Z_NULL, this function returns the
+   required initial value for the checksum.
+
+     An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
+   much faster.
+
+   Usage example:
 
      uLong adler = adler32(0L, Z_NULL, 0);
 
@@ -1273,9 +1485,10 @@ ZEXTERN uLong ZEXPORT adler32 OF((uLong
      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
@@ -1285,9 +1498,11 @@ ZEXTERN uLong ZEXPORT adler32_combine OF
 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.
+   updated CRC-32.  If buf is Z_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);
@@ -1298,9 +1513,9 @@ ZEXTERN uLong ZEXPORT crc32   OF((uLong
      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
@@ -1339,16 +1554,57 @@ ZEXTERN int ZEXPORT inflateBackInit_ OF(
         inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
 #define inflateBackInit(strm, windowBits, window) \
         inflateBackInit_((strm), (windowBits), (window), \
-        ZLIB_VERSION, sizeof(z_stream))
+                                            ZLIB_VERSION, sizeof(z_stream))
+
+/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or
+ * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if
+ * both are true, the application gets the *64 functions, and the regular
+ * functions are changed to 64 bits) -- in case these are set on systems
+ * without large file support, _LFS64_LARGEFILE must also be true
+ */
+#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
+   ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
+   ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));
+   ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile));
+   ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile));
+   ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t));
+   ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t));
+#endif
 
+#if !defined(ZLIB_INTERNAL) && _FILE_OFFSET_BITS-0 == 64 && _LFS64_LARGEFILE-0
+#  define gzopen gzopen64
+#  define gzseek gzseek64
+#  define gztell gztell64
+#  define gzoffset gzoffset64
+#  define adler32_combine adler32_combine64
+#  define crc32_combine crc32_combine64
+#  ifdef _LARGEFILE64_SOURCE
+     ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
+     ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int));
+     ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile));
+     ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile));
+     ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));
+     ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));
+#  endif
+#else
+   ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *));
+   ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int));
+   ZEXTERN z_off_t ZEXPORT gztell OF((gzFile));
+   ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile));
+   ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t));
+   ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t));
+#endif
 
+/* hack for buggy compilers */
 #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
-    struct internal_state {int dummy;}; /* hack for buggy compilers */
+    struct internal_state {int dummy;};
 #endif
 
+/* undocumented functions */
 ZEXTERN const char   * ZEXPORT zError           OF((int));
-ZEXTERN int            ZEXPORT inflateSyncPoint OF((z_streamp z));
+ZEXTERN int            ZEXPORT inflateSyncPoint OF((z_streamp));
 ZEXTERN const uLongf * ZEXPORT get_crc_table    OF((void));
+ZEXTERN int            ZEXPORT inflateUndermine OF((z_streamp, int));
 
 #ifdef __cplusplus
 }
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/external/zlib/zutil.c alien-rc4/src//engine/external/zlib/zutil.c
--- teeworlds-b177-r50edfd37-source/src//engine/external/zlib/zutil.c	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/external/zlib/zutil.c	2012-06-14 23:57:39.000000000 +0200
@@ -1,5 +1,5 @@
 /* zutil.c -- target dependent utility functions for the compression library
- * Copyright (C) 1995-2005 Jean-loup Gailly.
+ * Copyright (C) 1995-2005, 2010 Jean-loup Gailly.
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -34,25 +34,25 @@ uLong ZEXPORT zlibCompileFlags()
     uLong flags;
 
     flags = 0;
-    switch (sizeof(uInt)) {
+    switch ((int)(sizeof(uInt))) {
     case 2:     break;
     case 4:     flags += 1;     break;
     case 8:     flags += 2;     break;
     default:    flags += 3;
     }
-    switch (sizeof(uLong)) {
+    switch ((int)(sizeof(uLong))) {
     case 2:     break;
     case 4:     flags += 1 << 2;        break;
     case 8:     flags += 2 << 2;        break;
     default:    flags += 3 << 2;
     }
-    switch (sizeof(voidpf)) {
+    switch ((int)(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)) {
+    switch ((int)(sizeof(z_off_t))) {
     case 2:     break;
     case 4:     flags += 1 << 6;        break;
     case 8:     flags += 2 << 6;        break;
@@ -117,9 +117,9 @@ uLong ZEXPORT zlibCompileFlags()
 #  ifndef verbose
 #    define verbose 0
 #  endif
-int z_verbose = verbose;
+int ZLIB_INTERNAL z_verbose = verbose;
 
-void z_error (m)
+void ZLIB_INTERNAL z_error (m)
     char *m;
 {
     fprintf(stderr, "%s\n", m);
@@ -146,7 +146,7 @@ const char * ZEXPORT zError(err)
 
 #ifndef HAVE_MEMCPY
 
-void zmemcpy(dest, source, len)
+void ZLIB_INTERNAL zmemcpy(dest, source, len)
     Bytef* dest;
     const Bytef* source;
     uInt  len;
@@ -157,7 +157,7 @@ void zmemcpy(dest, source, len)
     } while (--len != 0);
 }
 
-int zmemcmp(s1, s2, len)
+int ZLIB_INTERNAL zmemcmp(s1, s2, len)
     const Bytef* s1;
     const Bytef* s2;
     uInt  len;
@@ -170,7 +170,7 @@ int zmemcmp(s1, s2, len)
     return 0;
 }
 
-void zmemzero(dest, len)
+void ZLIB_INTERNAL zmemzero(dest, len)
     Bytef* dest;
     uInt  len;
 {
@@ -213,7 +213,7 @@ local ptr_table table[MAX_PTR];
  * a protected system like OS/2. Use Microsoft C instead.
  */
 
-voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
+voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size)
 {
     voidpf buf = opaque; /* just to make some compilers happy */
     ulg bsize = (ulg)items*size;
@@ -237,7 +237,7 @@ voidpf zcalloc (voidpf opaque, unsigned
     return buf;
 }
 
-void  zcfree (voidpf opaque, voidpf ptr)
+void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr)
 {
     int n;
     if (*(ush*)&ptr != 0) { /* object < 64K */
@@ -272,13 +272,13 @@ void  zcfree (voidpf opaque, voidpf ptr)
 #  define _hfree   hfree
 #endif
 
-voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
+voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size)
 {
     if (opaque) opaque = 0; /* to make compiler happy */
     return _halloc((long)items, size);
 }
 
-void  zcfree (voidpf opaque, voidpf ptr)
+void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr)
 {
     if (opaque) opaque = 0; /* to make compiler happy */
     _hfree(ptr);
@@ -297,7 +297,7 @@ extern voidp  calloc OF((uInt items, uIn
 extern void   free   OF((voidpf ptr));
 #endif
 
-voidpf zcalloc (opaque, items, size)
+voidpf ZLIB_INTERNAL zcalloc (opaque, items, size)
     voidpf opaque;
     unsigned items;
     unsigned size;
@@ -307,7 +307,7 @@ voidpf zcalloc (opaque, items, size)
                               (voidpf)calloc(items, size);
 }
 
-void  zcfree (opaque, ptr)
+void ZLIB_INTERNAL zcfree (opaque, ptr)
     voidpf opaque;
     voidpf ptr;
 {
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/external/zlib/zutil.h alien-rc4/src//engine/external/zlib/zutil.h
--- teeworlds-b177-r50edfd37-source/src//engine/external/zlib/zutil.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/external/zlib/zutil.h	2012-06-14 23:57:39.000000000 +0200
@@ -1,5 +1,5 @@
 /* zutil.h -- internal interface and configuration of the compression library
- * Copyright (C) 1995-2005 Jean-loup Gailly.
+ * Copyright (C) 1995-2010 Jean-loup Gailly.
  * For conditions of distribution and use, see copyright notice in zlib.h
  */
 
@@ -13,31 +13,21 @@
 #ifndef ZUTIL_H
 #define ZUTIL_H
 
-#define ZLIB_INTERNAL
+#if ((__GNUC__-0) * 10 + __GNUC_MINOR__-0 >= 33) && !defined(NO_VIZ)
+#  define ZLIB_INTERNAL __attribute__((visibility ("hidden")))
+#else
+#  define ZLIB_INTERNAL
+#endif
+
 #include "zlib.h"
 
 #ifdef STDC
-#  ifndef _WIN32_WCE
+#  if !(defined(_WIN32_WCE) && defined(_MSC_VER))
 #    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
@@ -89,7 +79,7 @@ extern const char * const z_errmsg[10];
 #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
 #  define OS_CODE  0x00
 #  if defined(__TURBOC__) || defined(__BORLANDC__)
-#    if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
+#    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 );
@@ -118,7 +108,7 @@ extern const char * const z_errmsg[10];
 #ifdef OS2
 #  define OS_CODE  0x06
 #  ifdef M_I86
-     #include <malloc.h>
+#    include <malloc.h>
 #  endif
 #endif
 
@@ -151,7 +141,7 @@ extern const char * const z_errmsg[10];
 #  define fdopen(fd,mode) NULL /* No fdopen() */
 #endif
 
-#if (defined(_MSC_VER) && (_MSC_VER > 600))
+#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX
 #  if defined(_WIN32_WCE)
 #    define fdopen(fd,mode) NULL /* No fdopen() */
 #    ifndef _PTRDIFF_T_DEFINED
@@ -163,6 +153,18 @@ extern const char * const z_errmsg[10];
 #  endif
 #endif
 
+#if defined(__BORLANDC__)
+  #pragma warn -8004
+  #pragma warn -8008
+  #pragma warn -8066
+#endif
+
+/* provide prototypes for these when building zlib without LFS */
+#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0
+    ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));
+    ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));
+#endif
+
         /* common defaults */
 
 #ifndef OS_CODE
@@ -197,7 +199,9 @@ extern const char * const z_errmsg[10];
 #  ifdef WIN32
      /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
 #    if !defined(vsnprintf) && !defined(NO_vsnprintf)
-#      define vsnprintf _vsnprintf
+#      if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 )
+#         define vsnprintf _vsnprintf
+#      endif
 #    endif
 #  endif
 #  ifdef __SASC
@@ -232,16 +236,16 @@ extern const char * const z_errmsg[10];
 #    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));
+   void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
+   int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
+   void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len));
 #endif
 
 /* Diagnostic functions */
 #ifdef DEBUG
 #  include <stdio.h>
-   extern int z_verbose;
-   extern void z_error    OF((char *m));
+   extern int ZLIB_INTERNAL z_verbose;
+   extern void ZLIB_INTERNAL z_error OF((char *m));
 #  define Assert(cond,msg) {if(!(cond)) z_error(msg);}
 #  define Trace(x) {if (z_verbose>=0) fprintf x ;}
 #  define Tracev(x) {if (z_verbose>0) fprintf x ;}
@@ -258,8 +262,9 @@ extern const char * const z_errmsg[10];
 #endif
 
 
-voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
-void   zcfree  OF((voidpf opaque, voidpf ptr));
+voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items,
+                        unsigned size));
+void ZLIB_INTERNAL zcfree  OF((voidpf opaque, voidpf ptr));
 
 #define ZALLOC(strm, items, size) \
            (*((strm)->zalloc))((strm)->opaque, (items), (size))
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/graphics.h alien-rc4/src//engine/graphics.h
--- teeworlds-b177-r50edfd37-source/src//engine/graphics.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/graphics.h	2012-06-14 23:57:39.000000000 +0200
@@ -5,6 +5,7 @@
 
 #include "kernel.h"
 
+
 class CImageInfo
 {
 public:
@@ -55,7 +56,8 @@ public:
 	*/
 	enum
 	{
-		TEXLOAD_NORESAMPLE=1,
+		TEXLOAD_NORESAMPLE = 1,
+		TEXLOAD_NOMIPMAPS = 2,
 	};
 
 	int ScreenWidth() const { return m_ScreenWidth; }
@@ -74,12 +76,15 @@ public:
 	virtual void BlendNone() = 0;
 	virtual void BlendNormal() = 0;
 	virtual void BlendAdditive() = 0;
+	virtual void WrapNormal() = 0;
+	virtual void WrapClamp() = 0;
 	virtual int MemoryUsage() const = 0;
 
-	virtual int LoadPNG(CImageInfo *pImg, const char *pFilename, int StorageType) =0;
+	virtual int LoadPNG(CImageInfo *pImg, const char *pFilename, int StorageType) = 0;
 	virtual int UnloadTexture(int Index) = 0;
 	virtual int LoadTextureRaw(int Width, int Height, int Format, const void *pData, int StoreFormat, int Flags) = 0;
 	virtual int LoadTexture(const char *pFilename, int StorageType, int StoreFormat, int Flags) = 0;
+	virtual int LoadTextureRawSub(int TextureID, int x, int y, int Width, int Height, int Format, const void *pData) = 0;
 	virtual void TextureSet(int TextureID) = 0;
 
 	struct CLineItem
@@ -131,13 +136,18 @@ public:
 	virtual int GetVideoModes(CVideoMode *pModes, int MaxModes) = 0;
 
 	virtual void Swap() = 0;
+
+	// syncronization
+	virtual void InsertSignal(class semaphore *pSemaphore) = 0;
+	virtual bool IsIdle() = 0;
+	virtual void WaitForIdle() = 0;
 };
 
 class IEngineGraphics : public IGraphics
 {
 	MACRO_INTERFACE("enginegraphics", 0)
 public:
-	virtual bool Init() = 0;
+	virtual int Init() = 0;
 	virtual void Shutdown() = 0;
 
 	virtual void Minimize() = 0;
@@ -149,5 +159,6 @@ public:
 };
 
 extern IEngineGraphics *CreateEngineGraphics();
+extern IEngineGraphics *CreateEngineGraphicsThreaded();
 
 #endif
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/server/server.cpp alien-rc4/src//engine/server/server.cpp
--- teeworlds-b177-r50edfd37-source/src//engine/server/server.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/server/server.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -19,6 +19,7 @@
 #include <engine/shared/econ.h>
 #include <engine/shared/filecollection.h>
 #include <engine/shared/mapchecker.h>
+#include <engine/shared/netban.h>
 #include <engine/shared/network.h>
 #include <engine/shared/packer.h>
 #include <engine/shared/protocol.h>
@@ -35,37 +36,48 @@
 	#include <windows.h>
 #endif
 
-static const char *StrLtrim(const char *pStr)
+static const char *StrUTF8Ltrim(const char *pStr)
 {
-	while(*pStr && *pStr >= 0 && *pStr <= 32)
-		pStr++;
-	return pStr;
-}
-
-static void StrRtrim(char *pStr)
-{
-	int i = str_length(pStr);
-	while(i >= 0)
+	while(*pStr)
 	{
-		if(pStr[i] < 0 || pStr[i] > 32)
-			break;
-		pStr[i] = 0;
-		i--;
+		const char *pStrOld = pStr;
+		int Code = str_utf8_decode(&pStr);
+
+		// check if unicode is not empty
+		if(Code > 0x20 && Code != 0xA0 && Code != 0x034F && (Code < 0x2000 || Code > 0x200F) && (Code < 0x2028 || Code > 0x202F) &&
+			(Code < 0x205F || Code > 0x2064) && (Code < 0x206A || Code > 0x206F) && (Code < 0xFE00 || Code > 0xFE0F) &&
+			Code != 0xFEFF && (Code < 0xFFF9 || Code > 0xFFFC))
+		{
+			return pStrOld;
+		}
 	}
+	return pStr;
 }
 
-
-static int StrAllnum(const char *pStr)
+static void StrUTF8Rtrim(char *pStr)
 {
-	while(*pStr)
+	const char *p = pStr;
+	const char *pEnd = 0;
+	while(*p)
 	{
-		if(!(*pStr >= '0' && *pStr <= '9'))
-			return 0;
-		pStr++;
+		const char *pStrOld = p;
+		int Code = str_utf8_decode(&p);
+
+		// check if unicode is not empty
+		if(Code > 0x20 && Code != 0xA0 && Code != 0x034F && (Code < 0x2000 || Code > 0x200F) && (Code < 0x2028 || Code > 0x202F) &&
+			(Code < 0x205F || Code > 0x2064) && (Code < 0x206A || Code > 0x206F) && (Code < 0xFE00 || Code > 0xFE0F) &&
+			Code != 0xFEFF && (Code < 0xFFF9 || Code > 0xFFFC))
+		{
+			pEnd = 0;
+		}
+		else if(pEnd == 0)
+			pEnd = pStrOld;
 	}
-	return 1;
+	if(pEnd != 0)
+		*(const_cast<char *>(pEnd)) = 0;
 }
 
+
 CSnapIDPool::CSnapIDPool()
 {
 	Reset();
@@ -154,6 +166,115 @@ void CSnapIDPool::FreeID(int ID)
 	}
 }
 
+
+void CServerBan::Init(IConsole *pConsole, IStorage *pStorage, CServer* pServer)
+{
+	CNetBan::Init(pConsole, pStorage);
+
+	m_pServer = pServer;
+
+	// overwrites base command, todo: improve this
+	Console()->Register("ban", "s?ir", CFGFLAG_SERVER|CFGFLAG_STORE, ConBanExt, this, "Ban player with ip/client id for x minutes for any reason");
+}
+
+template<class T>
+int CServerBan::BanExt(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason)
+{
+	// validate address
+	if(Server()->m_RconClientID >= 0 && Server()->m_RconClientID < MAX_CLIENTS &&
+		Server()->m_aClients[Server()->m_RconClientID].m_State != CServer::CClient::STATE_EMPTY)
+	{
+		if(NetMatch(pData, Server()->m_NetServer.ClientAddr(Server()->m_RconClientID)))
+		{
+			Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (you can't ban yourself)");
+			return -1;
+		}
+
+		for(int i = 0; i < MAX_CLIENTS; ++i)
+		{
+			if(i == Server()->m_RconClientID || Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY)
+				continue;
+
+			if(Server()->m_aClients[i].m_Authed >= Server()->m_RconAuthLevel && NetMatch(pData, Server()->m_NetServer.ClientAddr(i)))
+			{
+				Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (command denied)");
+				return -1;
+			}
+		}
+	}
+	else if(Server()->m_RconClientID == IServer::RCON_CID_VOTE)
+	{
+		for(int i = 0; i < MAX_CLIENTS; ++i)
+		{
+			if(Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY)
+				continue;
+
+			if(Server()->m_aClients[i].m_Authed != CServer::AUTHED_NO && NetMatch(pData, Server()->m_NetServer.ClientAddr(i)))
+			{
+				Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (command denied)");
+				return -1;
+			}
+		}
+	}
+
+	int Result = Ban(pBanPool, pData, Seconds, pReason);
+	if(Result != 0)
+		return Result;
+
+	// drop banned clients
+	typename T::CDataType Data = *pData;
+	for(int i = 0; i < MAX_CLIENTS; ++i)
+	{
+		if(Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY)
+			continue;
+
+		if(NetMatch(&Data, Server()->m_NetServer.ClientAddr(i)))
+		{
+			CNetHash NetHash(&Data);
+			char aBuf[256];
+			MakeBanInfo(pBanPool->Find(&Data, &NetHash), aBuf, sizeof(aBuf), MSGTYPE_PLAYER);
+			Server()->m_NetServer.Drop(i, aBuf);
+		}
+	}
+
+	return Result;
+}
+
+int CServerBan::BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason)
+{
+	return BanExt(&m_BanAddrPool, pAddr, Seconds, pReason);
+}
+
+int CServerBan::BanRange(const CNetRange *pRange, int Seconds, const char *pReason)
+{
+	if(pRange->IsValid())
+		return BanExt(&m_BanRangePool, pRange, Seconds, pReason);
+
+	Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (invalid range)");
+	return -1;
+}
+
+void CServerBan::ConBanExt(IConsole::IResult *pResult, void *pUser)
+{
+	CServerBan *pThis = static_cast<CServerBan *>(pUser);
+
+	const char *pStr = pResult->GetString(0);
+	int Minutes = pResult->NumArguments()>1 ? clamp(pResult->GetInteger(1), 0, 44640) : 30;
+	const char *pReason = pResult->NumArguments()>2 ? pResult->GetString(2) : "No reason given";
+
+	if(StrAllnum(pStr))
+	{
+		int ClientID = str_toint(pStr);
+		if(ClientID < 0 || ClientID >= MAX_CLIENTS || pThis->Server()->m_aClients[ClientID].m_State == CServer::CClient::STATE_EMPTY)
+			pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (invalid client id)");
+		else
+			pThis->BanAddr(pThis->Server()->m_NetServer.ClientAddr(ClientID), Minutes*60, pReason);
+	}
+	else
+		ConBan(pResult, pUser);
+}
+
+
 void CServer::CClient::Reset()
 {
 	// reset input
@@ -183,7 +304,7 @@ CServer::CServer() : m_DemoRecorder(&m_S
 
 	m_MapReload = 0;
 
-	m_RconClientID = -1;
+	m_RconClientID = IServer::RCON_CID_SERV;
 	m_RconAuthLevel = AUTHED_ADMIN;
 
 	Init();
@@ -195,8 +316,8 @@ int CServer::TrySetClientName(int Client
 	char aTrimmedName[64];
 
 	// trim the name
-	str_copy(aTrimmedName, StrLtrim(pName), sizeof(aTrimmedName));
-	StrRtrim(aTrimmedName);
+	str_copy(aTrimmedName, StrUTF8Ltrim(pName), sizeof(aTrimmedName));
+	StrUTF8Rtrim(aTrimmedName);
 
 	// check if new and old name are the same
 	if(m_aClients[ClientID].m_aName[0] && str_comp(m_aClients[ClientID].m_aName, aTrimmedName) == 0)
@@ -324,6 +445,11 @@ int CServer::Init()
 	return 0;
 }
 
+void CServer::SetRconCID(int ClientID)
+{
+	m_RconClientID = ClientID;
+}
+
 bool CServer::IsAuthed(int ClientID)
 {
 	return m_aClients[ClientID].m_Authed;
@@ -346,11 +472,7 @@ int CServer::GetClientInfo(int ClientID,
 void CServer::GetClientAddr(int ClientID, char *pAddrStr, int Size)
 {
 	if(ClientID >= 0 && ClientID < MAX_CLIENTS && m_aClients[ClientID].m_State == CClient::STATE_INGAME)
-	{
-		NETADDR Addr = m_NetServer.ClientAddr(ClientID);
-		Addr.port = 0;
-		net_addr_str(&Addr, pAddrStr, Size);
-	}
+		net_addr_str(m_NetServer.ClientAddr(ClientID), pAddrStr, Size, false);
 }
 
 
@@ -390,6 +512,11 @@ bool CServer::ClientIngame(int ClientID)
 	return ClientID >= 0 && ClientID < MAX_CLIENTS && m_aClients[ClientID].m_State == CServer::CClient::STATE_INGAME;
 }
 
+int CServer::MaxClients() const
+{
+	return m_NetServer.MaxClients();
+}
+
 int CServer::SendMsg(CMsgPacker *pMsg, int Flags, int ClientID)
 {
 	return SendMsgEx(pMsg, Flags, ClientID, false);
@@ -591,9 +718,8 @@ int CServer::DelClientCallback(int Clien
 {
 	CServer *pThis = (CServer *)pUser;
 
-	NETADDR Addr = pThis->m_NetServer.ClientAddr(ClientID);
 	char aAddrStr[NETADDR_MAXSTRSIZE];
-	net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr));
+	net_addr_str(pThis->m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true);
 	char aBuf[256];
 	str_format(aBuf, sizeof(aBuf), "client dropped. cid=%d addr=%s reason='%s'", ClientID, aAddrStr,	pReason);
 	pThis->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aBuf);
@@ -672,7 +798,7 @@ void CServer::SendRconCmdRem(const ICons
 void CServer::UpdateClientRconCommands()
 {
 	int ClientID = Tick() % MAX_CLIENTS;
-		
+
 	if(m_aClients[ClientID].m_State != CClient::STATE_EMPTY && m_aClients[ClientID].m_Authed)
 	{
 		int ConsoleAccessLevel = m_aClients[ClientID].m_Authed == AUTHED_ADMIN ? IConsole::ACCESS_LEVEL_ADMIN : IConsole::ACCESS_LEVEL_MOD;
@@ -687,7 +813,6 @@ void CServer::UpdateClientRconCommands()
 void CServer::ProcessClientPacket(CNetChunk *pPacket)
 {
 	int ClientID = pPacket->m_ClientID;
-	NETADDR Addr;
 	CUnpacker Unpacker;
 	Unpacker.Reset(pPacket->m_pData, pPacket->m_DataSize);
 
@@ -766,9 +891,8 @@ void CServer::ProcessClientPacket(CNetCh
 		{
 			if(m_aClients[ClientID].m_State == CClient::STATE_CONNECTING)
 			{
-				Addr = m_NetServer.ClientAddr(ClientID);
 				char aAddrStr[NETADDR_MAXSTRSIZE];
-				net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr));
+				net_addr_str(m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true);
 
 				char aBuf[256];
 				str_format(aBuf, sizeof(aBuf), "player is ready. ClientID=%x addr=%s", ClientID, aAddrStr);
@@ -782,9 +906,8 @@ void CServer::ProcessClientPacket(CNetCh
 		{
 			if(m_aClients[ClientID].m_State == CClient::STATE_READY && GameServer()->IsClientReady(ClientID))
 			{
-				Addr = m_NetServer.ClientAddr(ClientID);
 				char aAddrStr[NETADDR_MAXSTRSIZE];
-				net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr));
+				net_addr_str(m_NetServer.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true);
 
 				char aBuf[256];
 				str_format(aBuf, sizeof(aBuf), "player has entered the game. ClientID=%x addr=%s", ClientID, aAddrStr);
@@ -857,9 +980,9 @@ void CServer::ProcessClientPacket(CNetCh
 				m_RconClientID = ClientID;
 				m_RconAuthLevel = m_aClients[ClientID].m_Authed;
 				Console()->SetAccessLevel(m_aClients[ClientID].m_Authed == AUTHED_ADMIN ? IConsole::ACCESS_LEVEL_ADMIN : IConsole::ACCESS_LEVEL_MOD);
-				Console()->ExecuteLine(pCmd);
+				Console()->ExecuteLineFlag(pCmd, CFGFLAG_SERVER);
 				Console()->SetAccessLevel(IConsole::ACCESS_LEVEL_ADMIN);
-				m_RconClientID = -1;
+				m_RconClientID = IServer::RCON_CID_SERV;
 				m_RconAuthLevel = AUTHED_ADMIN;
 			}
 		}
@@ -918,10 +1041,7 @@ void CServer::ProcessClientPacket(CNetCh
 						if(!g_Config.m_SvRconBantime)
 							m_NetServer.Drop(ClientID, "Too many remote console authentication tries");
 						else
-						{
-							NETADDR Addr = m_NetServer.ClientAddr(ClientID);
-							BanAdd(Addr, g_Config.m_SvRconBantime*60, "Too many remote console authentication tries");
-						}
+							m_ServerBan.BanAddr(m_NetServer.ClientAddr(ClientID), g_Config.m_SvRconBantime*60, "Too many remote console authentication tries");
 					}
 				}
 				else
@@ -965,7 +1085,7 @@ void CServer::ProcessClientPacket(CNetCh
 	}
 }
 
-void CServer::SendServerInfo(NETADDR *pAddr, int Token)
+void CServer::SendServerInfo(const NETADDR *pAddr, int Token)
 {
 	CNetChunk Packet;
 	CPacker p;
@@ -1034,33 +1154,10 @@ void CServer::UpdateServerInfo()
 	for(int i = 0; i < MAX_CLIENTS; ++i)
 	{
 		if(m_aClients[i].m_State != CClient::STATE_EMPTY)
-		{
-			NETADDR Addr = m_NetServer.ClientAddr(i);
-			SendServerInfo(&Addr, -1);
-		}
+			SendServerInfo(m_NetServer.ClientAddr(i), -1);
 	}
 }
 
-int CServer::BanAdd(NETADDR Addr, int Seconds, const char *pReason)
-{
-	Addr.port = 0;
-	char aAddrStr[128];
-	net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr));
-	char aBuf[256];
-	if(Seconds)
-		str_format(aBuf, sizeof(aBuf), "banned %s for %d minutes", aAddrStr, Seconds/60);
-	else
-		str_format(aBuf, sizeof(aBuf), "banned %s for life", aAddrStr);
-	Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf);
-
-	return m_NetServer.BanAdd(Addr, Seconds, pReason);
-}
-
-int CServer::BanRemove(NETADDR Addr)
-{
-	return m_NetServer.BanRemove(Addr);
-}
-
 
 void CServer::PumpNetwork()
 {
@@ -1087,6 +1184,7 @@ void CServer::PumpNetwork()
 			ProcessClientPacket(&Packet);
 	}
 
+	m_ServerBan.Update();
 	m_Econ.Update();
 }
 
@@ -1137,7 +1235,7 @@ int CServer::LoadMap(const char *pMapNam
 	str_copy(m_aCurrentMap, pMapName, sizeof(m_aCurrentMap));
 	//map_set(df);
 
-	// load compelate map into memory for download
+	// load complete map into memory for download
 	{
 		IOHANDLE File = Storage()->OpenFile(aBuf, IOFLAG_READ, IStorage::TYPE_ALL);
 		m_CurrentMapSize = (int)io_length(File);
@@ -1173,7 +1271,7 @@ int CServer::Run()
 
 	// start server
 	NETADDR BindAddr;
-	if(g_Config.m_SvBindaddr[0] && net_host_lookup(g_Config.m_SvBindaddr, &BindAddr, NETTYPE_ALL) == 0)
+	if(g_Config.m_Bindaddr[0] && net_host_lookup(g_Config.m_Bindaddr, &BindAddr, NETTYPE_ALL) == 0)
 	{
 		// sweet!
 		BindAddr.port = g_Config.m_SvPort;
@@ -1185,15 +1283,16 @@ int CServer::Run()
 		BindAddr.port = g_Config.m_SvPort;
 	}
 
-	if(!m_NetServer.Open(BindAddr, g_Config.m_SvMaxClients, g_Config.m_SvMaxClientsPerIP, 0))
+	if(!m_NetServer.Open(BindAddr, &m_ServerBan, g_Config.m_SvMaxClients, g_Config.m_SvMaxClientsPerIP, 0))
 	{
-		dbg_msg("server", "couldn't open socket. port might already be in use");
+		dbg_msg("server", "couldn't open socket. port %d might already be in use", g_Config.m_SvPort);
 		return -1;
 	}
 
 	m_NetServer.SetCallbacks(NewClientCallback, DelClientCallback, this);
 
-	m_Econ.Init(Console());
+	m_ServerBan.Init(Console(), Storage(), this);
+	m_Econ.Init(Console(), &m_ServerBan);
 
 	char aBuf[256];
 	str_format(aBuf, sizeof(aBuf), "server name is '%s'", g_Config.m_SvName);
@@ -1356,163 +1455,23 @@ void CServer::ConKick(IConsole::IResult
 		((CServer *)pUser)->Kick(pResult->GetInteger(0), "Kicked by console");
 }
 
-void CServer::ConBan(IConsole::IResult *pResult, void *pUser)
-{
-	NETADDR Addr;
-	CServer *pServer = (CServer *)pUser;
-	const char *pStr = pResult->GetString(0);
-	int Minutes = 30;
-	const char *pReason = "No reason given";
-
-	if(pResult->NumArguments() > 1)
-		Minutes = max(0, pResult->GetInteger(1));
-
-	if(pResult->NumArguments() > 2)
-		pReason = pResult->GetString(2);
-
-	if(net_addr_from_str(&Addr, pStr) == 0)
-	{
-		if(pServer->m_RconClientID >= 0 && pServer->m_RconClientID < MAX_CLIENTS && pServer->m_aClients[pServer->m_RconClientID].m_State != CClient::STATE_EMPTY)
-		{
-			NETADDR AddrCheck = pServer->m_NetServer.ClientAddr(pServer->m_RconClientID);
-			Addr.port = AddrCheck.port = 0;
-			if(net_addr_comp(&Addr, &AddrCheck) == 0)
-			{
-				pServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "you can't ban yourself");
-				return;
-			}
-
-			for(int i = 0; i < MAX_CLIENTS; ++i)
-			{
-				if(i == pServer->m_RconClientID)
-					continue;
-
-				AddrCheck = pServer->m_NetServer.ClientAddr(i);
-				AddrCheck.port = 0;
-				if(net_addr_comp(&Addr, &AddrCheck) == 0 && pServer->m_aClients[i].m_Authed > pServer->m_RconAuthLevel)
-				{
-					pServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "ban command denied");
-					return;
-				}
-			}
-		}
-		pServer->BanAdd(Addr, Minutes*60, pReason);
-	}
-	else if(StrAllnum(pStr))
-	{
-		int ClientID = str_toint(pStr);
-
-		if(ClientID < 0 || ClientID >= MAX_CLIENTS || pServer->m_aClients[ClientID].m_State == CClient::STATE_EMPTY)
-		{
-			pServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "invalid client id");
-			return;
-		}
-		else if(pServer->m_RconClientID == ClientID)
-		{
-			pServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "you can't ban yourself");
-			return;
-		}
-		else if(pServer->m_aClients[ClientID].m_Authed > pServer->m_RconAuthLevel)
-		{
-			pServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "ban command denied");
-			return;
-		}
-
-		Addr = pServer->m_NetServer.ClientAddr(ClientID);
-		pServer->BanAdd(Addr, Minutes*60, pReason);
-	}
-	else
-	{
-		pServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "invalid network address to ban");
-		return;
- 	}
-}
-
-void CServer::ConUnban(IConsole::IResult *pResult, void *pUser)
-{
-	NETADDR Addr;
-	CServer *pServer = (CServer *)pUser;
-	const char *pStr = pResult->GetString(0);
-
-	if(net_addr_from_str(&Addr, pStr) == 0 && !pServer->BanRemove(Addr))
-	{
-		char aAddrStr[NETADDR_MAXSTRSIZE];
-		net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr));
-
-		char aBuf[256];
-		str_format(aBuf, sizeof(aBuf), "unbanned %s", aAddrStr);
-		pServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf);
-	}
-	else if(StrAllnum(pStr))
-	{
-		int BanIndex = str_toint(pStr);
-		CNetServer::CBanInfo Info;
-		if(BanIndex < 0 || !pServer->m_NetServer.BanGet(BanIndex, &Info))
-			pServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "invalid ban index");
-		else if(!pServer->BanRemove(Info.m_Addr))
-		{
-			char aAddrStr[NETADDR_MAXSTRSIZE];
-			net_addr_str(&Info.m_Addr, aAddrStr, sizeof(aAddrStr));
-
-			char aBuf[256];
-			str_format(aBuf, sizeof(aBuf), "unbanned %s", aAddrStr);
-			pServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf);
-		}
-	}
-	else
-		pServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", "invalid network address");
-}
-
-void CServer::ConBans(IConsole::IResult *pResult, void *pUser)
-{
-	unsigned Now = time_timestamp();
-	char aBuf[1024];
-	char aAddrStr[NETADDR_MAXSTRSIZE];
-	CServer* pServer = (CServer *)pUser;
-
-	int Num = pServer->m_NetServer.BanNum();
-	for(int i = 0; i < Num; i++)
-	{
-		CNetServer::CBanInfo Info;
-		pServer->m_NetServer.BanGet(i, &Info);
-		NETADDR Addr = Info.m_Addr;
-		net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr));
-
-		if(Info.m_Expires == -1)
-		{
-			str_format(aBuf, sizeof(aBuf), "#%i %s for life", i, aAddrStr);
-		}
-		else
-		{
-			unsigned t = Info.m_Expires - Now;
-			str_format(aBuf, sizeof(aBuf), "#%i %s for %d minutes and %d seconds", i, aAddrStr, t/60, t%60);
-		}
-		pServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "Server", aBuf);
-	}
-	str_format(aBuf, sizeof(aBuf), "%d ban(s)", Num);
-	pServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "Server", aBuf);
-}
-
 void CServer::ConStatus(IConsole::IResult *pResult, void *pUser)
 {
-	int i;
-	NETADDR Addr;
 	char aBuf[1024];
 	char aAddrStr[NETADDR_MAXSTRSIZE];
-	CServer* pServer = (CServer *)pUser;
+	CServer* pThis = static_cast<CServer *>(pUser);
 
-	for(i = 0; i < MAX_CLIENTS; i++)
+	for(int i = 0; i < MAX_CLIENTS; i++)
 	{
-		if(pServer->m_aClients[i].m_State != CClient::STATE_EMPTY)
+		if(pThis->m_aClients[i].m_State != CClient::STATE_EMPTY)
 		{
-			Addr = pServer->m_NetServer.ClientAddr(i);
-			net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr));
-			if(pServer->m_aClients[i].m_State == CClient::STATE_INGAME)
+			net_addr_str(pThis->m_NetServer.ClientAddr(i), aAddrStr, sizeof(aAddrStr), true);
+			if(pThis->m_aClients[i].m_State == CClient::STATE_INGAME)
 				str_format(aBuf, sizeof(aBuf), "id=%d addr=%s name='%s' score=%d", i, aAddrStr,
-					pServer->m_aClients[i].m_aName, pServer->m_aClients[i].m_Score);
+					pThis->m_aClients[i].m_aName, pThis->m_aClients[i].m_Score);
 			else
 				str_format(aBuf, sizeof(aBuf), "id=%d addr=%s connecting", i, aAddrStr);
-			pServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "Server", aBuf);
+			pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "Server", aBuf);
 		}
 	}
 }
@@ -1541,6 +1500,11 @@ void CServer::DemoRecorder_HandleAutoSta
 	}
 }
 
+bool CServer::DemoRecorder_IsRecording()
+{
+	return m_DemoRecorder.IsRecording();
+}
+
 void CServer::ConRecord(IConsole::IResult *pResult, void *pUser)
 {
 	CServer* pServer = (CServer *)pUser;
@@ -1567,6 +1531,27 @@ void CServer::ConMapReload(IConsole::IRe
 	((CServer *)pUser)->m_MapReload = 1;
 }
 
+void CServer::ConLogout(IConsole::IResult *pResult, void *pUser)
+{
+	CServer *pServer = (CServer *)pUser;
+
+	if(pServer->m_RconClientID >= 0 && pServer->m_RconClientID < MAX_CLIENTS &&
+		pServer->m_aClients[pServer->m_RconClientID].m_State != CServer::CClient::STATE_EMPTY)
+	{
+		CMsgPacker Msg(NETMSG_RCON_AUTH_STATUS);
+		Msg.AddInt(0);	//authed
+		Msg.AddInt(0);	//cmdlist
+		pServer->SendMsgEx(&Msg, MSGFLAG_VITAL, pServer->m_RconClientID, true);
+
+		pServer->m_aClients[pServer->m_RconClientID].m_Authed = AUTHED_NO;
+		pServer->m_aClients[pServer->m_RconClientID].m_pRconCmdToSend = 0;
+		pServer->SendRconLine(pServer->m_RconClientID, "Logout successful.");
+		char aBuf[32];
+		str_format(aBuf, sizeof(aBuf), "ClientID=%d logged out", pServer->m_RconClientID);
+		pServer->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf);
+	}
+}
+
 void CServer::ConchainSpecialInfoupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
 {
 	pfnCallback(pResult, pCallbackUserData);
@@ -1587,7 +1572,7 @@ void CServer::ConchainModCommandUpdate(I
 	{
 		CServer *pThis = static_cast<CServer *>(pUserData);
 		const IConsole::CCommandInfo *pInfo = pThis->Console()->GetCommandInfo(pResult->GetString(0), CFGFLAG_SERVER, false);
-		int OldAccessLevel;
+		int OldAccessLevel = 0;
 		if(pInfo)
 			OldAccessLevel = pInfo->GetAccessLevel();
 		pfnCallback(pResult, pCallbackUserData);
@@ -1625,11 +1610,9 @@ void CServer::RegisterCommands()
 	m_pConsole = Kernel()->RequestInterface<IConsole>();
 
 	Console()->Register("kick", "i?r", CFGFLAG_SERVER, ConKick, this, "Kick player with specified id for any reason");
-	Console()->Register("ban", "s?ir", CFGFLAG_SERVER|CFGFLAG_STORE, ConBan, this, "Ban player with ip/id for x minutes for any reason");
-	Console()->Register("unban", "s", CFGFLAG_SERVER|CFGFLAG_STORE, ConUnban, this, "Unban ip");
-	Console()->Register("bans", "", CFGFLAG_SERVER|CFGFLAG_STORE, ConBans, this, "Show banlist");
 	Console()->Register("status", "", CFGFLAG_SERVER, ConStatus, this, "List players");
 	Console()->Register("shutdown", "", CFGFLAG_SERVER, ConShutdown, this, "Shut down");
+	Console()->Register("logout", "", CFGFLAG_SERVER, ConLogout, this, "Logout of rcon");
 
 	Console()->Register("record", "?s", CFGFLAG_SERVER|CFGFLAG_STORE, ConRecord, this, "Record to a file");
 	Console()->Register("stoprecord", "", CFGFLAG_SERVER, ConStopRecord, this, "Stop recording");
@@ -1690,9 +1673,9 @@ int main(int argc, const char **argv) //
 	IEngine *pEngine = CreateEngine("Teeworlds");
 	IEngineMap *pEngineMap = CreateEngineMap();
 	IGameServer *pGameServer = CreateGameServer();
-	IConsole *pConsole = CreateConsole(CFGFLAG_SERVER);
+	IConsole *pConsole = CreateConsole(CFGFLAG_SERVER|CFGFLAG_ECON);
 	IEngineMasterServer *pEngineMasterServer = CreateEngineMasterServer();
-	IStorage *pStorage = CreateStorage("Teeworlds", argc, argv); // ignore_convention
+	IStorage *pStorage = CreateStorage("Teeworlds", IStorage::STORAGETYPE_SERVER, argc, argv); // ignore_convention
 	IConfig *pConfig = CreateConfig();
 
 	pServer->InitRegister(&pServer->m_NetServer, pEngineMasterServer, pConsole);
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/server/server.h alien-rc4/src//engine/server/server.h
--- teeworlds-b177-r50edfd37-source/src//engine/server/server.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/server/server.h	2012-06-14 23:57:39.000000000 +0200
@@ -5,6 +5,7 @@
 
 #include <engine/server.h>
 
+
 class CSnapIDPool
 {
 	enum
@@ -39,6 +40,25 @@ public:
 	void FreeID(int ID);
 };
 
+
+class CServerBan : public CNetBan
+{
+	class CServer *m_pServer;
+
+	template<class T> int BanExt(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason);
+
+public:
+	class CServer *Server() const { return m_pServer; }
+
+	void Init(class IConsole *pConsole, class IStorage *pStorage, class CServer* pServer);
+
+	int BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason);
+	int BanRange(const CNetRange *pRange, int Seconds, const char *pReason);
+
+	static void ConBanExt(class IConsole::IResult *pResult, void *pUser);
+};
+
+
 class CServer : public IServer
 {
 	class IGameServer *m_pGameServer;
@@ -114,6 +134,7 @@ public:
 	CSnapIDPool m_IDPool;
 	CNetServer m_NetServer;
 	CEcon m_Econ;
+	CServerBan m_ServerBan;
 
 	IEngineMap *m_pMap;
 
@@ -149,6 +170,7 @@ public:
 	void Kick(int ClientID, const char *pReason);
 
 	void DemoRecorder_HandleAutoStart();
+	bool DemoRecorder_IsRecording();
 
 	//int Tick()
 	int64 TickStartTime(int Tick);
@@ -156,6 +178,7 @@ public:
 
 	int Init();
 
+	void SetRconCID(int ClientID);
 	bool IsAuthed(int ClientID);
 	int GetClientInfo(int ClientID, CClientInfo *pInfo);
 	void GetClientAddr(int ClientID, char *pAddrStr, int Size);
@@ -163,6 +186,7 @@ public:
 	const char *ClientClan(int ClientID);
 	int ClientCountry(int ClientID);
 	bool ClientIngame(int ClientID);
+	int MaxClients() const;
 
 	virtual int SendMsg(CMsgPacker *pMsg, int Flags, int ClientID);
 	int SendMsgEx(CMsgPacker *pMsg, int Flags, int ClientID, bool System);
@@ -183,12 +207,9 @@ public:
 
 	void ProcessClientPacket(CNetChunk *pPacket);
 
-	void SendServerInfo(NETADDR *pAddr, int Token);
+	void SendServerInfo(const NETADDR *pAddr, int Token);
 	void UpdateServerInfo();
 
-	int BanAdd(NETADDR Addr, int Seconds, const char *pReason);
-	int BanRemove(NETADDR Addr);
-
 	void PumpNetwork();
 
 	char *GetMapName();
@@ -198,14 +219,12 @@ public:
 	int Run();
 
 	static void ConKick(IConsole::IResult *pResult, void *pUser);
-	static void ConBan(IConsole::IResult *pResult, void *pUser);
-	static void ConUnban(IConsole::IResult *pResult, void *pUser);
-	static void ConBans(IConsole::IResult *pResult, void *pUser);
- 	static void ConStatus(IConsole::IResult *pResult, void *pUser);
+	static void ConStatus(IConsole::IResult *pResult, void *pUser);
 	static void ConShutdown(IConsole::IResult *pResult, void *pUser);
 	static void ConRecord(IConsole::IResult *pResult, void *pUser);
 	static void ConStopRecord(IConsole::IResult *pResult, void *pUser);
 	static void ConMapReload(IConsole::IResult *pResult, void *pUser);
+	static void ConLogout(IConsole::IResult *pResult, void *pUser);
 	static void ConchainSpecialInfoupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData);
 	static void ConchainMaxclientsperipUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData);
 	static void ConchainModCommandUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData);
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/serverbrowser.h alien-rc4/src//engine/serverbrowser.h
--- teeworlds-b177-r50edfd37-source/src//engine/serverbrowser.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/serverbrowser.h	2012-06-14 23:57:39.000000000 +0200
@@ -24,7 +24,7 @@ public:
 		int m_Country;
 		int m_Score;
 		bool m_Player;
-		
+
 		int m_FriendState;
 	};
 
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/server.h alien-rc4/src//engine/server.h
--- teeworlds-b177-r50edfd37-source/src//engine/server.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/server.h	2012-06-14 23:57:39.000000000 +0200
@@ -25,6 +25,7 @@ public:
 	int Tick() const { return m_CurrentGameTick; }
 	int TickSpeed() const { return m_TickSpeed; }
 
+	virtual int MaxClients() const = 0;
 	virtual const char *ClientName(int ClientID) = 0;
 	virtual const char *ClientClan(int ClientID) = 0;
 	virtual int ClientCountry(int ClientID) = 0;
@@ -54,10 +55,17 @@ public:
 
 	virtual void SnapSetStaticsize(int ItemType, int Size) = 0;
 
+	enum
+	{
+		RCON_CID_SERV=-1,
+		RCON_CID_VOTE=-2,
+	};
+	virtual void SetRconCID(int ClientID) = 0;
 	virtual bool IsAuthed(int ClientID) = 0;
 	virtual void Kick(int ClientID, const char *pReason) = 0;
 
 	virtual void DemoRecorder_HandleAutoStart() = 0;
+	virtual bool DemoRecorder_IsRecording() = 0;
 };
 
 class IGameServer : public IInterface
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/shared/config.cpp alien-rc4/src//engine/shared/config.cpp
--- teeworlds-b177-r50edfd37-source/src//engine/shared/config.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/shared/config.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -111,13 +111,8 @@ public:
 	{
 		if(!m_ConfigFile)
 			return;
-#if defined(CONF_FAMILY_WINDOWS)
-		static const char Newline[] = "\r\n";
-#else
-		static const char Newline[] = "\n";
-#endif
 		io_write(m_ConfigFile, pLine, str_length(pLine));
-		io_write(m_ConfigFile, Newline, sizeof(Newline)-1);
+		io_write_newline(m_ConfigFile);
 	}
 };
 
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/shared/config.h alien-rc4/src//engine/shared/config.h
--- teeworlds-b177-r50edfd37-source/src//engine/shared/config.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/shared/config.h	2012-06-14 23:57:39.000000000 +0200
@@ -20,7 +20,8 @@ enum
 	CFGFLAG_CLIENT=2,
 	CFGFLAG_SERVER=4,
 	CFGFLAG_STORE=8,
-	CFGFLAG_MASTER=16
+	CFGFLAG_MASTER=16,
+	CFGFLAG_ECON=32,
 };
 
 #endif
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/shared/config_variables.h alien-rc4/src//engine/shared/config_variables.h
--- teeworlds-b177-r50edfd37-source/src//engine/shared/config_variables.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/shared/config_variables.h	2012-06-14 23:57:39.000000000 +0200
@@ -17,6 +17,7 @@ MACRO_CONFIG_INT(ConsoleOutputLevel, con
 
 MACRO_CONFIG_INT(ClCpuThrottle, cl_cpu_throttle, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "")
 MACRO_CONFIG_INT(ClEditor, cl_editor, 0, 0, 1, CFGFLAG_CLIENT, "")
+MACRO_CONFIG_INT(ClLoadCountryFlags, cl_load_country_flags, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Load and show country flags")
 
 MACRO_CONFIG_INT(ClAutoDemoRecord, cl_auto_demo_record, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Automatically record demos")
 MACRO_CONFIG_INT(ClAutoDemoMax, cl_auto_demo_max, 10, 0, 1000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Maximum number of automatically recorded demos (0 = no limit)")
@@ -47,7 +48,7 @@ MACRO_CONFIG_INT(BrSort, br_sort, 0, 0,
 MACRO_CONFIG_INT(BrSortOrder, br_sort_order, 0, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "")
 MACRO_CONFIG_INT(BrMaxRequests, br_max_requests, 25, 0, 1000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Number of requests to use when refreshing server browser")
 
-MACRO_CONFIG_INT(SndBufferSize, snd_buffer_size, 512, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Sound buffer size")
+MACRO_CONFIG_INT(SndBufferSize, snd_buffer_size, 512, 128, 32768, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Sound buffer size")
 MACRO_CONFIG_INT(SndRate, snd_rate, 48000, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Sound mixing rate")
 MACRO_CONFIG_INT(SndEnable, snd_enable, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Sound enable")
 MACRO_CONFIG_INT(SndMusic, snd_enable_music, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Play background music")
@@ -70,11 +71,14 @@ MACRO_CONFIG_INT(GfxTextureQuality, gfx_
 MACRO_CONFIG_INT(GfxFsaaSamples, gfx_fsaa_samples, 0, 0, 16, CFGFLAG_SAVE|CFGFLAG_CLIENT, "FSAA Samples")
 MACRO_CONFIG_INT(GfxRefreshRate, gfx_refresh_rate, 0, 0, 0, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Screen refresh rate")
 MACRO_CONFIG_INT(GfxFinish, gfx_finish, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "")
+MACRO_CONFIG_INT(GfxAsyncRender, gfx_asyncrender, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Do rendering async from the the update")
+
+MACRO_CONFIG_INT(GfxThreaded, gfx_threaded, 1, 0, 1, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Use the threaded graphics backend")
 
 MACRO_CONFIG_INT(InpMousesens, inp_mousesens, 100, 5, 100000, CFGFLAG_SAVE|CFGFLAG_CLIENT, "Mouse sensitivity")
 
 MACRO_CONFIG_STR(SvName, sv_name, 128, "unnamed server", CFGFLAG_SERVER, "Server name")
-MACRO_CONFIG_STR(SvBindaddr, sv_bindaddr, 128, "", CFGFLAG_SERVER, "Address to bind the server to")
+MACRO_CONFIG_STR(Bindaddr, bindaddr, 128, "", CFGFLAG_CLIENT|CFGFLAG_SERVER|CFGFLAG_MASTER, "Address to bind the client/server to")
 MACRO_CONFIG_INT(SvPort, sv_port, 8303, 0, 0, CFGFLAG_SERVER, "Port to use for the server")
 MACRO_CONFIG_INT(SvExternalPort, sv_external_port, 0, 0, 0, CFGFLAG_SERVER, "External port to report to the master servers")
 MACRO_CONFIG_STR(SvMap, sv_map, 128, "dm1", CFGFLAG_SERVER, "Map to use on the server")
@@ -89,12 +93,12 @@ MACRO_CONFIG_INT(SvRconBantime, sv_rcon_
 MACRO_CONFIG_INT(SvAutoDemoRecord, sv_auto_demo_record, 0, 0, 1, CFGFLAG_SERVER, "Automatically record demos")
 MACRO_CONFIG_INT(SvAutoDemoMax, sv_auto_demo_max, 10, 0, 1000, CFGFLAG_SERVER, "Maximum number of automatically recorded demos (0 = no limit)")
 
-MACRO_CONFIG_STR(EcBindaddr, ec_bindaddr, 128, "localhost", CFGFLAG_SERVER, "Address to bind the external console to. Anything but 'localhost' is dangerous")
-MACRO_CONFIG_INT(EcPort, ec_port, 0, 0, 0, CFGFLAG_SERVER, "Port to use for the external console")
-MACRO_CONFIG_STR(EcPassword, ec_password, 32, "", CFGFLAG_SERVER, "External console password")
-MACRO_CONFIG_INT(EcBantime, ec_bantime, 0, 0, 1440, CFGFLAG_SERVER, "The time a client gets banned if econ authentication fails. 0 just closes the connection")
-MACRO_CONFIG_INT(EcAuthTimeout, ec_auth_timeout, 30, 1, 120, CFGFLAG_SERVER, "Time in seconds before the the econ authentification times out")
-MACRO_CONFIG_INT(EcOutputLevel, ec_output_level, 1, 0, 2, CFGFLAG_SERVER, "Adjusts the amount of information in the external console")
+MACRO_CONFIG_STR(EcBindaddr, ec_bindaddr, 128, "localhost", CFGFLAG_ECON, "Address to bind the external console to. Anything but 'localhost' is dangerous")
+MACRO_CONFIG_INT(EcPort, ec_port, 0, 0, 0, CFGFLAG_ECON, "Port to use for the external console")
+MACRO_CONFIG_STR(EcPassword, ec_password, 32, "", CFGFLAG_ECON, "External console password")
+MACRO_CONFIG_INT(EcBantime, ec_bantime, 0, 0, 1440, CFGFLAG_ECON, "The time a client gets banned if econ authentication fails. 0 just closes the connection")
+MACRO_CONFIG_INT(EcAuthTimeout, ec_auth_timeout, 30, 1, 120, CFGFLAG_ECON, "Time in seconds before the the econ authentification times out")
+MACRO_CONFIG_INT(EcOutputLevel, ec_output_level, 1, 0, 2, CFGFLAG_ECON, "Adjusts the amount of information in the external console")
 
 MACRO_CONFIG_INT(Debug, debug, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SERVER, "Debug mode")
 MACRO_CONFIG_INT(DbgStress, dbg_stress, 0, 0, 0, CFGFLAG_CLIENT|CFGFLAG_SERVER, "Stress systems")
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/shared/console.cpp alien-rc4/src//engine/shared/console.cpp
--- teeworlds-b177-r50edfd37-source/src//engine/shared/console.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/shared/console.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -12,6 +12,8 @@
 #include "console.h"
 #include "linereader.h"
 
+// todo: rework this
+
 const char *CConsole::CResult::GetString(unsigned Index)
 {
 	if (Index < 0 || Index >= m_NumArgs)
@@ -374,6 +376,14 @@ void CConsole::ExecuteLine(const char *p
 	CConsole::ExecuteLineStroked(0, pStr); // then release it
 }
 
+void CConsole::ExecuteLineFlag(const char *pStr, int FlagMask)
+{
+	int Temp = m_FlagMask;
+	m_FlagMask = FlagMask;
+	ExecuteLine(pStr);
+	m_FlagMask = Temp;
+}
+
 
 void CConsole::ExecuteFile(const char *pFilename)
 {
@@ -564,6 +574,75 @@ static void StrVariableCommand(IConsole:
 	}
 }
 
+void CConsole::ConToggle(IConsole::IResult *pResult, void *pUser)
+{
+	CConsole* pConsole = static_cast<CConsole *>(pUser);
+	char aBuf[128] = {0};
+	CCommand *pCommand = pConsole->FindCommand(pResult->GetString(0), pConsole->m_FlagMask);
+	if(pCommand)
+	{
+		FCommandCallback pfnCallback = pCommand->m_pfnCallback;
+		void *pUserData = pCommand->m_pUserData;
+
+		// check for chain
+		if(pCommand->m_pfnCallback == Con_Chain)
+		{
+			CChain *pChainInfo = static_cast<CChain *>(pCommand->m_pUserData);
+			pfnCallback = pChainInfo->m_pfnCallback;
+			pUserData = pChainInfo->m_pCallbackUserData;
+		}
+
+		if(pfnCallback == IntVariableCommand)
+		{
+			CIntVariableData *pData = static_cast<CIntVariableData *>(pUserData);
+			int Val = *(pData->m_pVariable)==pResult->GetInteger(1) ? pResult->GetInteger(2) : pResult->GetInteger(1);
+			str_format(aBuf, sizeof(aBuf), "%s %i", pResult->GetString(0), Val);
+			pConsole->ExecuteLine(aBuf);
+			aBuf[0] = 0;
+		}
+		else
+			str_format(aBuf, sizeof(aBuf), "Invalid command: '%s'.", pResult->GetString(0));
+	}
+	else
+		str_format(aBuf, sizeof(aBuf), "No such command: '%s'.", pResult->GetString(0));
+
+	if(aBuf[0] != 0)
+		pConsole->Print(OUTPUT_LEVEL_STANDARD, "Console", aBuf);
+}
+
+void CConsole::ConToggleStroke(IConsole::IResult *pResult, void *pUser)
+{
+	CConsole* pConsole = static_cast<CConsole *>(pUser);
+	char aBuf[128] = {0};
+	CCommand *pCommand = pConsole->FindCommand(pResult->GetString(1), pConsole->m_FlagMask);
+	if(pCommand)
+	{
+		FCommandCallback pfnCallback = pCommand->m_pfnCallback;
+
+		// check for chain
+		if(pCommand->m_pfnCallback == Con_Chain)
+		{
+			CChain *pChainInfo = static_cast<CChain *>(pCommand->m_pUserData);
+			pfnCallback = pChainInfo->m_pfnCallback;
+		}
+
+		if(pfnCallback == IntVariableCommand)
+		{
+			int Val = pResult->GetInteger(0)==0 ? pResult->GetInteger(3) : pResult->GetInteger(2);
+			str_format(aBuf, sizeof(aBuf), "%s %i", pResult->GetString(1), Val);
+			pConsole->ExecuteLine(aBuf);
+			aBuf[0] = 0;
+		}
+		else
+			str_format(aBuf, sizeof(aBuf), "Invalid command: '%s'.", pResult->GetString(1));
+	}
+	else
+		str_format(aBuf, sizeof(aBuf), "No such command: '%s'.", pResult->GetString(1));
+
+	if(aBuf[0] != 0)
+		pConsole->Print(OUTPUT_LEVEL_STANDARD, "Console", aBuf);
+}
+
 CConsole::CConsole(int FlagMask)
 {
 	m_FlagMask = FlagMask;
@@ -585,6 +664,9 @@ CConsole::CConsole(int FlagMask)
 	Register("echo", "r", CFGFLAG_SERVER|CFGFLAG_CLIENT, Con_Echo, this, "Echo the text");
 	Register("exec", "r", CFGFLAG_SERVER|CFGFLAG_CLIENT, Con_Exec, this, "Execute the specified file");
 
+	Register("toggle", "sii", CFGFLAG_SERVER|CFGFLAG_CLIENT, ConToggle, this, "Toggle config value");
+	Register("+toggle", "sii", CFGFLAG_CLIENT, ConToggleStroke, this, "Toggle config value via keypress");
+
 	Register("mod_command", "s?i", CFGFLAG_SERVER, ConModCommandAccess, this, "Specify command accessibility for moderators");
 	Register("mod_status", "", CFGFLAG_SERVER, ConModCommandStatus, this, "List all commands which are accessible for moderators");
 
@@ -633,7 +715,7 @@ void CConsole::ParseArguments(int NumArg
 
 void CConsole::AddCommandSorted(CCommand *pCommand)
 {
-	if(!m_pFirstCommand || str_comp(pCommand->m_pName, m_pFirstCommand->m_pName) < 0)
+	if(!m_pFirstCommand || str_comp(pCommand->m_pName, m_pFirstCommand->m_pName) <= 0)
 	{
 		if(m_pFirstCommand && m_pFirstCommand->m_pNext)
 			pCommand->m_pNext = m_pFirstCommand;
@@ -645,7 +727,7 @@ void CConsole::AddCommandSorted(CCommand
 	{
 		for(CCommand *p = m_pFirstCommand; p; p = p->m_pNext)
 		{
-			if(!p->m_pNext || str_comp(pCommand->m_pName, p->m_pNext->m_pName) < 0)
+			if(!p->m_pNext || str_comp(pCommand->m_pName, p->m_pNext->m_pName) <= 0)
 			{
 				pCommand->m_pNext = p->m_pNext;
 				p->m_pNext = pCommand;
@@ -658,18 +740,25 @@ void CConsole::AddCommandSorted(CCommand
 void CConsole::Register(const char *pName, const char *pParams,
 	int Flags, FCommandCallback pfnFunc, void *pUser, const char *pHelp)
 {
-	CCommand *pCommand = new(mem_alloc(sizeof(CCommand), sizeof(void*))) CCommand;
+	CCommand *pCommand = FindCommand(pName, Flags);
+	bool DoAdd = false;
+	if(pCommand == 0)
+	{
+		pCommand = new(mem_alloc(sizeof(CCommand), sizeof(void*))) CCommand;
+		DoAdd = true;
+	}
 	pCommand->m_pfnCallback = pfnFunc;
 	pCommand->m_pUserData = pUser;
 
 	pCommand->m_pName = pName;
 	pCommand->m_pHelp = pHelp;
 	pCommand->m_pParams = pParams;
-	
+
 	pCommand->m_Flags = Flags;
 	pCommand->m_Temp = false;
 
-	AddCommandSorted(pCommand);
+	if(DoAdd)
+		AddCommandSorted(pCommand);
 }
 
 void CConsole::RegisterTemp(const char *pName, const char *pParams,	int Flags, const char *pHelp)
@@ -699,7 +788,7 @@ void CConsole::RegisterTemp(const char *
 	}
 
 	pCommand->m_pfnCallback = 0;
-	pCommand->m_pUserData = 0;	
+	pCommand->m_pUserData = 0;
 	pCommand->m_Flags = Flags;
 	pCommand->m_Temp = true;
 
@@ -729,7 +818,7 @@ void CConsole::DeregisterTemp(const char
 				break;
 			}
 	}
-	
+
 	// add to recycle list
 	if(pRemoved)
 	{
@@ -742,7 +831,7 @@ void CConsole::DeregisterTempAll()
 {
 	// set non temp as first one
 	for(; m_pFirstCommand && m_pFirstCommand->m_Temp; m_pFirstCommand = m_pFirstCommand->m_pNext);
-	
+
 	// remove temp entries from command list
 	for(CCommand *pCommand = m_pFirstCommand; pCommand && pCommand->m_pNext; pCommand = pCommand->m_pNext)
 	{
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/shared/console.h alien-rc4/src//engine/shared/console.h
--- teeworlds-b177-r50edfd37-source/src//engine/shared/console.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/shared/console.h	2012-06-14 23:57:39.000000000 +0200
@@ -54,6 +54,8 @@ class CConsole : public IConsole
 	static void Con_Chain(IResult *pResult, void *pUserData);
 	static void Con_Echo(IResult *pResult, void *pUserData);
 	static void Con_Exec(IResult *pResult, void *pUserData);
+	static void ConToggle(IResult *pResult, void *pUser);
+	static void ConToggleStroke(IResult *pResult, void *pUser);
 	static void ConModCommandAccess(IResult *pResult, void *pUser);
 	static void ConModCommandStatus(IConsole::IResult *pResult, void *pUser);
 
@@ -156,7 +158,7 @@ class CConsole : public IConsole
 public:
 	CConsole(int FlagMask);
 
-	virtual const CCommandInfo *FirstCommandInfo(int AccessLevel, int Flagmask) const;
+	virtual const CCommandInfo *FirstCommandInfo(int AccessLevel, int FlagMask) const;
 	virtual const CCommandInfo *GetCommandInfo(const char *pName, int FlagMask, bool Temp);
 	virtual void PossibleCommands(const char *pStr, int FlagMask, bool Temp, FPossibleCallback pfnCallback, void *pUser);
 
@@ -170,6 +172,7 @@ public:
 
 	virtual bool LineIsValid(const char *pStr);
 	virtual void ExecuteLine(const char *pStr);
+	virtual void ExecuteLineFlag(const char *pStr, int FlagMask);
 	virtual void ExecuteFile(const char *pFilename);
 
 	virtual int RegisterPrintCallback(int OutputLevel, FPrintCallback pfnPrintCallback, void *pUserData);
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/shared/demo.cpp alien-rc4/src//engine/shared/demo.cpp
--- teeworlds-b177-r50edfd37-source/src//engine/shared/demo.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/shared/demo.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -13,8 +13,9 @@
 #include "snapshot.h"
 
 static const unsigned char gs_aHeaderMarker[7] = {'T', 'W', 'D', 'E', 'M', 'O', 0};
-static const unsigned char gs_ActVersion = 3;
+static const unsigned char gs_ActVersion = 4;
 static const int gs_LengthOffset = 152;
+static const int gs_NumMarkersOffset = 176;
 
 
 CDemoRecorder::CDemoRecorder(class CSnapshotDelta *pSnapshotDelta)
@@ -89,6 +90,8 @@ int CDemoRecorder::Start(class IStorage
 	str_copy(Header.m_aType, pType, sizeof(Header.m_aType));
 	// Header.m_Length - add this on stop
 	str_timestamp(Header.m_aTimestamp, sizeof(Header.m_aTimestamp));
+	// Header.m_aNumTimelineMarkers - add this on stop
+	// Header.m_aTimelineMarkers - add this on stop
 	io_write(DemoFile, &Header, sizeof(Header));
 
 	// write map data
@@ -105,6 +108,7 @@ int CDemoRecorder::Start(class IStorage
 	m_LastKeyFrame = -1;
 	m_LastTickMarker = -1;
 	m_FirstTick = -1;
+	m_NumTimelineMarkers = 0;
 
 	char aBuf[256];
 	str_format(aBuf, sizeof(aBuf), "Recording to '%s'", pFilename);
@@ -266,6 +270,25 @@ int CDemoRecorder::Stop()
 	aLength[3] = (DemoLength)&0xff;
 	io_write(m_File, aLength, sizeof(aLength));
 
+	// add the timeline markers to the header
+	io_seek(m_File, gs_NumMarkersOffset, IOSEEK_START);
+	char aNumMarkers[4];
+	aNumMarkers[0] = (m_NumTimelineMarkers>>24)&0xff;
+	aNumMarkers[1] = (m_NumTimelineMarkers>>16)&0xff;
+	aNumMarkers[2] = (m_NumTimelineMarkers>>8)&0xff;
+	aNumMarkers[3] = (m_NumTimelineMarkers)&0xff;
+	io_write(m_File, aNumMarkers, sizeof(aNumMarkers));
+	for(int i = 0; i < m_NumTimelineMarkers; i++)
+	{
+		int Marker = m_aTimelineMarkers[i];
+		char aMarker[4];
+		aMarker[0] = (Marker>>24)&0xff;
+		aMarker[1] = (Marker>>16)&0xff;
+		aMarker[2] = (Marker>>8)&0xff;
+		aMarker[3] = (Marker)&0xff;
+		io_write(m_File, aMarker, sizeof(aMarker));
+	}
+
 	io_close(m_File);
 	m_File = 0;
 	m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", "Stopped recording");
@@ -273,6 +296,24 @@ int CDemoRecorder::Stop()
 	return 0;
 }
 
+void CDemoRecorder::AddDemoMarker()
+{
+	if(m_LastTickMarker < 0 || m_NumTimelineMarkers >= MAX_TIMELINE_MARKERS)
+		return;
+
+	// not more than 1 marker in a second
+	if(m_NumTimelineMarkers > 0)
+	{
+		int Diff = m_LastTickMarker - m_aTimelineMarkers[m_NumTimelineMarkers-1];
+		if(Diff < SERVER_TICK_SPEED*1.0f)
+			return;
+	}
+
+	m_aTimelineMarkers[m_NumTimelineMarkers++] = m_LastTickMarker;
+
+	m_pConsole->Print(IConsole::OUTPUT_LEVEL_STANDARD, "demo_recorder", "Added timeline marker");
+}
+
 
 
 CDemoPlayer::CDemoPlayer(class CSnapshotDelta *pSnapshotDelta)
@@ -622,6 +663,16 @@ int CDemoPlayer::Load(class IStorage *pS
 		mem_free(pMapData);
 	}
 
+	// get timeline markers
+	int Num = ((m_Info.m_Header.m_aNumTimelineMarkers[0]<<24)&0xFF000000) | ((m_Info.m_Header.m_aNumTimelineMarkers[1]<<16)&0xFF0000) |
+				((m_Info.m_Header.m_aNumTimelineMarkers[2]<<8)&0xFF00) | (m_Info.m_Header.m_aNumTimelineMarkers[3]&0xFF);
+	m_Info.m_Info.m_NumTimelineMarkers = Num;
+	for(int i = 0; i < Num && i < MAX_TIMELINE_MARKERS; i++)
+	{
+		char *pTimelineMarker = m_Info.m_Header.m_aTimelineMarkers[i];
+		m_Info.m_Info.m_aTimelineMarkers[i] = ((pTimelineMarker[0]<<24)&0xFF000000) | ((pTimelineMarker[1]<<16)&0xFF0000) |
+												((pTimelineMarker[2]<<8)&0xFF00) | (pTimelineMarker[3]&0xFF);
+	}
 
 	// scan the file for interessting points
 	ScanFile();
@@ -775,7 +826,7 @@ void CDemoPlayer::GetDemoName(char *pBuf
 		else if(*pFileName == '.')
 			pEnd = pFileName;
 	}
-	
+
 	int Length = pEnd > pExtractedName ? min(BufferSize, (int)(pEnd-pExtractedName+1)) : BufferSize;
 	str_copy(pBuffer, pExtractedName, Length);
 }
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/shared/demo.h alien-rc4/src//engine/shared/demo.h
--- teeworlds-b177-r50edfd37-source/src//engine/shared/demo.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/shared/demo.h	2012-06-14 23:57:39.000000000 +0200
@@ -17,6 +17,8 @@ class CDemoRecorder : public IDemoRecord
 	int m_FirstTick;
 	unsigned char m_aLastSnapshotData[CSnapshot::MAX_SIZE];
 	class CSnapshotDelta *m_pSnapshotDelta;
+	int m_NumTimelineMarkers;
+	int m_aTimelineMarkers[MAX_TIMELINE_MARKERS];
 
 	void WriteTickMarker(int Tick, int Keyframe);
 	void Write(int Type, const void *pData, int Size);
@@ -25,6 +27,7 @@ public:
 
 	int Start(class IStorage *pStorage, class IConsole *pConsole, const char *pFilename, const char *pNetversion, const char *pMap, unsigned MapCrc, const char *pType);
 	int Stop();
+	void AddDemoMarker();
 
 	void RecordSnapshot(int Tick, const void *pData, int Size);
 	void RecordMessage(const void *pData, int Size);
@@ -108,7 +111,7 @@ public:
 	void Unpause();
 	int Stop();
 	void SetSpeed(float Speed);
-	int SetPos(float Precent);
+	int SetPos(float Percent);
 	const CInfo *BaseInfo() const { return &m_Info.m_Info; }
 	void GetDemoName(char *pBuffer, int BufferSize) const;
 	bool GetDemoInfo(class IStorage *pStorage, const char *pFilename, int StorageType, CDemoHeader *pDemoHeader) const;
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/shared/econ.cpp alien-rc4/src//engine/shared/econ.cpp
--- teeworlds-b177-r50edfd37-source/src//engine/shared/econ.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/shared/econ.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -2,14 +2,15 @@
 #include <engine/shared/config.h>
 
 #include "econ.h"
+#include "netban.h"
+
 
 int CEcon::NewClientCallback(int ClientID, void *pUser)
 {
 	CEcon *pThis = (CEcon *)pUser;
 
-	NETADDR Addr = pThis->m_NetConsole.ClientAddr(ClientID);
 	char aAddrStr[NETADDR_MAXSTRSIZE];
-	net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr));
+	net_addr_str(pThis->m_NetConsole.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true);
 	char aBuf[128];
 	str_format(aBuf, sizeof(aBuf), "client accepted. cid=%d addr=%s'", ClientID, aAddrStr);
 	pThis->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "econ", aBuf);
@@ -26,9 +27,8 @@ int CEcon::DelClientCallback(int ClientI
 {
 	CEcon *pThis = (CEcon *)pUser;
 
-	NETADDR Addr = pThis->m_NetConsole.ClientAddr(ClientID);
 	char aAddrStr[NETADDR_MAXSTRSIZE];
-	net_addr_str(&Addr, aAddrStr, sizeof(aAddrStr));
+	net_addr_str(pThis->m_NetConsole.ClientAddr(ClientID), aAddrStr, sizeof(aAddrStr), true);
 	char aBuf[256];
 	str_format(aBuf, sizeof(aBuf), "client dropped. cid=%d addr=%s reason='%s'", ClientID, aAddrStr, pReason);
 	pThis->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "econ", aBuf);
@@ -52,7 +52,15 @@ void CEcon::ConchainEconOutputLevelUpdat
 	}
 }
 
-void CEcon::Init(IConsole *pConsole)
+void CEcon::ConLogout(IConsole::IResult *pResult, void *pUserData)
+{
+	CEcon *pThis = static_cast<CEcon *>(pUserData);
+
+	if(pThis->m_UserClientID >= 0 && pThis->m_UserClientID < NET_MAX_CONSOLE_CLIENTS && pThis->m_aClients[pThis->m_UserClientID].m_State != CClient::STATE_EMPTY)
+		pThis->m_NetConsole.Drop(pThis->m_UserClientID, "Logout");
+}
+
+void CEcon::Init(IConsole *pConsole, CNetBan *pNetBan)
 {
 	m_pConsole = pConsole;
 
@@ -60,6 +68,7 @@ void CEcon::Init(IConsole *pConsole)
 		m_aClients[i].m_State = CClient::STATE_EMPTY;
 
 	m_Ready = false;
+	m_UserClientID = -1;
 
 	if(g_Config.m_EcPort == 0 || g_Config.m_EcPassword[0] == 0)
 		return;
@@ -74,7 +83,7 @@ void CEcon::Init(IConsole *pConsole)
 		BindAddr.port = g_Config.m_EcPort;
 	}
 
-	if(m_NetConsole.Open(BindAddr, 0))
+	if(m_NetConsole.Open(BindAddr, pNetBan, 0))
 	{
 		m_NetConsole.SetCallbacks(NewClientCallback, DelClientCallback, this);
 		m_Ready = true;
@@ -84,6 +93,8 @@ void CEcon::Init(IConsole *pConsole)
 
 		Console()->Chain("ec_output_level", ConchainEconOutputLevelUpdate, this);
 		m_PrintCBIndex = Console()->RegisterPrintCallback(g_Config.m_EcOutputLevel, SendLineCB, this);
+
+		Console()->Register("logout", "", CFGFLAG_ECON, ConLogout, this, "Logout of econ");
 	}
 	else
 		Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD,"econ", "couldn't open socket. port might already be in use");
@@ -115,27 +126,26 @@ void CEcon::Update()
 			else
 			{
 				m_aClients[ClientID].m_AuthTries++;
-				char aBuf[128];
-				str_format(aBuf, sizeof(aBuf), "Wrong password %d/%d.", m_aClients[ClientID].m_AuthTries, MAX_AUTH_TRIES);
-				m_NetConsole.Send(ClientID, aBuf);
+				char aMsg[128];
+				str_format(aMsg, sizeof(aMsg), "Wrong password %d/%d.", m_aClients[ClientID].m_AuthTries, MAX_AUTH_TRIES);
+				m_NetConsole.Send(ClientID, aMsg);
 				if(m_aClients[ClientID].m_AuthTries >= MAX_AUTH_TRIES)
 				{
 					if(!g_Config.m_EcBantime)
 						m_NetConsole.Drop(ClientID, "Too many authentication tries");
 					else
-					{
-						NETADDR Addr = m_NetConsole.ClientAddr(ClientID);
-						m_NetConsole.AddBan(Addr, g_Config.m_EcBantime*60);
-					}
+						m_NetConsole.NetBan()->BanAddr(m_NetConsole.ClientAddr(ClientID), g_Config.m_EcBantime*60, "Too many authentication tries");
 				}
 			}
 		}
 		else if(m_aClients[ClientID].m_State == CClient::STATE_AUTHED)
 		{
 			char aFormatted[256];
-			str_format(aFormatted, sizeof(aBuf), "cid=%d cmd='%s'", ClientID, aBuf);
+			str_format(aFormatted, sizeof(aFormatted), "cid=%d cmd='%s'", ClientID, aBuf);
 			Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "server", aFormatted);
+			m_UserClientID = ClientID;
 			Console()->ExecuteLine(aBuf);
+			m_UserClientID = -1;
 		}
 	}
 
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/shared/econ.h alien-rc4/src//engine/shared/econ.h
--- teeworlds-b177-r50edfd37-source/src//engine/shared/econ.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/shared/econ.h	2012-06-14 23:57:39.000000000 +0200
@@ -3,6 +3,7 @@
 
 #include "network.h"
 
+
 class CEcon
 {
 	enum
@@ -31,9 +32,11 @@ class CEcon
 
 	bool m_Ready;
 	int m_PrintCBIndex;
+	int m_UserClientID;
 
 	static void SendLineCB(const char *pLine, void *pUserData);
 	static void ConchainEconOutputLevelUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData);
+	static void ConLogout(IConsole::IResult *pResult, void *pUserData);
 
 	static int NewClientCallback(int ClientID, void *pUser);
 	static int DelClientCallback(int ClientID, const char *pReason, void *pUser);
@@ -41,7 +44,7 @@ class CEcon
 public:
 	IConsole *Console() { return m_pConsole; }
 
-	void Init(IConsole *pConsole);
+	void Init(IConsole *pConsole, class CNetBan *pNetBan);
 	void Update();
 	void Send(int ClientID, const char *pLine);
 	void Shutdown();
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/shared/masterserver.cpp alien-rc4/src//engine/shared/masterserver.cpp
--- teeworlds-b177-r50edfd37-source/src//engine/shared/masterserver.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/shared/masterserver.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -157,7 +157,7 @@ public:
 						Added = true;
 						break;
 					}
-				
+
 				if(!Added)
 				{
 					for(int i = 0; i < MAX_MASTERSERVERS; ++i)
@@ -192,13 +192,13 @@ public:
 		{
 			char aAddrStr[NETADDR_MAXSTRSIZE];
 			if(m_aMasterServers[i].m_Addr.type != NETTYPE_INVALID)
-				net_addr_str(&m_aMasterServers[i].m_Addr, aAddrStr, sizeof(aAddrStr));
+				net_addr_str(&m_aMasterServers[i].m_Addr, aAddrStr, sizeof(aAddrStr), true);
 			else
 				aAddrStr[0] = 0;
 			char aBuf[256];
-			str_format(aBuf, sizeof(aBuf), "%s %s\n", m_aMasterServers[i].m_aHostname, aAddrStr);
-
+			str_format(aBuf, sizeof(aBuf), "%s %s", m_aMasterServers[i].m_aHostname, aAddrStr);
 			io_write(File, aBuf, str_length(aBuf));
+			io_write_newline(File);
 		}
 
 		io_close(File);
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/shared/netban.cpp alien-rc4/src//engine/shared/netban.cpp
--- teeworlds-b177-r50edfd37-source/src//engine/shared/netban.cpp	1970-01-01 01:00:00.000000000 +0100
+++ alien-rc4/src//engine/shared/netban.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -0,0 +1,603 @@
+#include <base/math.h>
+
+#include <engine/console.h>
+#include <engine/storage.h>
+#include <engine/shared/config.h>
+
+#include "netban.h"
+
+
+bool CNetBan::StrAllnum(const char *pStr)
+{
+	while(*pStr)
+	{
+		if(!(*pStr >= '0' && *pStr <= '9'))
+			return false;
+		pStr++;
+	}
+	return true;
+}
+
+
+CNetBan::CNetHash::CNetHash(const NETADDR *pAddr)
+{
+	if(pAddr->type==NETTYPE_IPV4)
+		m_Hash = (pAddr->ip[0]+pAddr->ip[1]+pAddr->ip[2]+pAddr->ip[3])&0xFF;
+	else
+		m_Hash = (pAddr->ip[0]+pAddr->ip[1]+pAddr->ip[2]+pAddr->ip[3]+pAddr->ip[4]+pAddr->ip[5]+pAddr->ip[6]+pAddr->ip[7]+
+			pAddr->ip[8]+pAddr->ip[9]+pAddr->ip[10]+pAddr->ip[11]+pAddr->ip[12]+pAddr->ip[13]+pAddr->ip[14]+pAddr->ip[15])&0xFF;
+	m_HashIndex = 0;
+}
+
+CNetBan::CNetHash::CNetHash(const CNetRange *pRange)
+{
+	m_Hash = 0;
+	m_HashIndex = 0;
+	for(int i = 0; pRange->m_LB.ip[i] == pRange->m_UB.ip[i]; ++i)
+	{
+		m_Hash += pRange->m_LB.ip[i];
+		++m_HashIndex;
+	}
+	m_Hash &= 0xFF;
+}
+
+int CNetBan::CNetHash::MakeHashArray(const NETADDR *pAddr, CNetHash aHash[17])
+{
+	int Length = pAddr->type==NETTYPE_IPV4 ? 4 : 16;
+	aHash[0].m_Hash = 0;
+	aHash[0].m_HashIndex = 0;
+	for(int i = 1, Sum = 0; i <= Length; ++i)
+	{
+		Sum += pAddr->ip[i-1];
+		aHash[i].m_Hash = Sum&0xFF;
+		aHash[i].m_HashIndex = i%Length;
+	}
+	return Length;
+}
+
+
+template<class T, int HashCount>
+typename CNetBan::CBan<T> *CNetBan::CBanPool<T, HashCount>::Add(const T *pData, const CBanInfo *pInfo,  const CNetHash *pNetHash)
+{
+	if(!m_pFirstFree)
+		return 0;
+
+	// create new ban
+	CBan<T> *pBan = m_pFirstFree;
+	pBan->m_Data = *pData;
+	pBan->m_Info = *pInfo;
+	pBan->m_NetHash = *pNetHash;
+	if(pBan->m_pNext)
+		pBan->m_pNext->m_pPrev = pBan->m_pPrev;
+	if(pBan->m_pPrev)
+		pBan->m_pPrev->m_pNext = pBan->m_pNext;
+	else
+		m_pFirstFree = pBan->m_pNext;
+
+	// add it to the hash list
+	if(m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash])
+		m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash]->m_pHashPrev = pBan;
+	pBan->m_pHashPrev = 0;
+	pBan->m_pHashNext = m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash];
+	m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash] = pBan;
+
+	// insert it into the used list
+	if(m_pFirstUsed)
+	{
+		for(CBan<T> *p = m_pFirstUsed; ; p = p->m_pNext)
+		{
+			if(p->m_Info.m_Expires == CBanInfo::EXPIRES_NEVER || (pInfo->m_Expires != CBanInfo::EXPIRES_NEVER && pInfo->m_Expires <= p->m_Info.m_Expires))
+			{
+				// insert before
+				pBan->m_pNext = p;
+				pBan->m_pPrev = p->m_pPrev;
+				if(p->m_pPrev)
+					p->m_pPrev->m_pNext = pBan;
+				else
+					m_pFirstUsed = pBan;
+				p->m_pPrev = pBan;
+				break;
+			}
+
+			if(!p->m_pNext)
+			{
+				// last entry
+				p->m_pNext = pBan;
+				pBan->m_pPrev = p;
+				pBan->m_pNext = 0;
+				break;
+			}
+		}
+	}
+	else
+	{
+		m_pFirstUsed = pBan;
+		pBan->m_pNext = pBan->m_pPrev = 0;
+	}
+
+	// update ban count
+	++m_CountUsed;
+
+	return pBan;
+}
+
+template<class T, int HashCount>
+int CNetBan::CBanPool<T, HashCount>::Remove(CBan<T> *pBan)
+{
+	if(pBan == 0)
+		return -1;
+
+	// remove from hash list
+	if(pBan->m_pHashNext)
+		pBan->m_pHashNext->m_pHashPrev = pBan->m_pHashPrev;
+	if(pBan->m_pHashPrev)
+		pBan->m_pHashPrev->m_pHashNext = pBan->m_pHashNext;
+	else
+		m_paaHashList[pBan->m_NetHash.m_HashIndex][pBan->m_NetHash.m_Hash] = pBan->m_pHashNext;
+	pBan->m_pHashNext = pBan->m_pHashPrev = 0;
+
+	// remove from used list
+	if(pBan->m_pNext)
+		pBan->m_pNext->m_pPrev = pBan->m_pPrev;
+	if(pBan->m_pPrev)
+		pBan->m_pPrev->m_pNext = pBan->m_pNext;
+	else
+		m_pFirstUsed = pBan->m_pNext;
+
+	// add to recycle list
+	if(m_pFirstFree)
+		m_pFirstFree->m_pPrev = pBan;
+	pBan->m_pPrev = 0;
+	pBan->m_pNext = m_pFirstFree;
+	m_pFirstFree = pBan;
+
+	// update ban count
+	--m_CountUsed;
+
+	return 0;
+}
+
+template<class T, int HashCount>
+void CNetBan::CBanPool<T, HashCount>::Update(CBan<CDataType> *pBan, const CBanInfo *pInfo)
+{
+	pBan->m_Info = *pInfo;
+
+	// remove from used list
+	if(pBan->m_pNext)
+		pBan->m_pNext->m_pPrev = pBan->m_pPrev;
+	if(pBan->m_pPrev)
+		pBan->m_pPrev->m_pNext = pBan->m_pNext;
+	else
+		m_pFirstUsed = pBan->m_pNext;
+
+	// insert it into the used list
+	if(m_pFirstUsed)
+	{
+		for(CBan<T> *p = m_pFirstUsed; ; p = p->m_pNext)
+		{
+			if(p->m_Info.m_Expires == CBanInfo::EXPIRES_NEVER || (pInfo->m_Expires != CBanInfo::EXPIRES_NEVER && pInfo->m_Expires <= p->m_Info.m_Expires))
+			{
+				// insert before
+				pBan->m_pNext = p;
+				pBan->m_pPrev = p->m_pPrev;
+				if(p->m_pPrev)
+					p->m_pPrev->m_pNext = pBan;
+				else
+					m_pFirstUsed = pBan;
+				p->m_pPrev = pBan;
+				break;
+			}
+
+			if(!p->m_pNext)
+			{
+				// last entry
+				p->m_pNext = pBan;
+				pBan->m_pPrev = p;
+				pBan->m_pNext = 0;
+				break;
+			}
+		}
+	}
+	else
+	{
+		m_pFirstUsed = pBan;
+		pBan->m_pNext = pBan->m_pPrev = 0;
+	}
+}
+
+template<class T, int HashCount>
+void CNetBan::CBanPool<T, HashCount>::Reset()
+{
+	mem_zero(m_paaHashList, sizeof(m_paaHashList));
+	mem_zero(m_aBans, sizeof(m_aBans));
+	m_pFirstUsed = 0;
+	m_CountUsed = 0;
+
+	for(int i = 1; i < MAX_BANS-1; ++i)
+	{
+		m_aBans[i].m_pNext = &m_aBans[i+1];
+		m_aBans[i].m_pPrev = &m_aBans[i-1];
+	}
+
+	m_aBans[0].m_pNext = &m_aBans[1];
+	m_aBans[MAX_BANS-1].m_pPrev = &m_aBans[MAX_BANS-2];
+	m_pFirstFree = &m_aBans[0];
+}
+
+template<class T, int HashCount>
+typename CNetBan::CBan<T> *CNetBan::CBanPool<T, HashCount>::Get(int Index) const
+{
+	if(Index < 0 || Index >= Num())
+		return 0;
+
+	for(CNetBan::CBan<T> *pBan = m_pFirstUsed; pBan; pBan = pBan->m_pNext, --Index)
+	{
+		if(Index == 0)
+			return pBan;
+	}
+
+	return 0;
+}
+
+
+template<class T>
+void CNetBan::MakeBanInfo(const CBan<T> *pBan, char *pBuf, unsigned BuffSize, int Type) const
+{
+	if(pBan == 0)
+	{
+		if(BuffSize > 0)
+			pBuf[0] = 0;
+		return;
+	}
+	
+	// build type based part
+	char aBuf[256];
+	if(Type == MSGTYPE_PLAYER)
+		str_copy(aBuf, "You have been banned", sizeof(aBuf));
+	else
+	{
+		char aTemp[256];
+		switch(Type)
+		{
+		case MSGTYPE_LIST:
+			str_format(aBuf, sizeof(aBuf), "%s banned", NetToString(&pBan->m_Data, aTemp, sizeof(aTemp))); break;
+		case MSGTYPE_BANADD:
+			str_format(aBuf, sizeof(aBuf), "banned %s", NetToString(&pBan->m_Data, aTemp, sizeof(aTemp))); break;
+		case MSGTYPE_BANREM:
+			str_format(aBuf, sizeof(aBuf), "unbanned %s", NetToString(&pBan->m_Data, aTemp, sizeof(aTemp))); break;
+		default:
+			aBuf[0] = 0;
+		}
+	}
+
+	// add info part
+	if(pBan->m_Info.m_Expires != CBanInfo::EXPIRES_NEVER)
+	{
+		int Mins = ((pBan->m_Info.m_Expires-time_timestamp()) + 59) / 60;
+		if(Mins <= 1)
+			str_format(pBuf, BuffSize, "%s for 1 minute (%s)", aBuf, pBan->m_Info.m_aReason);
+		else
+			str_format(pBuf, BuffSize, "%s for %d minutes (%s)", aBuf, Mins, pBan->m_Info.m_aReason);
+	}
+	else
+		str_format(pBuf, BuffSize, "%s for life (%s)", aBuf, pBan->m_Info.m_aReason);
+}
+
+template<class T>
+int CNetBan::Ban(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason)
+{
+	// do not ban localhost
+	if(NetMatch(pData, &m_LocalhostIPV4) || NetMatch(pData, &m_LocalhostIPV6))
+	{
+		Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (localhost)");
+		return -1;
+	}
+
+	int Stamp = Seconds > 0 ? time_timestamp()+Seconds : CBanInfo::EXPIRES_NEVER;
+
+	// set up info
+	CBanInfo Info = {0};
+	Info.m_Expires = Stamp;
+	str_copy(Info.m_aReason, pReason, sizeof(Info.m_aReason));
+
+	// check if it already exists
+	CNetHash NetHash(pData);
+	CBan<typename T::CDataType> *pBan = pBanPool->Find(pData, &NetHash);
+	if(pBan)
+	{
+		// adjust the ban
+		pBanPool->Update(pBan, &Info);
+		char aBuf[128];
+		MakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_LIST);
+		Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf);
+		return 1;
+	}
+
+	// add ban and print result
+	pBan = pBanPool->Add(pData, &Info, &NetHash);
+	if(pBan)
+	{
+		char aBuf[128];
+		MakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_BANADD);
+		Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf);
+		return 0;
+	}
+	else
+		Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (full banlist)");
+	return -1;
+}
+
+template<class T>
+int CNetBan::Unban(T *pBanPool, const typename T::CDataType *pData)
+{
+	CNetHash NetHash(pData);
+	CBan<typename T::CDataType> *pBan = pBanPool->Find(pData, &NetHash);
+	if(pBan)
+	{
+		char aBuf[256];
+		MakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_BANREM);
+		pBanPool->Remove(pBan);
+		Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf);
+		return 0;
+	}
+	else
+		Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "unban failed (invalid entry)");
+	return -1;
+}
+
+void CNetBan::Init(IConsole *pConsole, IStorage *pStorage)
+{
+	m_pConsole = pConsole;
+	m_pStorage = pStorage;
+	m_BanAddrPool.Reset();
+	m_BanRangePool.Reset();
+
+	net_host_lookup("localhost", &m_LocalhostIPV4, NETTYPE_IPV4);
+	net_host_lookup("localhost", &m_LocalhostIPV6, NETTYPE_IPV6);
+
+	Console()->Register("ban", "s?ir", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConBan, this, "Ban ip for x minutes for any reason");
+	Console()->Register("ban_range", "ss?ir", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConBanRange, this, "Ban ip range for x minutes for any reason");
+	Console()->Register("unban", "s", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConUnban, this, "Unban ip/banlist entry");
+	Console()->Register("unban_range", "ss", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConUnbanRange, this, "Unban ip range");
+	Console()->Register("unban_all", "", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConUnbanAll, this, "Unban all entries");
+	Console()->Register("bans", "", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConBans, this, "Show banlist");
+	Console()->Register("bans_save", "s", CFGFLAG_SERVER|CFGFLAG_MASTER|CFGFLAG_STORE, ConBansSave, this, "Save banlist in a file");
+}
+
+void CNetBan::Update()
+{
+	int Now = time_timestamp();
+
+	// remove expired bans
+	char aBuf[256], aNetStr[256];
+	while(m_BanAddrPool.First() && m_BanAddrPool.First()->m_Info.m_Expires != CBanInfo::EXPIRES_NEVER && m_BanAddrPool.First()->m_Info.m_Expires < Now)
+	{
+		str_format(aBuf, sizeof(aBuf), "ban %s expired", NetToString(&m_BanAddrPool.First()->m_Data, aNetStr, sizeof(aNetStr)));
+		Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf);
+		m_BanAddrPool.Remove(m_BanAddrPool.First());
+	}
+	while(m_BanRangePool.First() && m_BanRangePool.First()->m_Info.m_Expires != CBanInfo::EXPIRES_NEVER && m_BanRangePool.First()->m_Info.m_Expires < Now)
+	{
+		str_format(aBuf, sizeof(aBuf), "ban %s expired", NetToString(&m_BanRangePool.First()->m_Data, aNetStr, sizeof(aNetStr)));
+		Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf);
+		m_BanRangePool.Remove(m_BanRangePool.First());
+	}
+}
+
+int CNetBan::BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason)
+{
+	return Ban(&m_BanAddrPool, pAddr, Seconds, pReason);
+}
+
+int CNetBan::BanRange(const CNetRange *pRange, int Seconds, const char *pReason)
+{
+	if(pRange->IsValid())
+		return Ban(&m_BanRangePool, pRange, Seconds, pReason);
+
+	Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (invalid range)");
+	return -1;
+}
+
+int CNetBan::UnbanByAddr(const NETADDR *pAddr)
+{
+	return Unban(&m_BanAddrPool, pAddr);
+}
+
+int CNetBan::UnbanByRange(const CNetRange *pRange)
+{
+	if(pRange->IsValid())
+		return Unban(&m_BanRangePool, pRange);
+	
+	Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban failed (invalid range)");
+	return -1;
+}
+
+int CNetBan::UnbanByIndex(int Index)
+{
+	int Result;
+	char aBuf[256];
+	CBanAddr *pBan = m_BanAddrPool.Get(Index);
+	if(pBan)
+	{
+		NetToString(&pBan->m_Data, aBuf, sizeof(aBuf));
+		Result = m_BanAddrPool.Remove(pBan);
+	}
+	else
+	{
+		CBanRange *pBan = m_BanRangePool.Get(Index-m_BanAddrPool.Num());
+		if(pBan)
+		{
+			NetToString(&pBan->m_Data, aBuf, sizeof(aBuf));
+			Result = m_BanRangePool.Remove(pBan);
+		}
+		else
+		{
+			Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "unban failed (invalid index)");
+			return -1;
+		}
+	}
+
+	char aMsg[256];
+	str_format(aMsg, sizeof(aMsg), "unbanned index %i (%s)", Index, aBuf);
+	Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aMsg);
+	return Result;
+}
+
+bool CNetBan::IsBanned(const NETADDR *pAddr, char *pBuf, unsigned BufferSize) const
+{
+	CNetHash aHash[17];
+	int Length = CNetHash::MakeHashArray(pAddr, aHash);
+
+	// check ban adresses
+	CBanAddr *pBan = m_BanAddrPool.Find(pAddr, &aHash[Length]);
+	if(pBan)
+	{
+		MakeBanInfo(pBan, pBuf, BufferSize, MSGTYPE_PLAYER);
+		return true;
+	}
+
+	// check ban ranges
+	for(int i = Length-1; i >= 0; --i)
+	{
+		for(CBanRange *pBan = m_BanRangePool.First(&aHash[i]); pBan; pBan = pBan->m_pHashNext)
+		{
+			if(NetMatch(&pBan->m_Data, pAddr, i, Length))
+			{
+				MakeBanInfo(pBan, pBuf, BufferSize, MSGTYPE_PLAYER);
+				return true;
+			}
+		}
+	}
+	
+	return false;
+}
+
+void CNetBan::ConBan(IConsole::IResult *pResult, void *pUser)
+{
+	CNetBan *pThis = static_cast<CNetBan *>(pUser);
+
+	const char *pStr = pResult->GetString(0);
+	int Minutes = pResult->NumArguments()>1 ? clamp(pResult->GetInteger(1), 0, 44640) : 30;
+	const char *pReason = pResult->NumArguments()>2 ? pResult->GetString(2) : "No reason given";
+
+	NETADDR Addr;
+	if(net_addr_from_str(&Addr, pStr) == 0)
+		pThis->BanAddr(&Addr, Minutes*60, pReason);
+	else
+		pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (invalid network address)");
+}
+
+void CNetBan::ConBanRange(IConsole::IResult *pResult, void *pUser)
+{
+	CNetBan *pThis = static_cast<CNetBan *>(pUser);
+
+	const char *pStr1 = pResult->GetString(0);
+	const char *pStr2 = pResult->GetString(1);
+	int Minutes = pResult->NumArguments()>2 ? clamp(pResult->GetInteger(2), 0, 44640) : 30;
+	const char *pReason = pResult->NumArguments()>3 ? pResult->GetString(3) : "No reason given";
+
+	CNetRange Range;
+	if(net_addr_from_str(&Range.m_LB, pStr1) == 0 && net_addr_from_str(&Range.m_UB, pStr2) == 0)
+		pThis->BanRange(&Range, Minutes*60, pReason);
+	else
+		pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "ban error (invalid range)");
+}
+
+void CNetBan::ConUnban(IConsole::IResult *pResult, void *pUser)
+{
+	CNetBan *pThis = static_cast<CNetBan *>(pUser);
+
+	const char *pStr = pResult->GetString(0);
+	if(StrAllnum(pStr))
+		pThis->UnbanByIndex(str_toint(pStr));
+	else
+	{
+		NETADDR Addr;
+		if(net_addr_from_str(&Addr, pStr) == 0)
+			pThis->UnbanByAddr(&Addr);
+		else
+			pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "unban error (invalid network address)");
+	}
+}
+
+void CNetBan::ConUnbanRange(IConsole::IResult *pResult, void *pUser)
+{
+	CNetBan *pThis = static_cast<CNetBan *>(pUser);
+
+	const char *pStr1 = pResult->GetString(0);
+	const char *pStr2 = pResult->GetString(1);
+
+	CNetRange Range;
+	if(net_addr_from_str(&Range.m_LB, pStr1) == 0 && net_addr_from_str(&Range.m_UB, pStr2) == 0)
+		pThis->UnbanByRange(&Range);
+	else
+		pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "unban error (invalid range)");
+}
+
+void CNetBan::ConUnbanAll(IConsole::IResult *pResult, void *pUser)
+{
+	CNetBan *pThis = static_cast<CNetBan *>(pUser);
+
+	pThis->UnbanAll();
+	pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", "unbanned all entries");
+}
+
+void CNetBan::ConBans(IConsole::IResult *pResult, void *pUser)
+{
+	CNetBan *pThis = static_cast<CNetBan *>(pUser);
+
+	int Count = 0;
+	char aBuf[256], aMsg[256];
+	for(CBanAddr *pBan = pThis->m_BanAddrPool.First(); pBan; pBan = pBan->m_pNext)
+	{
+		pThis->MakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_LIST);
+		str_format(aMsg, sizeof(aMsg), "#%i %s", Count++, aBuf);
+		pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aMsg);
+	}
+	for(CBanRange *pBan = pThis->m_BanRangePool.First(); pBan; pBan = pBan->m_pNext)
+	{
+		pThis->MakeBanInfo(pBan, aBuf, sizeof(aBuf), MSGTYPE_LIST);
+		str_format(aMsg, sizeof(aMsg), "#%i %s", Count++, aBuf);
+		pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aMsg);
+	}
+	str_format(aMsg, sizeof(aMsg), "%d %s", Count, Count==1?"ban":"bans");
+	pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aMsg);
+}
+
+void CNetBan::ConBansSave(IConsole::IResult *pResult, void *pUser)
+{
+	CNetBan *pThis = static_cast<CNetBan *>(pUser);
+
+	char aBuf[256];
+	IOHANDLE File = pThis->Storage()->OpenFile(pResult->GetString(0), IOFLAG_WRITE, IStorage::TYPE_SAVE);
+	if(!File)
+	{
+		str_format(aBuf, sizeof(aBuf), "failed to save banlist to '%s'", pResult->GetString(0));
+		pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf);
+		return;
+	}
+
+	int Now = time_timestamp();
+	char aAddrStr1[NETADDR_MAXSTRSIZE], aAddrStr2[NETADDR_MAXSTRSIZE];
+	for(CBanAddr *pBan = pThis->m_BanAddrPool.First(); pBan; pBan = pBan->m_pNext)
+	{
+		int Min = pBan->m_Info.m_Expires>-1 ? (pBan->m_Info.m_Expires-Now+59)/60 : -1;
+		net_addr_str(&pBan->m_Data, aAddrStr1, sizeof(aAddrStr1), false);
+		str_format(aBuf, sizeof(aBuf), "ban %s %i %s", aAddrStr1, Min, pBan->m_Info.m_aReason);
+		io_write(File, aBuf, str_length(aBuf));
+		io_write_newline(File);
+	}
+	for(CBanRange *pBan = pThis->m_BanRangePool.First(); pBan; pBan = pBan->m_pNext)
+	{
+		int Min = pBan->m_Info.m_Expires>-1 ? (pBan->m_Info.m_Expires-Now+59)/60 : -1;
+		net_addr_str(&pBan->m_Data.m_LB, aAddrStr1, sizeof(aAddrStr1), false);
+		net_addr_str(&pBan->m_Data.m_UB, aAddrStr2, sizeof(aAddrStr2), false);
+		str_format(aBuf, sizeof(aBuf), "ban_range %s %s %i %s", aAddrStr1, aAddrStr2, Min, pBan->m_Info.m_aReason);	
+		io_write(File, aBuf, str_length(aBuf));
+		io_write_newline(File);
+	}
+
+	io_close(File);
+	str_format(aBuf, sizeof(aBuf), "saved banlist to '%s'", pResult->GetString(0));
+	pThis->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "net_ban", aBuf);
+}
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/shared/netban.h alien-rc4/src//engine/shared/netban.h
--- teeworlds-b177-r50edfd37-source/src//engine/shared/netban.h	1970-01-01 01:00:00.000000000 +0100
+++ alien-rc4/src//engine/shared/netban.h	2012-06-14 23:57:39.000000000 +0200
@@ -0,0 +1,193 @@
+#ifndef ENGINE_SHARED_NETBAN_H
+#define ENGINE_SHARED_NETBAN_H
+
+#include <base/system.h>
+
+
+inline int NetComp(const NETADDR *pAddr1, const NETADDR *pAddr2)
+{
+	return mem_comp(pAddr1, pAddr2, pAddr1->type==NETTYPE_IPV4 ? 8 : 20);
+}
+
+class CNetRange
+{
+public:
+	NETADDR m_LB;
+	NETADDR m_UB;
+
+	bool IsValid() const { return m_LB.type == m_UB.type && NetComp(&m_LB, &m_UB) < 0; }
+};
+
+inline int NetComp(const CNetRange *pRange1, const CNetRange *pRange2)
+{
+	return NetComp(&pRange1->m_LB, &pRange2->m_LB) || NetComp(&pRange1->m_UB, &pRange2->m_UB);
+}
+
+
+class CNetBan
+{
+protected:
+	bool NetMatch(const NETADDR *pAddr1, const NETADDR *pAddr2) const
+	{
+		return NetComp(pAddr1, pAddr2) == 0;
+	}
+
+	bool NetMatch(const CNetRange *pRange, const NETADDR *pAddr, int Start, int Length) const
+	{
+		return pRange->m_LB.type == pAddr->type &&
+			mem_comp(&pRange->m_LB.ip[Start], &pAddr->ip[Start], Length-Start) <= 0 && mem_comp(&pRange->m_UB.ip[Start], &pAddr->ip[Start], Length-Start) >= 0;
+	}
+
+	bool NetMatch(const CNetRange *pRange, const NETADDR *pAddr) const
+	{
+		return NetMatch(pRange, pAddr, 0,  pRange->m_LB.type==NETTYPE_IPV4 ? 4 : 16);
+	}
+
+	const char *NetToString(const NETADDR *pData, char *pBuffer, unsigned BufferSize) const
+	{
+		char aAddrStr[NETADDR_MAXSTRSIZE];
+		net_addr_str(pData, aAddrStr, sizeof(aAddrStr), false);
+		str_format(pBuffer, BufferSize, "'%s'", aAddrStr);
+		return pBuffer;
+	}
+
+	const char *NetToString(const CNetRange *pData, char *pBuffer, unsigned BufferSize) const
+	{
+		char aAddrStr1[NETADDR_MAXSTRSIZE], aAddrStr2[NETADDR_MAXSTRSIZE];
+		net_addr_str(&pData->m_LB, aAddrStr1, sizeof(aAddrStr1), false);
+		net_addr_str(&pData->m_UB, aAddrStr2, sizeof(aAddrStr2), false);
+		str_format(pBuffer, BufferSize, "'%s' - '%s'", aAddrStr1, aAddrStr2);
+		return pBuffer;
+	}
+
+	// todo: move?
+	static bool StrAllnum(const char *pStr);
+
+	class CNetHash
+	{
+	public:
+		int m_Hash;
+		int m_HashIndex;	// matching parts for ranges, 0 for addr
+
+		CNetHash() {}	
+		CNetHash(const NETADDR *pAddr);
+		CNetHash(const CNetRange *pRange);
+
+		static int MakeHashArray(const NETADDR *pAddr, CNetHash aHash[17]);
+	};
+
+	struct CBanInfo
+	{
+		enum
+		{
+			EXPIRES_NEVER=-1,
+			REASON_LENGTH=64,
+		};
+		int m_Expires;
+		char m_aReason[REASON_LENGTH];
+	};
+
+	template<class T> struct CBan
+	{
+		T m_Data;
+		CBanInfo m_Info;
+		CNetHash m_NetHash;
+
+		// hash list
+		CBan *m_pHashNext;
+		CBan *m_pHashPrev;
+
+		// used or free list
+		CBan *m_pNext;
+		CBan *m_pPrev;
+	};
+
+	template<class T, int HashCount> class CBanPool
+	{
+	public:
+		typedef T CDataType;
+
+		CBan<CDataType> *Add(const CDataType *pData, const CBanInfo *pInfo, const CNetHash *pNetHash);
+		int Remove(CBan<CDataType> *pBan);
+		void Update(CBan<CDataType> *pBan, const CBanInfo *pInfo);
+		void Reset();
+	
+		int Num() const { return m_CountUsed; }
+		bool IsFull() const { return m_CountUsed == MAX_BANS; }
+
+		CBan<CDataType> *First() const { return m_pFirstUsed; }
+		CBan<CDataType> *First(const CNetHash *pNetHash) const { return m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash]; }
+		CBan<CDataType> *Find(const CDataType *pData, const CNetHash *pNetHash) const
+		{
+			for(CBan<CDataType> *pBan = m_paaHashList[pNetHash->m_HashIndex][pNetHash->m_Hash]; pBan; pBan = pBan->m_pHashNext)
+			{
+				if(NetComp(&pBan->m_Data, pData) == 0)
+					return pBan;
+			}
+
+			return 0;
+		}
+		CBan<CDataType> *Get(int Index) const;
+
+	private:
+		enum
+		{
+			MAX_BANS=1024,
+		};
+
+		CBan<CDataType> *m_paaHashList[HashCount][256];
+		CBan<CDataType> m_aBans[MAX_BANS];
+		CBan<CDataType> *m_pFirstFree;
+		CBan<CDataType> *m_pFirstUsed;
+		int m_CountUsed;
+	};
+
+	typedef CBanPool<NETADDR, 1> CBanAddrPool;
+	typedef CBanPool<CNetRange, 16> CBanRangePool;
+	typedef CBan<NETADDR> CBanAddr;
+	typedef CBan<CNetRange> CBanRange;
+	
+	template<class T> void MakeBanInfo(const CBan<T> *pBan, char *pBuf, unsigned BuffSize, int Type) const;
+	template<class T> int Ban(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason);
+	template<class T> int Unban(T *pBanPool, const typename T::CDataType *pData);
+
+	class IConsole *m_pConsole;
+	class IStorage *m_pStorage;
+	CBanAddrPool m_BanAddrPool;
+	CBanRangePool m_BanRangePool;
+	NETADDR m_LocalhostIPV4, m_LocalhostIPV6;
+
+public:
+	enum
+	{
+		MSGTYPE_PLAYER=0,
+		MSGTYPE_LIST,
+		MSGTYPE_BANADD,
+		MSGTYPE_BANREM,
+	};
+
+	class IConsole *Console() const { return m_pConsole; }
+	class IStorage *Storage() const { return m_pStorage; }
+
+	virtual ~CNetBan() {}
+	virtual void Init(class IConsole *pConsole, class IStorage *pStorage);
+	void Update();
+
+	virtual int BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason);
+	virtual int BanRange(const CNetRange *pRange, int Seconds, const char *pReason);
+	int UnbanByAddr(const NETADDR *pAddr);
+	int UnbanByRange(const CNetRange *pRange);
+	int UnbanByIndex(int Index);
+	void UnbanAll() { m_BanAddrPool.Reset(); m_BanRangePool.Reset(); }
+	bool IsBanned(const NETADDR *pAddr, char *pBuf, unsigned BufferSize) const;
+
+	static void ConBan(class IConsole::IResult *pResult, void *pUser);
+	static void ConBanRange(class IConsole::IResult *pResult, void *pUser);
+	static void ConUnban(class IConsole::IResult *pResult, void *pUser);
+	static void ConUnbanRange(class IConsole::IResult *pResult, void *pUser);
+	static void ConUnbanAll(class IConsole::IResult *pResult, void *pUser);
+	static void ConBans(class IConsole::IResult *pResult, void *pUser);
+	static void ConBansSave(class IConsole::IResult *pResult, void *pUser);
+};
+
+#endif
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/shared/network_console_conn.cpp alien-rc4/src//engine/shared/network_console_conn.cpp
--- teeworlds-b177-r50edfd37-source/src//engine/shared/network_console_conn.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/shared/network_console_conn.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -181,6 +181,6 @@ int CConsoleNetConnection::Send(const ch
 		pData += Send;
 		Length -= Send;
 	}
-	
+
 	return 0;
 }
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/shared/network_console.cpp alien-rc4/src//engine/shared/network_console.cpp
--- teeworlds-b177-r50edfd37-source/src//engine/shared/network_console.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/shared/network_console.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -1,15 +1,21 @@
 /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
 /* If you are missing that file, acquire a complete release at teeworlds.com.                */
 #include <base/system.h>
+
+#include <engine/console.h>
+
+#include "netban.h"
 #include "network.h"
 
-bool CNetConsole::Open(NETADDR BindAddr, int Flags)
+
+bool CNetConsole::Open(NETADDR BindAddr, CNetBan *pNetBan, int Flags)
 {
 	// zero out the whole structure
 	mem_zero(this, sizeof(*this));
 	m_Socket.type = NETTYPE_INVALID;
 	m_Socket.ipv4sock = -1;
 	m_Socket.ipv6sock = -1;
+	m_pNetBan = pNetBan;
 
 	// open socket
 	m_Socket = net_tcp_create(BindAddr);
@@ -56,7 +62,7 @@ int CNetConsole::AcceptClient(NETSOCKET
 {
 	char aError[256] = { 0 };
 	int FreeSlot = -1;
-	
+
 	// look for free slot or multiple client
 	for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++)
 	{
@@ -64,8 +70,7 @@ int CNetConsole::AcceptClient(NETSOCKET
 			FreeSlot = i;
 		if(m_aSlots[i].m_Connection.State() != NET_CONNSTATE_OFFLINE)
 		{
-			NETADDR PeerAddr = m_aSlots[i].m_Connection.PeerAddress();
-			if(net_addr_comp(pAddr, &PeerAddr) == 0)
+			if(net_addr_comp(pAddr, m_aSlots[i].m_Connection.PeerAddress()) == 0)
 			{
 				str_copy(aError, "only one client per IP allowed", sizeof(aError));
 				break;
@@ -99,26 +104,16 @@ int CNetConsole::Update()
 
 	if(net_tcp_accept(m_Socket, &Socket, &Addr) > 0)
 	{
-		int Index = FindBan(Addr);
-		if(Index == -1)
-			AcceptClient(Socket, &Addr);
-		else
+		// check if we just should drop the packet
+		char aBuf[128];
+		if(NetBan() && NetBan()->IsBanned(&Addr, aBuf, sizeof(aBuf)))
 		{
-			char aBuf[128];
-			if(m_aBans[Index].m_Expires > -1)
-			{
-				int Mins = (m_aBans[Index].m_Expires-time_timestamp()+ 59) / 60;
-				if(Mins <= 1)
-					str_format(aBuf, sizeof(aBuf), "You have been banned for 1 minute");
-				else
-					str_format(aBuf, sizeof(aBuf), "You have been banned for %d minutes", Mins);
-			}
-			else
-				str_format(aBuf, sizeof(aBuf), "You have been banned for life");
-			
+			// banned, reply with a message and drop
 			net_tcp_send(Socket, aBuf, str_length(aBuf));
 			net_tcp_close(Socket);
 		}
+		else
+			AcceptClient(Socket, &Addr);
 	}
 
 	for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++)
@@ -129,8 +124,6 @@ int CNetConsole::Update()
 			Drop(i, m_aSlots[i].m_Connection.ErrorString());
 	}
 
-	UpdateBans();
-
 	return 0;
 }
 
@@ -155,65 +148,3 @@ int CNetConsole::Send(int ClientID, cons
 	else
 		return -1;
 }
-
-int CNetConsole::FindBan(NETADDR Addr)
-{
-	Addr.port = 0;
-	for(int i = 0; i < m_NumBans; i++)
-		if(net_addr_comp(&m_aBans[i].m_Addr, &Addr) == 0)
-			return i;
-
-	return -1;
-}
-
-bool CNetConsole::AddBan(NETADDR Addr, int Seconds)
-{
-	if(m_NumBans == MAX_BANS)
-		return false;
-	
-	Addr.port = 0;
-	int Index = FindBan(Addr);
-	if(Index == -1)
-	{
-		Index = m_NumBans++;
-		m_aBans[Index].m_Addr = Addr;
-	}
-	m_aBans[Index].m_Expires = Seconds>0 ? time_timestamp()+Seconds : -1;
-
-	for(int i = 0; i < NET_MAX_CONSOLE_CLIENTS; i++)
-	{
-		if(m_aSlots[i].m_Connection.State() != NET_CONNSTATE_OFFLINE)
-		{
-			NETADDR PeerAddr = m_aSlots[i].m_Connection.PeerAddress();
-			PeerAddr.port = 0;
-			if(net_addr_comp(&Addr, &PeerAddr) == 0)
-			{
-				char aBuf[128];
-				if(Seconds>0)
-				{
-					int Mins = (Seconds + 59) / 60;
-					if(Mins <= 1)
-						str_format(aBuf, sizeof(aBuf), "You have been banned for 1 minute");
-					else
-						str_format(aBuf, sizeof(aBuf), "You have been banned for %d minutes", Mins);
-				}
-				else
-					str_format(aBuf, sizeof(aBuf), "You have been banned for life");
-				Drop(i, aBuf);
-			}
-		}
-	}
-	return true;
-}
-
-void CNetConsole::UpdateBans()
-{
-	int Now = time_timestamp();
-	for(int i = 0; i < m_NumBans; ++i)
-		if(m_aBans[i].m_Expires > 0 && m_aBans[i].m_Expires < Now)
-		{
-			m_aBans[i] = m_aBans[m_NumBans-1];
-			--m_NumBans;
-			break;
-		}
-}
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/shared/network.h alien-rc4/src//engine/shared/network.h
--- teeworlds-b177-r50edfd37-source/src//engine/shared/network.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/shared/network.h	2012-06-14 23:57:39.000000000 +0200
@@ -73,8 +73,6 @@ enum
 	NET_CTRLMSG_ACCEPT=3,
 	NET_CTRLMSG_CLOSE=4,
 
-	NET_SERVER_MAXBANS=1024,
-
 	NET_CONN_BUFFERSIZE=1024*32,
 
 	NET_ENUM_TERMINATOR
@@ -182,7 +180,7 @@ public:
 	const char *ErrorString();
 	void SignalResend();
 	int State() const { return m_State; }
-	NETADDR PeerAddress() const { return m_PeerAddr; }
+	const NETADDR *PeerAddress() const { return &m_PeerAddr; }
 
 	void ResetErrorString() { m_ErrorString[0] = 0; }
 	const char *ErrorString() const { return m_ErrorString; }
@@ -214,7 +212,7 @@ public:
 	void Disconnect(const char *pReason);
 
 	int State() const { return m_State; }
-	NETADDR PeerAddress() const { return m_PeerAddr; }
+	const NETADDR *PeerAddress() const { return &m_PeerAddr; }
 	const char *ErrorString() const { return m_aErrorString; }
 
 	void Reset();
@@ -244,59 +242,34 @@ public:
 // server side
 class CNetServer
 {
-public:
-	struct CBanInfo
-	{
-		NETADDR m_Addr;
-		int m_Expires;
-		char m_Reason[128];
-	};
-
-private:
 	struct CSlot
 	{
 	public:
 		CNetConnection m_Connection;
 	};
 
-	struct CBan
-	{
-	public:
-		CBanInfo m_Info;
-
-		// hash list
-		CBan *m_pHashNext;
-		CBan *m_pHashPrev;
-
-		// used or free list
-		CBan *m_pNext;
-		CBan *m_pPrev;
-	};
-
-
 	NETSOCKET m_Socket;
+	class CNetBan *m_pNetBan;
 	CSlot m_aSlots[NET_MAX_CLIENTS];
 	int m_MaxClients;
 	int m_MaxClientsPerIP;
 
-	CBan *m_aBans[256];
-	CBan m_BanPool[NET_SERVER_MAXBANS];
-	CBan *m_BanPool_FirstFree;
-	CBan *m_BanPool_FirstUsed;
-
 	NETFUNC_NEWCLIENT m_pfnNewClient;
 	NETFUNC_DELCLIENT m_pfnDelClient;
 	void *m_UserPtr;
 
 	CNetRecvUnpacker m_RecvUnpacker;
-
-	void BanRemoveByObject(CBan *pBan);
+	
+	int64 m_LastConTry;
+	int64 m_PrevLastConTry;
+	NETADDR m_LastConAddr;
+	NETADDR m_PrevLastConAddr;
 
 public:
 	int SetCallbacks(NETFUNC_NEWCLIENT pfnNewClient, NETFUNC_DELCLIENT pfnDelClient, void *pUser);
 
 	//
-	bool Open(NETADDR BindAddr, int MaxClients, int MaxClientsPerIP, int Flags);
+	bool Open(NETADDR BindAddr, class CNetBan *pNetBan, int MaxClients, int MaxClientsPerIP, int Flags);
 	int Close();
 
 	//
@@ -307,16 +280,11 @@ public:
 	//
 	int Drop(int ClientID, const char *pReason);
 
-	// banning
-	int BanAdd(NETADDR Addr, int Seconds, const char *pReason);
-	int BanRemove(NETADDR Addr);
-	int BanNum(); // caution, slow
-	int BanGet(int Index, CBanInfo *pInfo); // caution, slow
-
 	// status requests
-	NETADDR ClientAddr(int ClientID) const { return m_aSlots[ClientID].m_Connection.PeerAddress(); }
+	const NETADDR *ClientAddr(int ClientID) const { return m_aSlots[ClientID].m_Connection.PeerAddress(); }
 	NETSOCKET Socket() const { return m_Socket; }
-	int NetType() { return m_Socket.type; }
+	class CNetBan *NetBan() const { return m_pNetBan; }
+	int NetType() const { return m_Socket.type; }
 	int MaxClients() const { return m_MaxClients; }
 
 	//
@@ -325,27 +293,13 @@ public:
 
 class CNetConsole
 {
-	enum
-	{
-		MAX_BANS=128,
-	};
-
-	int FindBan(NETADDR Addr);
-	void UpdateBans();
-
-	struct CBanEntry
-	{
-		NETADDR m_Addr;
-		int m_Expires;
-	} m_aBans[MAX_BANS];
-	int m_NumBans;
-
 	struct CSlot
 	{
 		CConsoleNetConnection m_Connection;
 	};
 
 	NETSOCKET m_Socket;
+	class CNetBan *m_pNetBan;
 	CSlot m_aSlots[NET_MAX_CONSOLE_CLIENTS];
 
 	NETFUNC_NEWCLIENT m_pfnNewClient;
@@ -358,7 +312,7 @@ public:
 	void SetCallbacks(NETFUNC_NEWCLIENT pfnNewClient, NETFUNC_DELCLIENT pfnDelClient, void *pUser);
 
 	//
-	bool Open(NETADDR BindAddr, int Flags);
+	bool Open(NETADDR BindAddr, class CNetBan *pNetBan, int Flags);
 	int Close();
 
 	//
@@ -370,10 +324,9 @@ public:
 	int AcceptClient(NETSOCKET Socket, const NETADDR *pAddr);
 	int Drop(int ClientID, const char *pReason);
 
-	bool AddBan(NETADDR Addr, int Seconds);
-
 	// status requests
-	NETADDR ClientAddr(int ClientID) const { return m_aSlots[ClientID].m_Connection.PeerAddress(); }
+	const NETADDR *ClientAddr(int ClientID) const { return m_aSlots[ClientID].m_Connection.PeerAddress(); }
+	class CNetBan *NetBan() const { return m_pNetBan; }
 };
 
 
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/shared/network_server.cpp alien-rc4/src//engine/shared/network_server.cpp
--- teeworlds-b177-r50edfd37-source/src//engine/shared/network_server.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/shared/network_server.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -1,32 +1,15 @@
 /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
 /* If you are missing that file, acquire a complete release at teeworlds.com.                */
 #include <base/system.h>
-#include "network.h"
 
-#define MACRO_LIST_LINK_FIRST(Object, First, Prev, Next) \
-	{ if(First) First->Prev = Object; \
-	Object->Prev = (struct CBan *)0; \
-	Object->Next = First; \
-	First = Object; }
-
-#define MACRO_LIST_LINK_AFTER(Object, After, Prev, Next) \
-	{ Object->Prev = After; \
-	Object->Next = After->Next; \
-	After->Next = Object; \
-	if(Object->Next) \
-		Object->Next->Prev = Object; \
-	}
+#include <engine/console.h>
+#include <engine/config.h>
 
-#define MACRO_LIST_UNLINK(Object, First, Prev, Next) \
-	{ if(Object->Next) Object->Next->Prev = Object->Prev; \
-	if(Object->Prev) Object->Prev->Next = Object->Next; \
-	else First = Object->Next; \
-	Object->Next = 0; Object->Prev = 0; }
+#include "netban.h"
+#include "network.h"
 
-#define MACRO_LIST_FIND(Start, Next, Expression) \
-	{ while(Start && !(Expression)) Start = Start->Next; }
 
-bool CNetServer::Open(NETADDR BindAddr, int MaxClients, int MaxClientsPerIP, int Flags)
+bool CNetServer::Open(NETADDR BindAddr, CNetBan *pNetBan, int MaxClients, int MaxClientsPerIP, int Flags)
 {
 	// zero out the whole structure
 	mem_zero(this, sizeof(*this));
@@ -36,6 +19,8 @@ bool CNetServer::Open(NETADDR BindAddr,
 	if(!m_Socket.type)
 		return false;
 
+	m_pNetBan = pNetBan;
+
 	// clamp clients
 	m_MaxClients = MaxClients;
 	if(m_MaxClients > NET_MAX_CLIENTS)
@@ -48,16 +33,9 @@ bool CNetServer::Open(NETADDR BindAddr,
 	for(int i = 0; i < NET_MAX_CLIENTS; i++)
 		m_aSlots[i].m_Connection.Init(m_Socket);
 
-	// setup all pointers for bans
-	for(int i = 1; i < NET_SERVER_MAXBANS-1; i++)
-	{
-		m_BanPool[i].m_pNext = &m_BanPool[i+1];
-		m_BanPool[i].m_pPrev = &m_BanPool[i-1];
-	}
-
-	m_BanPool[0].m_pNext = &m_BanPool[1];
-	m_BanPool[NET_SERVER_MAXBANS-1].m_pPrev = &m_BanPool[NET_SERVER_MAXBANS-2];
-	m_BanPool_FirstFree = &m_BanPool[0];
+	// 0.0.0.0 would never connect as client
+	net_addr_from_str(&m_LastConAddr,"0.0.0.0"); 
+	net_addr_from_str(&m_PrevLastConAddr,"0.0.0.0");
 
 	return true;
 }
@@ -94,159 +72,8 @@ int CNetServer::Drop(int ClientID, const
 	return 0;
 }
 
-int CNetServer::BanGet(int Index, CBanInfo *pInfo)
-{
-	CBan *pBan;
-	for(pBan = m_BanPool_FirstUsed; pBan && Index; pBan = pBan->m_pNext, Index--)
-		{}
-
-	if(!pBan)
-		return 0;
-	*pInfo = pBan->m_Info;
-	return 1;
-}
-
-int CNetServer::BanNum()
-{
-	int Count = 0;
-	CBan *pBan;
-	for(pBan = m_BanPool_FirstUsed; pBan; pBan = pBan->m_pNext)
-		Count++;
-	return Count;
-}
-
-void CNetServer::BanRemoveByObject(CBan *pBan)
-{
-	int IpHash = (pBan->m_Info.m_Addr.ip[0]+pBan->m_Info.m_Addr.ip[1]+pBan->m_Info.m_Addr.ip[2]+pBan->m_Info.m_Addr.ip[3]+
-					pBan->m_Info.m_Addr.ip[4]+pBan->m_Info.m_Addr.ip[5]+pBan->m_Info.m_Addr.ip[6]+pBan->m_Info.m_Addr.ip[7]+
-					pBan->m_Info.m_Addr.ip[8]+pBan->m_Info.m_Addr.ip[9]+pBan->m_Info.m_Addr.ip[10]+pBan->m_Info.m_Addr.ip[11]+
-					pBan->m_Info.m_Addr.ip[12]+pBan->m_Info.m_Addr.ip[13]+pBan->m_Info.m_Addr.ip[14]+pBan->m_Info.m_Addr.ip[15])&0xff;
-	char aAddrStr[NETADDR_MAXSTRSIZE];
-	net_addr_str(&pBan->m_Info.m_Addr, aAddrStr, sizeof(aAddrStr));
-	dbg_msg("netserver", "removing ban on %s", aAddrStr);
-	MACRO_LIST_UNLINK(pBan, m_BanPool_FirstUsed, m_pPrev, m_pNext);
-	MACRO_LIST_UNLINK(pBan, m_aBans[IpHash], m_pHashPrev, m_pHashNext);
-	MACRO_LIST_LINK_FIRST(pBan, m_BanPool_FirstFree, m_pPrev, m_pNext);
-}
-
-int CNetServer::BanRemove(NETADDR Addr)
-{
-	int IpHash = (Addr.ip[0]+Addr.ip[1]+Addr.ip[2]+Addr.ip[3]+Addr.ip[4]+Addr.ip[5]+Addr.ip[6]+Addr.ip[7]+
-					Addr.ip[8]+Addr.ip[9]+Addr.ip[10]+Addr.ip[11]+Addr.ip[12]+Addr.ip[13]+Addr.ip[14]+Addr.ip[15])&0xff;
-	CBan *pBan = m_aBans[IpHash];
-
-	MACRO_LIST_FIND(pBan, m_pHashNext, net_addr_comp(&pBan->m_Info.m_Addr, &Addr) == 0);
-
-	if(pBan)
-	{
-		BanRemoveByObject(pBan);
-		return 0;
-	}
-
-	return -1;
-}
-
-int CNetServer::BanAdd(NETADDR Addr, int Seconds, const char *pReason)
-{
-	int IpHash = (Addr.ip[0]+Addr.ip[1]+Addr.ip[2]+Addr.ip[3]+Addr.ip[4]+Addr.ip[5]+Addr.ip[6]+Addr.ip[7]+
-					Addr.ip[8]+Addr.ip[9]+Addr.ip[10]+Addr.ip[11]+Addr.ip[12]+Addr.ip[13]+Addr.ip[14]+Addr.ip[15])&0xff;
-	int Stamp = -1;
-	CBan *pBan;
-
-	// remove the port
-	Addr.port = 0;
-
-	if(Seconds)
-		Stamp = time_timestamp() + Seconds;
-
-	// search to see if it already exists
-	pBan = m_aBans[IpHash];
-	MACRO_LIST_FIND(pBan, m_pHashNext, net_addr_comp(&pBan->m_Info.m_Addr, &Addr) == 0);
-	if(pBan)
-	{
-		// adjust the ban
-		pBan->m_Info.m_Expires = Stamp;
-		return 0;
-	}
-
-	if(!m_BanPool_FirstFree)
-		return -1;
-
-	// fetch and clear the new ban
-	pBan = m_BanPool_FirstFree;
-	MACRO_LIST_UNLINK(pBan, m_BanPool_FirstFree, m_pPrev, m_pNext);
-
-	// setup the ban info
-	pBan->m_Info.m_Expires = Stamp;
-	pBan->m_Info.m_Addr = Addr;
-	str_copy(pBan->m_Info.m_Reason, pReason, sizeof(pBan->m_Info.m_Reason));
-
-	// add it to the ban hash
-	MACRO_LIST_LINK_FIRST(pBan, m_aBans[IpHash], m_pHashPrev, m_pHashNext);
-
-	// insert it into the used list
-	{
-		if(m_BanPool_FirstUsed)
-		{
-			CBan *pInsertAfter = m_BanPool_FirstUsed;
-			MACRO_LIST_FIND(pInsertAfter, m_pNext, Stamp < pInsertAfter->m_Info.m_Expires);
-
-			if(pInsertAfter)
-				pInsertAfter = pInsertAfter->m_pPrev;
-			else
-			{
-				// add to last
-				pInsertAfter = m_BanPool_FirstUsed;
-				while(pInsertAfter->m_pNext)
-					pInsertAfter = pInsertAfter->m_pNext;
-			}
-
-			if(pInsertAfter)
-			{
-				MACRO_LIST_LINK_AFTER(pBan, pInsertAfter, m_pPrev, m_pNext);
-			}
-			else
-			{
-				MACRO_LIST_LINK_FIRST(pBan, m_BanPool_FirstUsed, m_pPrev, m_pNext);
-			}
-		}
-		else
-		{
-			MACRO_LIST_LINK_FIRST(pBan, m_BanPool_FirstUsed, m_pPrev, m_pNext);
-		}
-	}
-
-	// drop banned clients
-	{
-		char Buf[128];
-		NETADDR BanAddr;
-
-		if(Stamp > -1)
-		{
-			int Mins = (Seconds + 59) / 60;
-			if(Mins <= 1)
-				str_format(Buf, sizeof(Buf), "You have been banned for 1 minute (%s)", pReason);
-			else
-				str_format(Buf, sizeof(Buf), "You have been banned for %d minutes (%s)", Mins, pReason);
-		}
-		else
-			str_format(Buf, sizeof(Buf), "You have been banned for life (%s)", pReason);
-
-		for(int i = 0; i < MaxClients(); i++)
-		{
-			BanAddr = m_aSlots[i].m_Connection.PeerAddress();
-			BanAddr.port = 0;
-
-			if(net_addr_comp(&Addr, &BanAddr) == 0)
-				Drop(i, Buf);
-		}
-	}
-	return 0;
-}
-
 int CNetServer::Update()
 {
-	int Now = time_timestamp();
 	for(int i = 0; i < MaxClients(); i++)
 	{
 		m_aSlots[i].m_Connection.Update();
@@ -254,13 +81,6 @@ int CNetServer::Update()
 			Drop(i, m_aSlots[i].m_Connection.ErrorString());
 	}
 
-	// remove expired bans
-	while(m_BanPool_FirstUsed && m_BanPool_FirstUsed->m_Info.m_Expires > -1 && m_BanPool_FirstUsed->m_Info.m_Expires < Now)
-	{
-		CBan *pBan = m_BanPool_FirstUsed;
-		BanRemoveByObject(pBan);
-	}
-
 	return 0;
 }
 
@@ -269,8 +89,6 @@ int CNetServer::Update()
 */
 int CNetServer::Recv(CNetChunk *pChunk)
 {
-	unsigned Now = time_timestamp();
-
 	while(1)
 	{
 		NETADDR Addr;
@@ -288,36 +106,12 @@ int CNetServer::Recv(CNetChunk *pChunk)
 
 		if(CNetBase::UnpackPacket(m_RecvUnpacker.m_aBuffer, Bytes, &m_RecvUnpacker.m_Data) == 0)
 		{
-			CBan *pBan = 0;
-			NETADDR BanAddr = Addr;
-			int IpHash = (BanAddr.ip[0]+BanAddr.ip[1]+BanAddr.ip[2]+BanAddr.ip[3]+BanAddr.ip[4]+BanAddr.ip[5]+BanAddr.ip[6]+BanAddr.ip[7]+
-							BanAddr.ip[8]+BanAddr.ip[9]+BanAddr.ip[10]+BanAddr.ip[11]+BanAddr.ip[12]+BanAddr.ip[13]+BanAddr.ip[14]+BanAddr.ip[15])&0xff;
-			int Found = 0;
-			BanAddr.port = 0;
-
-			// search a ban
-			for(pBan = m_aBans[IpHash]; pBan; pBan = pBan->m_pHashNext)
-			{
-				if(net_addr_comp(&pBan->m_Info.m_Addr, &BanAddr) == 0)
-					break;
-			}
-
 			// check if we just should drop the packet
-			if(pBan)
+			char aBuf[128];
+			if(NetBan() && NetBan()->IsBanned(&Addr, aBuf, sizeof(aBuf)))
 			{
 				// banned, reply with a message
-				char BanStr[128];
-				if(pBan->m_Info.m_Expires > -1)
-				{
-					int Mins = ((pBan->m_Info.m_Expires - Now)+59)/60;
-					if(Mins <= 1)
-						str_format(BanStr, sizeof(BanStr), "Banned for 1 minute (%s)", pBan->m_Info.m_Reason);
-					else
-						str_format(BanStr, sizeof(BanStr), "Banned for %d minutes (%s)", Mins, pBan->m_Info.m_Reason);
-				}
-				else
-					str_format(BanStr, sizeof(BanStr), "Banned for life (%s)", pBan->m_Info.m_Reason);
-				CNetBase::SendControlMsg(m_Socket, &Addr, 0, NET_CTRLMSG_CLOSE, BanStr, str_length(BanStr)+1);
+				CNetBase::SendControlMsg(m_Socket, &Addr, 0, NET_CTRLMSG_CLOSE, aBuf, str_length(aBuf)+1);
 				continue;
 			}
 
@@ -335,16 +129,15 @@ int CNetServer::Recv(CNetChunk *pChunk)
 				// TODO: check size here
 				if(m_RecvUnpacker.m_Data.m_Flags&NET_PACKETFLAG_CONTROL && m_RecvUnpacker.m_Data.m_aChunkData[0] == NET_CTRLMSG_CONNECT)
 				{
-					Found = 0;
+					bool Found = false;
 
 					// check if we already got this client
 					for(int i = 0; i < MaxClients(); i++)
 					{
-						NETADDR PeerAddr = m_aSlots[i].m_Connection.PeerAddress();
 						if(m_aSlots[i].m_Connection.State() != NET_CONNSTATE_OFFLINE &&
-							net_addr_comp(&PeerAddr, &Addr) == 0)
+							net_addr_comp(m_aSlots[i].m_Connection.PeerAddress(), &Addr) == 0)
 						{
-							Found = 1; // silent ignore.. we got this client already
+							Found = true; // silent ignore.. we got this client already
 							break;
 						}
 					}
@@ -361,7 +154,7 @@ int CNetServer::Recv(CNetChunk *pChunk)
 							if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_OFFLINE)
 								continue;
 
-							OtherAddr = m_aSlots[i].m_Connection.PeerAddress();
+							OtherAddr = *m_aSlots[i].m_Connection.PeerAddress();
 							OtherAddr.port = 0;
 							if(!net_addr_comp(&ThisAddr, &OtherAddr))
 							{
@@ -374,12 +167,27 @@ int CNetServer::Recv(CNetChunk *pChunk)
 								}
 							}
 						}
-
+					
+						if((!net_addr_comp(&ThisAddr, &m_LastConAddr) && time_get() - m_LastConTry < 0)
+								 && (!net_addr_comp(&ThisAddr, &m_PrevLastConAddr) && time_get() - m_PrevLastConTry < 0))
+						{
+							char aBuf[128];
+							str_format(aBuf, sizeof(aBuf), "Too fast reconnect.");
+							CNetBase::SendControlMsg(m_Socket, &Addr, 0, NET_CTRLMSG_CLOSE, aBuf, sizeof(aBuf));
+							return 0;
+						}
+					
+						m_PrevLastConAddr = m_LastConAddr;
+						m_PrevLastConTry = m_LastConTry;					
+	
+						m_LastConAddr = ThisAddr;
+						m_LastConTry = time_get() + 3 * time_freq();
+		
 						for(int i = 0; i < MaxClients(); i++)
 						{
 							if(m_aSlots[i].m_Connection.State() == NET_CONNSTATE_OFFLINE)
 							{
-								Found = 1;
+								Found = true;
 								m_aSlots[i].m_Connection.Feed(&m_RecvUnpacker.m_Data, &Addr);
 								if(m_pfnNewClient)
 									m_pfnNewClient(i, m_UserPtr);
@@ -399,8 +207,7 @@ int CNetServer::Recv(CNetChunk *pChunk)
 					// normal packet, find matching slot
 					for(int i = 0; i < MaxClients(); i++)
 					{
-						NETADDR PeerAddr = m_aSlots[i].m_Connection.PeerAddress();
-						if(net_addr_comp(&PeerAddr, &Addr) == 0)
+						if(net_addr_comp(m_aSlots[i].m_Connection.PeerAddress(), &Addr) == 0)
 						{
 							if(m_aSlots[i].m_Connection.Feed(&m_RecvUnpacker.m_Data, &Addr))
 							{
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/shared/storage.cpp alien-rc4/src//engine/shared/storage.cpp
--- teeworlds-b177-r50edfd37-source/src//engine/shared/storage.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/shared/storage.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -30,7 +30,7 @@ public:
 		m_aUserdir[0] = 0;
 	}
 
-	int Init(const char *pApplicationName, int NumArgs, const char **ppArguments)
+	int Init(const char *pApplicationName, int StorageType, int NumArgs, const char **ppArguments)
 	{
 		// get userdir
 		fs_storage_path(pApplicationName, m_aUserdir, sizeof(m_aUserdir));
@@ -52,14 +52,17 @@ public:
 		}
 
 		// add save directories
-		if(m_NumPaths && (!m_aaStoragePaths[TYPE_SAVE][0] || !fs_makedir(m_aaStoragePaths[TYPE_SAVE])))
+		if(StorageType != STORAGETYPE_BASIC && m_NumPaths && (!m_aaStoragePaths[TYPE_SAVE][0] || !fs_makedir(m_aaStoragePaths[TYPE_SAVE])))
 		{
 			char aPath[MAX_PATH_LENGTH];
-			fs_makedir(GetPath(TYPE_SAVE, "screenshots", aPath, sizeof(aPath)));
-			fs_makedir(GetPath(TYPE_SAVE, "screenshots/auto", aPath, sizeof(aPath)));
-			fs_makedir(GetPath(TYPE_SAVE, "maps", aPath, sizeof(aPath)));
+			if(StorageType == STORAGETYPE_CLIENT)
+			{
+				fs_makedir(GetPath(TYPE_SAVE, "screenshots", aPath, sizeof(aPath)));
+				fs_makedir(GetPath(TYPE_SAVE, "screenshots/auto", aPath, sizeof(aPath)));
+				fs_makedir(GetPath(TYPE_SAVE, "maps", aPath, sizeof(aPath)));
+				fs_makedir(GetPath(TYPE_SAVE, "downloadedmaps", aPath, sizeof(aPath)));
+			}
 			fs_makedir(GetPath(TYPE_SAVE, "dumps", aPath, sizeof(aPath)));
-			fs_makedir(GetPath(TYPE_SAVE, "downloadedmaps", aPath, sizeof(aPath)));
 			fs_makedir(GetPath(TYPE_SAVE, "demos", aPath, sizeof(aPath)));
 			fs_makedir(GetPath(TYPE_SAVE, "demos/auto", aPath, sizeof(aPath)));
 		}
@@ -377,10 +380,22 @@ public:
 		return !fs_makedir(GetPath(Type, pFoldername, aBuffer, sizeof(aBuffer)));
 	}
 
-	static IStorage *Create(const char *pApplicationName, int NumArgs, const char **ppArguments)
+	virtual void GetCompletePath(int Type, const char *pDir, char *pBuffer, unsigned BufferSize)
+	{
+		if(Type < 0 || Type >= m_NumPaths)
+		{
+			if(BufferSize > 0)
+				pBuffer[0] = 0;
+			return;
+		}
+
+		GetPath(Type, pDir, pBuffer, BufferSize);
+	}
+
+	static IStorage *Create(const char *pApplicationName, int StorageType, int NumArgs, const char **ppArguments)
 	{
 		CStorage *p = new CStorage();
-		if(p && p->Init(pApplicationName, NumArgs, ppArguments))
+		if(p && p->Init(pApplicationName, StorageType, NumArgs, ppArguments))
 		{
 			dbg_msg("storage", "initialisation failed");
 			delete p;
@@ -390,4 +405,4 @@ public:
 	}
 };
 
-IStorage *CreateStorage(const char *pApplicationName, int NumArgs, const char **ppArguments) { return CStorage::Create(pApplicationName, NumArgs, ppArguments); }
+IStorage *CreateStorage(const char *pApplicationName, int StorageType, int NumArgs, const char **ppArguments) { return CStorage::Create(pApplicationName, StorageType, NumArgs, ppArguments); }
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/sound.h alien-rc4/src//engine/sound.h
--- teeworlds-b177-r50edfd37-source/src//engine/sound.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/sound.h	2012-06-14 23:57:39.000000000 +0200
@@ -19,10 +19,10 @@ public:
 	virtual bool IsSoundEnabled() = 0;
 
 	virtual int LoadWV(const char *pFilename) = 0;
-	
+
 	virtual void SetChannel(int ChannelID, float Volume, float Panning) = 0;
 	virtual void SetListenerPos(float x, float y) = 0;
-	
+
 	virtual int PlayAt(int ChannelID, int SampleID, int Flags, float x, float y) = 0;
 	virtual int Play(int ChannelID, int SampleID, int Flags) = 0;
 	virtual void Stop(int SampleID) = 0;
diff -rupN teeworlds-b177-r50edfd37-source/src//engine/storage.h alien-rc4/src//engine/storage.h
--- teeworlds-b177-r50edfd37-source/src//engine/storage.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//engine/storage.h	2012-06-14 23:57:39.000000000 +0200
@@ -12,7 +12,11 @@ public:
 	enum
 	{
 		TYPE_SAVE = 0,
-		TYPE_ALL = -1
+		TYPE_ALL = -1,
+
+		STORAGETYPE_BASIC = 0,
+		STORAGETYPE_SERVER,
+		STORAGETYPE_CLIENT,
 	};
 
 	virtual void ListDirectory(int Type, const char *pPath, FS_LISTDIR_CALLBACK pfnCallback, void *pUser) = 0;
@@ -21,9 +25,10 @@ public:
 	virtual bool RemoveFile(const char *pFilename, int Type) = 0;
 	virtual bool RenameFile(const char* pOldFilename, const char* pNewFilename, int Type) = 0;
 	virtual bool CreateFolder(const char *pFoldername, int Type) = 0;
+	virtual void GetCompletePath(int Type, const char *pDir, char *pBuffer, unsigned BufferSize) = 0;
 };
 
-extern IStorage *CreateStorage(const char *pApplicationName, int NumArgs, const char **ppArguments);
+extern IStorage *CreateStorage(const char *pApplicationName, int StorageType, int NumArgs, const char **ppArguments);
 
 
 #endif
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/chat.cpp alien-rc4/src//game/client/components/chat.cpp
--- teeworlds-b177-r50edfd37-source/src//game/client/components/chat.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/chat.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -41,6 +41,11 @@ void CChat::OnReset()
 	m_PlaceholderOffset = 0;
 	m_PlaceholderLength = 0;
 	m_pHistoryEntry = 0x0;
+	m_PendingChatCounter = 0;
+	m_LastChatSend = 0;
+
+	for(int i = 0; i < CHAT_NUM; ++i)
+		m_aLastSoundPlayed[i] = 0;
 }
 
 void CChat::OnRelease()
@@ -107,9 +112,13 @@ bool CChat::OnInput(IInput::CEvent Event
 	{
 		if(m_Input.GetString()[0])
 		{
-			Say(m_Mode == MODE_ALL ? 0 : 1, m_Input.GetString());
-			char *pEntry = m_History.Allocate(m_Input.GetLength()+1);
-			mem_copy(pEntry, m_Input.GetString(), m_Input.GetLength()+1);
+			if(m_LastChatSend+time_freq() < time_get())
+				Say(m_Mode == MODE_ALL ? 0 : 1, m_Input.GetString());
+			else
+				++m_PendingChatCounter;
+			CHistoryEntry *pEntry = m_History.Allocate(sizeof(CHistoryEntry)+m_Input.GetLength());
+			pEntry->m_Team = m_Mode == MODE_ALL ? 0 : 1;
+			mem_copy(pEntry->m_aText, m_Input.GetString(), m_Input.GetLength()+1);
 		}
 		m_pHistoryEntry = 0x0;
 		m_Mode = MODE_NONE;
@@ -199,26 +208,26 @@ bool CChat::OnInput(IInput::CEvent Event
 	}
 	if(Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key == KEY_UP)
 	{
-		if (m_pHistoryEntry)
+		if(m_pHistoryEntry)
 		{
-			char *pTest = m_History.Prev(m_pHistoryEntry);
+			CHistoryEntry *pTest = m_History.Prev(m_pHistoryEntry);
 
-			if (pTest)
+			if(pTest)
 				m_pHistoryEntry = pTest;
 		}
 		else
 			m_pHistoryEntry = m_History.Last();
 
-		if (m_pHistoryEntry)
-			m_Input.Set(m_pHistoryEntry);
+		if(m_pHistoryEntry)
+			m_Input.Set(m_pHistoryEntry->m_aText);
 	}
 	else if (Event.m_Flags&IInput::FLAG_PRESS && Event.m_Key == KEY_DOWN)
 	{
-		if (m_pHistoryEntry)
+		if(m_pHistoryEntry)
 			m_pHistoryEntry = m_History.Next(m_pHistoryEntry);
 
 		if (m_pHistoryEntry)
-			m_Input.Set(m_pHistoryEntry);
+			m_Input.Set(m_pHistoryEntry->m_aText);
 		else
 			m_Input.Clear();
 	}
@@ -257,7 +266,8 @@ void CChat::OnMessage(int MsgType, void
 void CChat::AddLine(int ClientID, int Team, const char *pLine)
 {
 	if(ClientID != -1 && (m_pClient->m_aClients[ClientID].m_aName[0] == '\0' || // unknown client
-		m_pClient->m_aClients[ClientID].m_ChatIgnore))
+		m_pClient->m_aClients[ClientID].m_ChatIgnore ||
+		(m_pClient->m_Snap.m_LocalClientID != ClientID && g_Config.m_ClShowChatFriends && !m_pClient->m_aClients[ClientID].m_Friend)))
 		return;
 
 	bool Highlighted = false;
@@ -283,7 +293,7 @@ void CChat::AddLine(int ClientID, int Te
 		m_aLines[m_CurrentLine].m_ClientID = ClientID;
 		m_aLines[m_CurrentLine].m_Team = Team;
 		m_aLines[m_CurrentLine].m_NameColor = -2;
-		
+
 		// check for highlighted name
 		const char *pHL = str_find_nocase(pLine, m_pClient->m_aClients[m_pClient->m_Snap.m_LocalClientID].m_aName);
 		if(pHL)
@@ -322,16 +332,50 @@ void CChat::AddLine(int ClientID, int Te
 	}
 
 	// play sound
+	int64 Now = time_get();
 	if(ClientID == -1)
-		m_pClient->m_pSounds->Play(CSounds::CHN_GUI, SOUND_CHAT_SERVER, 0, vec2(0,0));
+	{
+		if(Now-m_aLastSoundPlayed[CHAT_SERVER] >= time_freq()*3/10)
+		{
+			m_pClient->m_pSounds->Play(CSounds::CHN_GUI, SOUND_CHAT_SERVER, 0);
+			m_aLastSoundPlayed[CHAT_SERVER] = Now;
+		}
+	}
 	else if(Highlighted)
-		m_pClient->m_pSounds->Play(CSounds::CHN_GUI, SOUND_CHAT_HIGHLIGHT, 0, vec2(0.0f, 0.0f));
+	{
+		if(Now-m_aLastSoundPlayed[CHAT_HIGHLIGHT] >= time_freq()*3/10)
+		{
+			m_pClient->m_pSounds->Play(CSounds::CHN_GUI, SOUND_CHAT_CLIENT, 0);
+			m_aLastSoundPlayed[CHAT_HIGHLIGHT] = Now;
+		}
+	}
 	else
-		m_pClient->m_pSounds->Play(CSounds::CHN_GUI, SOUND_CHAT_CLIENT, 0, vec2(0,0));
+	{
+		if(Now-m_aLastSoundPlayed[CHAT_CLIENT] >= time_freq()*3/10)
+		{
+			m_pClient->m_pSounds->Play(CSounds::CHN_GUI, SOUND_CHAT_HIGHLIGHT, 0);
+			m_aLastSoundPlayed[CHAT_CLIENT] = Now;
+		}
+	}
 }
 
 void CChat::OnRender()
 {
+	// send pending chat messages
+	if(m_PendingChatCounter > 0 && m_LastChatSend+time_freq() < time_get())
+	{
+		CHistoryEntry *pEntry = m_History.Last();
+		for(int i = m_PendingChatCounter-1; pEntry; --i, pEntry = m_History.Prev(pEntry))
+		{
+			if(i == 0)
+			{
+				Say(pEntry->m_Team, pEntry->m_aText);
+				break;
+			}
+		}
+		--m_PendingChatCounter;
+	}
+
 	float Width = 300.0f*Graphics()->ScreenAspect();
 	Graphics()->MapScreen(0.0f, 0.0f, Width, 300.0f);
 	float x = 5.0f;
@@ -457,6 +501,8 @@ void CChat::OnRender()
 
 void CChat::Say(int Team, const char *pLine)
 {
+	m_LastChatSend = time_get();
+
 	// send chat message
 	CNetMsg_Cl_Say Msg;
 	Msg.m_Team = Team;
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/chat.h alien-rc4/src//game/client/components/chat.h
--- teeworlds-b177-r50edfd37-source/src//game/client/components/chat.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/chat.h	2012-06-14 23:57:39.000000000 +0200
@@ -36,6 +36,11 @@ class CChat : public CComponent
 		MODE_NONE=0,
 		MODE_ALL,
 		MODE_TEAM,
+
+		CHAT_SERVER=0,
+		CHAT_HIGHLIGHT,
+		CHAT_CLIENT,
+		CHAT_NUM,
 	};
 
 	int m_Mode;
@@ -47,8 +52,17 @@ class CChat : public CComponent
 	char m_aCompletionBuffer[256];
 	int m_PlaceholderOffset;
 	int m_PlaceholderLength;
-	char *m_pHistoryEntry;
-	TStaticRingBuffer<char, 64*1024, CRingBufferBase::FLAG_RECYCLE> m_History;
+
+	struct CHistoryEntry
+	{
+		int m_Team;
+		char m_aText[1];
+	};
+	CHistoryEntry *m_pHistoryEntry;
+	TStaticRingBuffer<CHistoryEntry, 64*1024, CRingBufferBase::FLAG_RECYCLE> m_History;
+	int m_PendingChatCounter;
+	int64 m_LastChatSend;
+	int64 m_aLastSoundPlayed[CHAT_NUM];
 
 	static void ConSay(IConsole::IResult *pResult, void *pUserData);
 	static void ConSayTeam(IConsole::IResult *pResult, void *pUserData);
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/console.cpp alien-rc4/src//game/client/components/console.cpp
--- teeworlds-b177-r50edfd37-source/src//game/client/components/console.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/console.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -612,16 +612,10 @@ void CGameConsole::Dump(int Type)
 	IOHANDLE io = Storage()->OpenFile(aFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE);
 	if(io)
 	{
-		#if defined(CONF_FAMILY_WINDOWS)
-			static const char Newline[] = "\r\n";
-		#else
-			static const char Newline[] = "\n";
-		#endif
-
 		for(CInstance::CBacklogEntry *pEntry = pConsole->m_Backlog.First(); pEntry; pEntry = pConsole->m_Backlog.Next(pEntry))
 		{
 			io_write(io, pEntry->m_aText, str_length(pEntry->m_aText));
-			io_write(io, Newline, sizeof(Newline)-1);
+			io_write_newline(io);
 		}
 		io_close(io);
 	}
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/controls.cpp alien-rc4/src//game/client/components/controls.cpp
--- teeworlds-b177-r50edfd37-source/src//game/client/components/controls.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/controls.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -199,7 +199,7 @@ int CControls::SnapInput(int *pData)
 void CControls::OnRender()
 {
 	// update target pos
-	if(m_pClient->m_Snap.m_pGameInfoObj && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED || m_pClient->m_Snap.m_SpecInfo.m_Active))
+	if(m_pClient->m_Snap.m_pGameInfoObj && !m_pClient->m_Snap.m_SpecInfo.m_Active)
 		m_TargetPos = m_pClient->m_LocalCharacterPos + m_MousePos;
 	else if(m_pClient->m_Snap.m_SpecInfo.m_Active && m_pClient->m_Snap.m_SpecInfo.m_UsePosition)
 		m_TargetPos = m_pClient->m_Snap.m_SpecInfo.m_Position + m_MousePos;
@@ -209,7 +209,8 @@ void CControls::OnRender()
 
 bool CControls::OnMouseMove(float x, float y)
 {
-	if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED)
+	if((m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED) ||
+		(m_pClient->m_Snap.m_SpecInfo.m_Active && m_pClient->m_pChat->IsActive()))
 		return false;
 
 	m_MousePos += vec2(x, y); // TODO: ugly
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/countryflags.cpp alien-rc4/src//game/client/components/countryflags.cpp
--- teeworlds-b177-r50edfd37-source/src//game/client/components/countryflags.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/countryflags.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -6,6 +6,8 @@
 #include <engine/console.h>
 #include <engine/graphics.h>
 #include <engine/storage.h>
+#include <engine/textrender.h>
+#include <engine/shared/config.h>
 #include <engine/shared/linereader.h>
 
 #include "countryflags.h"
@@ -56,31 +58,57 @@ void CCountryFlags::LoadCountryflagsInde
 
 		// load the graphic file
 		char aBuf[128];
-		str_format(aBuf, sizeof(aBuf), "countryflags/%s.png", aOrigin);
 		CImageInfo Info;
-		if(!Graphics()->LoadPNG(&Info, aBuf, IStorage::TYPE_ALL))
+		if(g_Config.m_ClLoadCountryFlags)
 		{
-			char aMsg[128];
-			str_format(aMsg, sizeof(aMsg), "failed to load '%s'", aBuf);
-			Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", aMsg);
-			continue;
+			str_format(aBuf, sizeof(aBuf), "countryflags/%s.png", aOrigin);
+			if(!Graphics()->LoadPNG(&Info, aBuf, IStorage::TYPE_ALL))
+			{
+				char aMsg[128];
+				str_format(aMsg, sizeof(aMsg), "failed to load '%s'", aBuf);
+				Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", aMsg);
+				continue;
+			}
 		}
 
 		// add entry
 		CCountryFlag CountryFlag;
 		CountryFlag.m_CountryCode = CountryCode;
 		str_copy(CountryFlag.m_aCountryCodeString, aOrigin, sizeof(CountryFlag.m_aCountryCodeString));
-		CountryFlag.m_Texture = Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0);
-		mem_free(Info.m_pData);
-		str_format(aBuf, sizeof(aBuf), "loaded country flag '%s'", aOrigin);
-		Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", aBuf);
-		m_aCountryFlags.add(CountryFlag);
+		if(g_Config.m_ClLoadCountryFlags)
+		{
+			CountryFlag.m_Texture = Graphics()->LoadTextureRaw(Info.m_Width, Info.m_Height, Info.m_Format, Info.m_pData, Info.m_Format, 0);
+			mem_free(Info.m_pData);
+		}
+		else
+			CountryFlag.m_Texture = -1;
+		if(g_Config.m_Debug)
+		{
+			str_format(aBuf, sizeof(aBuf), "loaded country flag '%s'", aOrigin);
+			Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "countryflags", aBuf);
+		}
+		m_aCountryFlags.add_unsorted(CountryFlag);
 	}
 	io_close(File);
+	m_aCountryFlags.sort_range();
 
-	mem_zero(m_CodeIndexLUT, sizeof(m_CodeIndexLUT));
+	// find index of default item
+	int DefaultIndex = 0, Index = 0;
+	for(sorted_array<CCountryFlag>::range r = m_aCountryFlags.all(); !r.empty(); r.pop_front(), ++Index)
+		if(r.front().m_CountryCode == -1)
+		{
+			DefaultIndex = Index;
+			break;
+		}
+	
+	// init LUT
+	if(DefaultIndex != 0)
+		for(int i = 0; i < CODE_RANGE; ++i)
+			m_CodeIndexLUT[i] = DefaultIndex;
+	else
+		mem_zero(m_CodeIndexLUT, sizeof(m_CodeIndexLUT));
 	for(int i = 0; i < m_aCountryFlags.size(); ++i)
-		m_CodeIndexLUT[max(0, (m_aCountryFlags[i].m_CountryCode-CODE_LB)%CODE_RANGE)] = i+1;
+		m_CodeIndexLUT[max(0, (m_aCountryFlags[i].m_CountryCode-CODE_LB)%CODE_RANGE)] = i;
 }
 
 void CCountryFlags::OnInit()
@@ -94,6 +122,7 @@ void CCountryFlags::OnInit()
 		CCountryFlag DummyEntry;
 		DummyEntry.m_CountryCode = -1;
 		DummyEntry.m_Texture = -1;
+		mem_zero(DummyEntry.m_aCountryCodeString, sizeof(DummyEntry.m_aCountryCodeString));
 		m_aCountryFlags.add(DummyEntry);
 	}
 }
@@ -105,10 +134,31 @@ int CCountryFlags::Num() const
 
 const CCountryFlags::CCountryFlag *CCountryFlags::GetByCountryCode(int CountryCode) const
 {
-	return GetByIndex(m_CodeIndexLUT[max(0, (CountryCode-CODE_LB)%CODE_RANGE)]-1);
+	return GetByIndex(m_CodeIndexLUT[max(0, (CountryCode-CODE_LB)%CODE_RANGE)]);
 }
 
 const CCountryFlags::CCountryFlag *CCountryFlags::GetByIndex(int Index) const
 {
 	return &m_aCountryFlags[max(0, Index%m_aCountryFlags.size())];
 }
+
+void CCountryFlags::Render(int CountryCode, const vec4 *pColor, float x, float y, float w, float h)
+{
+	const CCountryFlag *pFlag = GetByCountryCode(CountryCode);
+	if(pFlag->m_Texture != -1)
+	{
+		Graphics()->TextureSet(pFlag->m_Texture);
+		Graphics()->QuadsBegin();
+		Graphics()->SetColor(pColor->r, pColor->g, pColor->b, pColor->a);
+		IGraphics::CQuadItem QuadItem(x, y, w, h);
+		Graphics()->QuadsDrawTL(&QuadItem, 1);
+		Graphics()->QuadsEnd();
+	}
+	else
+	{
+		CTextCursor Cursor;
+		TextRender()->SetCursor(&Cursor, x, y, 10.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);
+		Cursor.m_LineWidth = w;
+		TextRender()->TextEx(&Cursor, pFlag->m_aCountryCodeString, -1);
+	}
+}
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/countryflags.h alien-rc4/src//game/client/components/countryflags.h
--- teeworlds-b177-r50edfd37-source/src//game/client/components/countryflags.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/countryflags.h	2012-06-14 23:57:39.000000000 +0200
@@ -23,7 +23,7 @@ public:
 	int Num() const;
 	const CCountryFlag *GetByCountryCode(int CountryCode) const;
 	const CCountryFlag *GetByIndex(int Index) const;
-	//int Find(int CountryCode) const;
+	void Render(int CountryCode, const vec4 *pColor, float x, float y, float w, float h);
 
 private:
 	enum
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/damageind.cpp alien-rc4/src//game/client/components/damageind.cpp
--- teeworlds-b177-r50edfd37-source/src//game/client/components/damageind.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/damageind.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -1,5 +1,6 @@
 /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
 /* If you are missing that file, acquire a complete release at teeworlds.com.                */
+#include <engine/demo.h>
 #include <engine/graphics.h>
 #include <game/generated/protocol.h>
 #include <game/generated/client_data.h>
@@ -38,7 +39,7 @@ void CDamageInd::Create(vec2 Pos, vec2 D
 	if (i)
 	{
 		i->m_Pos = Pos;
-		i->m_Life = 0.75f;
+		i->m_StartTime = Client()->LocalTime();
 		i->m_Dir = Dir*-1;
 		i->m_StartAngle = (( (float)rand()/(float)RAND_MAX) - 1.0f) * 2.0f * pi;
 	}
@@ -48,21 +49,39 @@ void CDamageInd::OnRender()
 {
 	Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id);
 	Graphics()->QuadsBegin();
+	static float s_LastLocalTime = Client()->LocalTime();
 	for(int i = 0; i < m_NumItems;)
 	{
-		vec2 Pos = mix(m_aItems[i].m_Pos+m_aItems[i].m_Dir*75.0f, m_aItems[i].m_Pos, clamp((m_aItems[i].m_Life-0.60f)/0.15f, 0.0f, 1.0f));
+		if(Client()->State() == IClient::STATE_DEMOPLAYBACK)
+		{
+			const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo();
+			if(pInfo->m_Paused)
+				m_aItems[i].m_StartTime += Client()->LocalTime()-s_LastLocalTime;
+			else
+				m_aItems[i].m_StartTime += (Client()->LocalTime()-s_LastLocalTime)*(1.0f-pInfo->m_Speed);
+		}
+		else
+		{
+			if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED)
+				m_aItems[i].m_StartTime += Client()->LocalTime()-s_LastLocalTime;
+		}
 
-		m_aItems[i].m_Life -= Client()->FrameTime();
-		if(m_aItems[i].m_Life < 0.0f)
+		float Life = 0.75f - (Client()->LocalTime() - m_aItems[i].m_StartTime);
+		if(Life < 0.0f)
 			DestroyI(&m_aItems[i]);
 		else
 		{
-			Graphics()->SetColor(1.0f,1.0f,1.0f, m_aItems[i].m_Life/0.1f);
-			Graphics()->QuadsSetRotation(m_aItems[i].m_StartAngle + m_aItems[i].m_Life * 2.0f);
+			vec2 Pos = mix(m_aItems[i].m_Pos+m_aItems[i].m_Dir*75.0f, m_aItems[i].m_Pos, clamp((Life-0.60f)/0.15f, 0.0f, 1.0f));
+			Graphics()->SetColor(1.0f,1.0f,1.0f, Life/0.1f);
+			Graphics()->QuadsSetRotation(m_aItems[i].m_StartAngle + Life * 2.0f);
 			RenderTools()->SelectSprite(SPRITE_STAR1);
 			RenderTools()->DrawSprite(Pos.x, Pos.y, 48.0f);
 			i++;
 		}
 	}
+	s_LastLocalTime = Client()->LocalTime();
 	Graphics()->QuadsEnd();
 }
+
+
+
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/damageind.h alien-rc4/src//game/client/components/damageind.h
--- teeworlds-b177-r50edfd37-source/src//game/client/components/damageind.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/damageind.h	2012-06-14 23:57:39.000000000 +0200
@@ -12,7 +12,7 @@ class CDamageInd : public CComponent
 	{
 		vec2 m_Pos;
 		vec2 m_Dir;
-		float m_Life;
+		float m_StartTime;
 		float m_StartAngle;
 	};
 
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/effects.cpp alien-rc4/src//game/client/components/effects.cpp
--- teeworlds-b177-r50edfd37-source/src//game/client/components/effects.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/effects.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -44,7 +44,7 @@ void CEffects::AirJump(vec2 Pos)
 	p.m_Pos = Pos + vec2(6.0f, 16.0f);
 	m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p);
 
-	m_pClient->m_pSounds->Play(CSounds::CHN_WORLD, SOUND_PLAYER_AIRJUMP, 1.0f, Pos);
+	m_pClient->m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_PLAYER_AIRJUMP, 1.0f, Pos);
 }
 
 void CEffects::DamageIndicator(vec2 Pos, vec2 Dir)
@@ -147,7 +147,7 @@ void CEffects::PlayerSpawn(vec2 Pos)
 		m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p);
 
 	}
-	m_pClient->m_pSounds->Play(CSounds::CHN_WORLD, SOUND_PLAYER_SPAWN, 1.0f, Pos);
+	m_pClient->m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_PLAYER_SPAWN, 1.0f, Pos);
 }
 
 void CEffects::PlayerDeath(vec2 Pos, int ClientID)
@@ -242,7 +242,7 @@ void CEffects::HammerHit(vec2 Pos)
 	p.m_EndSize = 0;
 	p.m_Rot = frandom()*pi*2;
 	m_pClient->m_pParticles->Add(CParticles::GROUP_EXPLOSIONS, &p);
-	m_pClient->m_pSounds->Play(CSounds::CHN_WORLD, SOUND_HAMMER_HIT, 1.0f, Pos);
+	m_pClient->m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_HAMMER_HIT, 1.0f, Pos);
 }
 
 void CEffects::OnRender()
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/emoticon.cpp alien-rc4/src//game/client/components/emoticon.cpp
--- teeworlds-b177-r50edfd37-source/src//game/client/components/emoticon.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/emoticon.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -111,14 +111,14 @@ void CEmoticon::OnRender()
 
 	m_WasActive = true;
 
-	if (length(m_SelectorMouse) > 140)
-		m_SelectorMouse = normalize(m_SelectorMouse) * 140;
+	if (length(m_SelectorMouse) > 170.0f)
+		m_SelectorMouse = normalize(m_SelectorMouse) * 170.0f;
 
 	float SelectedAngle = GetAngle(m_SelectorMouse) + 2*pi/24;
 	if (SelectedAngle < 0)
 		SelectedAngle += 2*pi;
 
-	if (length(m_SelectorMouse) > 100)
+	if (length(m_SelectorMouse) > 110.0f)
 		m_SelectedEmote = (int)(SelectedAngle / (2*pi) * NUM_EMOTICONS);
 
 	CUIRect Screen = *UI()->Screen();
@@ -130,7 +130,7 @@ void CEmoticon::OnRender()
 	Graphics()->TextureSet(-1);
 	Graphics()->QuadsBegin();
 	Graphics()->SetColor(0,0,0,0.3f);
-	DrawCircle(Screen.w/2, Screen.h/2, 160, 64);
+	DrawCircle(Screen.w/2, Screen.h/2, 190.0f, 64);
 	Graphics()->QuadsEnd();
 
 	Graphics()->TextureSet(g_pData->m_aImages[IMAGE_EMOTICONS].m_Id);
@@ -144,10 +144,10 @@ void CEmoticon::OnRender()
 
 		bool Selected = m_SelectedEmote == i;
 
-		float Size = Selected ? 80 : 32;
+		float Size = Selected ? 80.0f : 50.0f;
 
-		float NudgeX = 120 * cosf(Angle);
-		float NudgeY = 120 * sinf(Angle);
+		float NudgeX = 150.0f * cosf(Angle);
+		float NudgeY = 150.0f * sinf(Angle);
 		RenderTools()->SelectSprite(SPRITE_OOP + i);
 		IGraphics::CQuadItem QuadItem(Screen.w/2 + NudgeX, Screen.h/2 + NudgeY, Size, Size);
 		Graphics()->QuadsDraw(&QuadItem, 1);
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/hud.cpp alien-rc4/src//game/client/components/hud.cpp
--- teeworlds-b177-r50edfd37-source/src//game/client/components/hud.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/hud.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -59,6 +59,18 @@ void CHud::RenderGameTimer()
 	}
 }
 
+void CHud::RenderPauseNotification()
+{
+	if(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED &&
+		!(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER))
+	{
+		const char *pText = Localize("Game paused");
+		float FontSize = 20.0f;
+		float w = TextRender()->TextWidth(0, FontSize,pText, -1);
+		TextRender()->Text(0, 150.0f*Graphics()->ScreenAspect()+-w/2.0f, 50.0f, FontSize, pText, -1);
+	}
+}
+
 void CHud::RenderSuddenDeath()
 {
 	if(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_SUDDENDEATH)
@@ -78,6 +90,7 @@ void CHud::RenderScoreHud()
 	{
 		int GameFlags = m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags;
 		float Whole = 300*Graphics()->ScreenAspect();
+		float StartY = 229.0f;
 
 		if(GameFlags&GAMEFLAG_TEAMS && m_pClient->m_Snap.m_pGameDataObj)
 		{
@@ -100,15 +113,15 @@ void CHud::RenderScoreHud()
 					Graphics()->SetColor(1.0f, 0.0f, 0.0f, 0.25f);
 				else
 					Graphics()->SetColor(0.0f, 0.0f, 1.0f, 0.25f);
-				RenderTools()->DrawRoundRectExt(Whole-ScoreWidthMax-ImageSize-2*Split, 245.0f+t*20, ScoreWidthMax+ImageSize+2*Split, 18.0f, 5.0f, CUI::CORNER_L);
+				RenderTools()->DrawRoundRectExt(Whole-ScoreWidthMax-ImageSize-2*Split, StartY+t*20, ScoreWidthMax+ImageSize+2*Split, 18.0f, 5.0f, CUI::CORNER_L);
 				Graphics()->QuadsEnd();
 
 				// draw score
-				TextRender()->Text(0, Whole-ScoreWidthMax+(ScoreWidthMax-aScoreTeamWidth[t])/2-Split, 245.0f+t*20, 14.0f, aScoreTeam[t], -1);
+				TextRender()->Text(0, Whole-ScoreWidthMax+(ScoreWidthMax-aScoreTeamWidth[t])/2-Split, StartY+t*20, 14.0f, aScoreTeam[t], -1);
 
 				if(GameFlags&GAMEFLAG_FLAGS)
 				{
-					int BlinkTimer = (m_pClient->m_FlagDropTick[t] != 0 && 
+					int BlinkTimer = (m_pClient->m_FlagDropTick[t] != 0 &&
 										(Client()->GameTick()-m_pClient->m_FlagDropTick[t])/Client()->GameTickSpeed() >= 25) ? 10 : 20;
 					if(FlagCarrier[t] == FLAG_ATSTAND || (FlagCarrier[t] == FLAG_TAKEN && ((Client()->GameTick()/BlinkTimer)&1)))
 					{
@@ -117,7 +130,7 @@ void CHud::RenderScoreHud()
 						Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GAME].m_Id);
 						Graphics()->QuadsBegin();
 						RenderTools()->SelectSprite(t==0?SPRITE_FLAG_RED:SPRITE_FLAG_BLUE);
-						IGraphics::CQuadItem QuadItem(Whole-ScoreWidthMax-ImageSize, 246.0f+t*20, ImageSize/2, ImageSize);
+						IGraphics::CQuadItem QuadItem(Whole-ScoreWidthMax-ImageSize, StartY+1.0f+t*20, ImageSize/2, ImageSize);
 						Graphics()->QuadsDrawTL(&QuadItem, 1);
 						Graphics()->QuadsEnd();
 					}
@@ -126,16 +139,17 @@ void CHud::RenderScoreHud()
 						// draw name of the flag holder
 						int ID = FlagCarrier[t]%MAX_CLIENTS;
 						const char *pName = m_pClient->m_aClients[ID].m_aName;
-						float w = TextRender()->TextWidth(0, 10.0f, pName, -1);
-						TextRender()->Text(0, Whole-ScoreWidthMax-ImageSize-3*Split-w, 247.0f+t*20, 10.0f, pName, -1);
+						float w = TextRender()->TextWidth(0, 8.0f, pName, -1);
+						TextRender()->Text(0, min(Whole-w-1.0f, Whole-ScoreWidthMax-ImageSize-2*Split), StartY+(t+1)*20.0f-3.0f, 8.0f, pName, -1);
 
 						// draw tee of the flag holder
 						CTeeRenderInfo Info = m_pClient->m_aClients[ID].m_RenderInfo;
 						Info.m_Size = 18.0f;
 						RenderTools()->RenderTee(CAnimState::GetIdle(), &Info, EMOTE_NORMAL, vec2(1,0),
-							vec2(Whole-ScoreWidthMax-Info.m_Size/2-Split, 246.0f+Info.m_Size/2+t*20));
+							vec2(Whole-ScoreWidthMax-Info.m_Size/2-Split, StartY+1.0f+Info.m_Size/2+t*20));
 					}
 				}
+				StartY += 8.0f;
 			}
 		}
 		else
@@ -191,25 +205,33 @@ void CHud::RenderScoreHud()
 					Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.25f);
 				else
 					Graphics()->SetColor(0.0f, 0.0f, 0.0f, 0.25f);
-				RenderTools()->DrawRoundRectExt(Whole-ScoreWidthMax-ImageSize-2*Split-PosSize, 245.0f+t*20, ScoreWidthMax+ImageSize+2*Split+PosSize, 18.0f, 5.0f, CUI::CORNER_L);
+				RenderTools()->DrawRoundRectExt(Whole-ScoreWidthMax-ImageSize-2*Split-PosSize, StartY+t*20, ScoreWidthMax+ImageSize+2*Split+PosSize, 18.0f, 5.0f, CUI::CORNER_L);
 				Graphics()->QuadsEnd();
 
 				// draw score
-				TextRender()->Text(0, Whole-ScoreWidthMax+(ScoreWidthMax-aScoreWidth[t])/2-Split, 245.0f+t*20, 14.0f, aScore[t], -1);
+				TextRender()->Text(0, Whole-ScoreWidthMax+(ScoreWidthMax-aScoreWidth[t])/2-Split, StartY+t*20, 14.0f, aScore[t], -1);
 
-				// draw tee
 				if(apPlayerInfo[t])
  				{
-					CTeeRenderInfo Info = m_pClient->m_aClients[apPlayerInfo[t]->m_ClientID].m_RenderInfo;
+					// draw name
+					int ID = apPlayerInfo[t]->m_ClientID;
+					const char *pName = m_pClient->m_aClients[ID].m_aName;
+					float w = TextRender()->TextWidth(0, 8.0f, pName, -1);
+					TextRender()->Text(0, min(Whole-w-1.0f, Whole-ScoreWidthMax-ImageSize-2*Split-PosSize), StartY+(t+1)*20.0f-3.0f, 8.0f, pName, -1);
+
+					// draw tee
+					CTeeRenderInfo Info = m_pClient->m_aClients[ID].m_RenderInfo;
  					Info.m_Size = 18.0f;
  					RenderTools()->RenderTee(CAnimState::GetIdle(), &Info, EMOTE_NORMAL, vec2(1,0),
- 						vec2(Whole-ScoreWidthMax-Info.m_Size/2-Split, 246.0f+Info.m_Size/2+t*20));
+ 						vec2(Whole-ScoreWidthMax-Info.m_Size/2-Split, StartY+1.0f+Info.m_Size/2+t*20));
 				}
 
 				// draw position
 				char aBuf[32];
 				str_format(aBuf, sizeof(aBuf), "%d.", aPos[t]);
-				TextRender()->Text(0, Whole-ScoreWidthMax-ImageSize-Split-PosSize, 247.0f+t*20, 10.0f, aBuf, -1);
+				TextRender()->Text(0, Whole-ScoreWidthMax-ImageSize-Split-PosSize, StartY+2.0f+t*20, 10.0f, aBuf, -1);
+
+				StartY += 8.0f;
 			}
 		}
 	}
@@ -248,7 +270,7 @@ void CHud::RenderFps()
 	if(g_Config.m_ClShowfps)
 	{
 		// calculate avg. fps
-		float FPS = 1.0f / Client()->FrameTime();
+		float FPS = 1.0f / Client()->RenderFrameTime();
 		m_AverageFPS = (m_AverageFPS*(1.0f-(1.0f/m_AverageFPS))) + (FPS*(1.0f/m_AverageFPS));
 		char Buf[512];
 		str_format(Buf, sizeof(Buf), "%d", (int)m_AverageFPS);
@@ -440,6 +462,7 @@ void CHud::OnRender()
 		}
 
 		RenderGameTimer();
+		RenderPauseNotification();
 		RenderSuddenDeath();
 		RenderScoreHud();
 		RenderWarmupTimer();
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/hud.h alien-rc4/src//game/client/components/hud.h
--- teeworlds-b177-r50edfd37-source/src//game/client/components/hud.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/hud.h	2012-06-14 23:57:39.000000000 +0200
@@ -17,6 +17,7 @@ class CHud : public CComponent
 	void RenderVoting();
 	void RenderHealthAndAmmo(const CNetObj_Character *pCharacter);
 	void RenderGameTimer();
+	void RenderPauseNotification();
 	void RenderSuddenDeath();
 	void RenderScoreHud();
 	void RenderSpectatorHud();
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/items.cpp alien-rc4/src//game/client/components/items.cpp
--- teeworlds-b177-r50edfd37-source/src//game/client/components/items.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/items.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -17,12 +17,11 @@
 
 void CItems::OnReset()
 {
-	ExtraProjectilesNum = 0;
+	m_NumExtraProjectiles = 0;
 }
 
 void CItems::RenderProjectile(const CNetObj_Projectile *pCurrent, int ItemID)
 {
-
 	// get positions
 	float Curvature = 0;
 	float Speed = 0;
@@ -42,7 +41,10 @@ void CItems::RenderProjectile(const CNet
 		Speed = m_pClient->m_Tuning.m_GunSpeed;
 	}
 
-	float Ct = (Client()->PrevGameTick()-pCurrent->m_StartTick)/(float)SERVER_TICK_SPEED + Client()->GameTickTime();
+	static float s_LastGameTickTime = Client()->GameTickTime();
+	if(m_pClient->m_Snap.m_pGameInfoObj && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED))
+		s_LastGameTickTime = Client()->GameTickTime();
+	float Ct = (Client()->PrevGameTick()-pCurrent->m_StartTick)/(float)SERVER_TICK_SPEED + s_LastGameTickTime;
 	if(Ct < 0)
 		return; // projectile havn't been shot yet
 
@@ -64,28 +66,27 @@ void CItems::RenderProjectile(const CNet
 	if(pCurrent->m_Type == WEAPON_GRENADE)
 	{
 		m_pClient->m_pEffects->SmokeTrail(Pos, Vel*-1);
-		m_pClient->m_pFlow->Add(Pos, Vel*1000*Client()->FrameTime(), 10.0f);
+		static float s_Time = 0.0f;
+		static float s_LastLocalTime = Client()->LocalTime();
 
 		if(Client()->State() == IClient::STATE_DEMOPLAYBACK)
 		{
 			const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo();
-			static float Time = 0;
-			static float LastLocalTime = Client()->LocalTime();
-
 			if(!pInfo->m_Paused)
-				Time += (Client()->LocalTime()-LastLocalTime)*pInfo->m_Speed;
-
-			Graphics()->QuadsSetRotation(Time*pi*2*2 + ItemID);
-
-			LastLocalTime = Client()->LocalTime();
+				s_Time += (Client()->LocalTime()-s_LastLocalTime)*pInfo->m_Speed;
 		}
 		else
-			Graphics()->QuadsSetRotation(Client()->LocalTime()*pi*2*2 + ItemID);
+		{
+			if(m_pClient->m_Snap.m_pGameInfoObj && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED))
+				s_Time += Client()->LocalTime()-s_LastLocalTime;
+		}
+
+		Graphics()->QuadsSetRotation(s_Time*pi*2*2 + ItemID);
+		s_LastLocalTime = Client()->LocalTime();
 	}
 	else
 	{
 		m_pClient->m_pEffects->BulletTrail(Pos);
-		m_pClient->m_pFlow->Add(Pos, Vel*1000*Client()->FrameTime(), 10.0f);
 
 		if(length(Vel) > 0.00001f)
 			Graphics()->QuadsSetRotation(GetAngle(Vel));
@@ -133,26 +134,23 @@ void CItems::RenderPickup(const CNetObj_
 
 	Graphics()->QuadsSetRotation(Angle);
 
+	static float s_Time = 0.0f;
+	static float s_LastLocalTime = Client()->LocalTime();
 	float Offset = Pos.y/32.0f + Pos.x/32.0f;
 	if(Client()->State() == IClient::STATE_DEMOPLAYBACK)
 	{
 		const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo();
-		static float Time = 0;
-		static float LastLocalTime = Client()->LocalTime();
-
 		if(!pInfo->m_Paused)
-			Time += (Client()->LocalTime()-LastLocalTime)*pInfo->m_Speed;
-
-		Pos.x += cosf(Time*2.0f+Offset)*2.5f;
-		Pos.y += sinf(Time*2.0f+Offset)*2.5f;
-
-		LastLocalTime = Client()->LocalTime();
+			s_Time += (Client()->LocalTime()-s_LastLocalTime)*pInfo->m_Speed;
 	}
 	else
 	{
-		Pos.x += cosf(Client()->LocalTime()*2.0f+Offset)*2.5f;
-		Pos.y += sinf(Client()->LocalTime()*2.0f+Offset)*2.5f;
-	}
+		if(m_pClient->m_Snap.m_pGameInfoObj && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED))
+			s_Time += Client()->LocalTime()-s_LastLocalTime;
+ 	}
+	Pos.x += cosf(s_Time*2.0f+Offset)*2.5f;
+	Pos.y += sinf(s_Time*2.0f+Offset)*2.5f;
+	s_LastLocalTime = Client()->LocalTime();
 	RenderTools()->DrawSprite(Pos.x, Pos.y, Size);
 	Graphics()->QuadsEnd();
 }
@@ -310,23 +308,23 @@ void CItems::OnRender()
 	}
 
 	// render extra projectiles
-	for(int i = 0; i < ExtraProjectilesNum; i++)
+	for(int i = 0; i < m_NumExtraProjectiles; i++)
 	{
-		if(aExtraProjectiles[i].m_StartTick < Client()->GameTick())
+		if(m_aExtraProjectiles[i].m_StartTick < Client()->GameTick())
 		{
-			aExtraProjectiles[i] = aExtraProjectiles[ExtraProjectilesNum-1];
-			ExtraProjectilesNum--;
+			m_aExtraProjectiles[i] = m_aExtraProjectiles[m_NumExtraProjectiles-1];
+			m_NumExtraProjectiles--;
 		}
 		else
-			RenderProjectile(&aExtraProjectiles[i], 0);
+			RenderProjectile(&m_aExtraProjectiles[i], 0);
 	}
 }
 
 void CItems::AddExtraProjectile(CNetObj_Projectile *pProj)
 {
-	if(ExtraProjectilesNum != MAX_EXTRA_PROJECTILES)
+	if(m_NumExtraProjectiles != MAX_EXTRA_PROJECTILES)
 	{
-		aExtraProjectiles[ExtraProjectilesNum] = *pProj;
-		ExtraProjectilesNum++;
+		m_aExtraProjectiles[m_NumExtraProjectiles] = *pProj;
+		m_NumExtraProjectiles++;
 	}
 }
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/items.h alien-rc4/src//game/client/components/items.h
--- teeworlds-b177-r50edfd37-source/src//game/client/components/items.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/items.h	2012-06-14 23:57:39.000000000 +0200
@@ -11,8 +11,8 @@ class CItems : public CComponent
 		MAX_EXTRA_PROJECTILES=32,
 	};
 
-	CNetObj_Projectile aExtraProjectiles[MAX_EXTRA_PROJECTILES];
-	int ExtraProjectilesNum;
+	CNetObj_Projectile m_aExtraProjectiles[MAX_EXTRA_PROJECTILES];
+	int m_NumExtraProjectiles;
 
 	void RenderProjectile(const CNetObj_Projectile *pCurrent, int ItemID);
 	void RenderPickup(const CNetObj_Pickup *pPrev, const CNetObj_Pickup *pCurrent);
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/maplayers.cpp alien-rc4/src//game/client/components/maplayers.cpp
--- teeworlds-b177-r50edfd37-source/src//game/client/components/maplayers.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/maplayers.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -22,6 +22,9 @@ CMapLayers::CMapLayers(int t)
 {
 	m_Type = t;
 	m_pLayers = 0;
+	m_CurrentLocalTick = 0;
+	m_LastLocalTick = 0;
+	m_EnvelopeUpdate = false;
 }
 
 void CMapLayers::OnInit()
@@ -29,6 +32,17 @@ void CMapLayers::OnInit()
 	m_pLayers = Layers();
 }
 
+void CMapLayers::EnvelopeUpdate()
+{
+	if(Client()->State() == IClient::STATE_DEMOPLAYBACK)
+	{
+		const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo();
+		m_CurrentLocalTick = pInfo->m_CurrentTick;
+		m_LastLocalTick = pInfo->m_CurrentTick;
+		m_EnvelopeUpdate = true;
+	}
+}
+
 
 void CMapLayers::MapScreenToGroup(float CenterX, float CenterY, CMapItemGroup *pGroup)
 {
@@ -63,24 +77,42 @@ void CMapLayers::EnvelopeEval(float Time
 
 	CMapItemEnvelope *pItem = (CMapItemEnvelope *)pThis->m_pLayers->Map()->GetItem(Start+Env, 0, 0);
 
-	static float Time = 0;
+	static float s_Time = 0.0f;
+	static float s_LastLocalTime = pThis->Client()->LocalTime();
 	if(pThis->Client()->State() == IClient::STATE_DEMOPLAYBACK)
 	{
 		const IDemoPlayer::CInfo *pInfo = pThis->DemoPlayer()->BaseInfo();
-		static int LastLocalTick = pInfo->m_CurrentTick;
-
-		if(!pInfo->m_Paused)
-			Time += (pInfo->m_CurrentTick-LastLocalTick) / (float)pThis->Client()->GameTickSpeed() * pInfo->m_Speed;
+		
+		if(!pInfo->m_Paused || pThis->m_EnvelopeUpdate)
+		{
+			if(pThis->m_CurrentLocalTick != pInfo->m_CurrentTick)
+			{
+				pThis->m_LastLocalTick = pThis->m_CurrentLocalTick;
+				pThis->m_CurrentLocalTick = pInfo->m_CurrentTick;
+			}
 
-		pThis->RenderTools()->RenderEvalEnvelope(pPoints+pItem->m_StartPoint, pItem->m_NumPoints, 4, Time+TimeOffset, pChannels);
+			s_Time = mix(pThis->m_LastLocalTick / (float)pThis->Client()->GameTickSpeed(),
+						pThis->m_CurrentLocalTick / (float)pThis->Client()->GameTickSpeed(),
+						pThis->Client()->IntraGameTick());
+		}
 
-		LastLocalTick = pInfo->m_CurrentTick;
+		pThis->RenderTools()->RenderEvalEnvelope(pPoints+pItem->m_StartPoint, pItem->m_NumPoints, 4, s_Time+TimeOffset, pChannels);
 	}
 	else
 	{
-		if(pThis->m_pClient->m_Snap.m_pGameInfoObj)
-			Time = (pThis->Client()->GameTick()-pThis->m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick) / (float)pThis->Client()->GameTickSpeed();
-		pThis->RenderTools()->RenderEvalEnvelope(pPoints+pItem->m_StartPoint, pItem->m_NumPoints, 4, Time+TimeOffset, pChannels);
+		if(pThis->m_pClient->m_Snap.m_pGameInfoObj && !(pThis->m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED))
+		{
+			if(pItem->m_Version < 2 || pItem->m_Synchronized)
+			{
+				s_Time = mix((pThis->Client()->PrevGameTick()-pThis->m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick) / (float)pThis->Client()->GameTickSpeed(),
+							(pThis->Client()->GameTick()-pThis->m_pClient->m_Snap.m_pGameInfoObj->m_RoundStartTick) / (float)pThis->Client()->GameTickSpeed(),
+							pThis->Client()->IntraGameTick());
+			}
+			else
+				s_Time += pThis->Client()->LocalTime()-s_LastLocalTime;
+		}
+		pThis->RenderTools()->RenderEvalEnvelope(pPoints+pItem->m_StartPoint, pItem->m_NumPoints, 4, s_Time+TimeOffset, pChannels);
+		s_LastLocalTime = pThis->Client()->LocalTime();
 	}
 }
 
@@ -160,16 +192,11 @@ void CMapLayers::OnRender()
 				IOHANDLE File = Storage()->OpenFile(aFilename, IOFLAG_WRITE, IStorage::TYPE_SAVE);
 				if(File)
 				{
-					#if defined(CONF_FAMILY_WINDOWS)
-						static const char Newline[] = "\r\n";
-					#else
-						static const char Newline[] = "\n";
-					#endif
 					for(int y = 0; y < pTMap->m_Height; y++)
 					{
 						for(int x = 0; x < pTMap->m_Width; x++)
 							io_write(File, &(pTiles[y*pTMap->m_Width + x].m_Index), sizeof(pTiles[y*pTMap->m_Width + x].m_Index));
-						io_write(File, Newline, sizeof(Newline)-1);
+						io_write_newline(File);
 					}
 					io_close(File);
 				}
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/maplayers.h alien-rc4/src//game/client/components/maplayers.h
--- teeworlds-b177-r50edfd37-source/src//game/client/components/maplayers.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/maplayers.h	2012-06-14 23:57:39.000000000 +0200
@@ -8,6 +8,9 @@ class CMapLayers : public CComponent
 {
 	CLayers *m_pLayers;	// todo refactor: maybe remove it and access it through client*
 	int m_Type;
+	int m_CurrentLocalTick;
+	int m_LastLocalTick;
+	bool m_EnvelopeUpdate;
 
 	void MapScreenToGroup(float CenterX, float CenterY, CMapItemGroup *pGroup);
 	static void EnvelopeEval(float TimeOffset, int Env, float *pChannels, void *pUser);
@@ -21,6 +24,8 @@ public:
 	CMapLayers(int Type);
 	virtual void OnInit();
 	virtual void OnRender();
+
+	void EnvelopeUpdate();
 };
 
 #endif
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/menus_browser.cpp alien-rc4/src//game/client/components/menus_browser.cpp
--- teeworlds-b177-r50edfd37-source/src//game/client/components/menus_browser.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/menus_browser.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -516,7 +516,7 @@ void CMenus::RenderServerbrowserFilters(
 	ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter);
 	if (DoButton_CheckBox((char *)&g_Config.m_BrFilterPureMap, Localize("Standard map"), g_Config.m_BrFilterPureMap, &Button))
 		g_Config.m_BrFilterPureMap ^= 1;
-	
+
 	ServerFilter.HSplitTop(20.0f, &Button, &ServerFilter);
 	if (DoButton_CheckBox((char *)&g_Config.m_BrFilterGametypeStrict, Localize("Strict gametype filter"), g_Config.m_BrFilterGametypeStrict, &Button))
 		g_Config.m_BrFilterGametypeStrict ^= 1;
@@ -563,16 +563,12 @@ void CMenus::RenderServerbrowserFilters(
 		Button.HMargin(3.0f, &Button);
 		if(DoButton_CheckBox(&g_Config.m_BrFilterCountry, Localize("Player country:"), g_Config.m_BrFilterCountry, &Button))
 			g_Config.m_BrFilterCountry ^= 1;
-		
+
 		float OldWidth = Rect.w;
 		Rect.w = Rect.h*2;
 		Rect.x += (OldWidth-Rect.w)/2.0f;
-		Graphics()->TextureSet(m_pClient->m_pCountryFlags->GetByCountryCode(g_Config.m_BrFilterCountryIndex)->m_Texture);
-		Graphics()->QuadsBegin();
-		Graphics()->SetColor(1.0f, 1.0f, 1.0f, g_Config.m_BrFilterCountry?1.0f: 0.5f);
-		IGraphics::CQuadItem QuadItem(Rect.x, Rect.y, Rect.w, Rect.h);
-		Graphics()->QuadsDrawTL(&QuadItem, 1);
-		Graphics()->QuadsEnd();
+		vec4 Color(1.0f, 1.0f, 1.0f, g_Config.m_BrFilterCountry?1.0f: 0.5f);
+		m_pClient->m_pCountryFlags->Render(g_Config.m_BrFilterCountryIndex, &Color, Rect.x, Rect.y, Rect.w, Rect.h);
 
 		if(g_Config.m_BrFilterCountry && UI()->DoButtonLogic(&g_Config.m_BrFilterCountryIndex, "", 0, &Rect))
 			m_Popup = POPUP_COUNTRY;
@@ -766,12 +762,8 @@ void CMenus::RenderServerbrowserServerDe
 				TextRender()->TextEx(&Cursor, pClan, -1);
 
 			// flag
-			Graphics()->TextureSet(m_pClient->m_pCountryFlags->GetByCountryCode(pSelectedServer->m_aClients[i].m_Country)->m_Texture);
-			Graphics()->QuadsBegin();
-			Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.5f);
-			IGraphics::CQuadItem QuadItem(Flag.x, Flag.y, Flag.w, Flag.h);
-			Graphics()->QuadsDrawTL(&QuadItem, 1);
-			Graphics()->QuadsEnd();
+			vec4 Color(1.0f, 1.0f, 1.0f, 0.5f);
+			m_pClient->m_pCountryFlags->Render(pSelectedServer->m_aClients[i].m_Country, &Color, Flag.x, Flag.y, Flag.w, Flag.h);
 		}
 	}
 }
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/menus.cpp alien-rc4/src//game/client/components/menus.cpp
--- teeworlds-b177-r50edfd37-source/src//game/client/components/menus.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/menus.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -35,11 +35,10 @@ vec4 CMenus::ms_GuiColor;
 vec4 CMenus::ms_ColorTabbarInactiveOutgame;
 vec4 CMenus::ms_ColorTabbarActiveOutgame;
 vec4 CMenus::ms_ColorTabbarInactive;
-vec4 CMenus::ms_ColorTabbarActive;
+vec4 CMenus::ms_ColorTabbarActive = vec4(0,0,0,0.5f);
 vec4 CMenus::ms_ColorTabbarInactiveIngame;
 vec4 CMenus::ms_ColorTabbarActiveIngame;
 
-
 float CMenus::ms_ButtonHeight = 25.0f;
 float CMenus::ms_ListheaderHeight = 17.0f;
 float CMenus::ms_FontmodHeight = 0.8f;
@@ -95,14 +94,16 @@ int CMenus::DoButton_Icon(int ImageId, i
 	return 0;
 }
 
-int CMenus::DoButton_Toggle(const void *pID, int Checked, const CUIRect *pRect)
+int CMenus::DoButton_Toggle(const void *pID, int Checked, const CUIRect *pRect, bool Active)
 {
 	Graphics()->TextureSet(g_pData->m_aImages[IMAGE_GUIBUTTONS].m_Id);
 	Graphics()->QuadsBegin();
+	if(!Active)
+		Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.5f);
 	RenderTools()->SelectSprite(Checked?SPRITE_GUIBUTTON_ON:SPRITE_GUIBUTTON_OFF);
 	IGraphics::CQuadItem QuadItem(pRect->x, pRect->y, pRect->w, pRect->h);
 	Graphics()->QuadsDrawTL(&QuadItem, 1);
-	if((UI()->HotItem() == pID))
+	if(UI()->HotItem() == pID && Active)
 	{
 		RenderTools()->SelectSprite(SPRITE_GUIBUTTON_HOVER);
 		IGraphics::CQuadItem QuadItem(pRect->x, pRect->y, pRect->w, pRect->h);
@@ -110,7 +111,7 @@ int CMenus::DoButton_Toggle(const void *
 	}
 	Graphics()->QuadsEnd();
 
-	return UI()->DoButtonLogic(pID, "", Checked, pRect);
+	return Active ? UI()->DoButtonLogic(pID, "", Checked, pRect) : 0;
 }
 
 int CMenus::DoButton_Menu(const void *pID, const char *pText, int Checked, const CUIRect *pRect)
@@ -628,6 +629,8 @@ int CMenus::RenderMenubar(CUIRect r)
 
 void CMenus::RenderLoading()
 {
+	// TODO: not supported right now due to separate render thread
+
 	static int64 LastLoadRender = 0;
 	float Percent = m_LoadCurrent++/(float)m_LoadTotal;
 
@@ -1108,7 +1111,7 @@ int CMenus::Render()
 			Box.HSplitBottom(24.f, &Box, &Part);
 			Box.HSplitBottom(20.f, &Box, 0);
 			Box.VMargin(20.0f, &Box);
-			
+
 			static int ActSelection = -2;
 			if(ActSelection == -2)
 				ActSelection = g_Config.m_BrFilterCountryIndex;
@@ -1131,12 +1134,8 @@ int CMenus::Render()
 					float OldWidth = Item.m_Rect.w;
 					Item.m_Rect.w = Item.m_Rect.h*2;
 					Item.m_Rect.x += (OldWidth-Item.m_Rect.w)/ 2.0f;
-					Graphics()->TextureSet(pEntry->m_Texture);
-					Graphics()->QuadsBegin();
-					Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);
-					IGraphics::CQuadItem QuadItem(Item.m_Rect.x, Item.m_Rect.y, Item.m_Rect.w, Item.m_Rect.h);
-					Graphics()->QuadsDrawTL(&QuadItem, 1);
-					Graphics()->QuadsEnd();
+					vec4 Color(1.0f, 1.0f, 1.0f, 1.0f);
+					m_pClient->m_pCountryFlags->Render(pEntry->m_CountryCode, &Color, Item.m_Rect.x, Item.m_Rect.y, Item.m_Rect.w, Item.m_Rect.h);
 					UI()->DoLabel(&Label, pEntry->m_aCountryCodeString, 10.0f, 0);
 				}
 			}
@@ -1402,8 +1401,8 @@ void CMenus::OnStateChange(int NewState,
 
 	if(NewState == IClient::STATE_OFFLINE)
 	{
-		if(OldState >= IClient::STATE_ONLINE)
-			m_pClient->m_pSounds->Play(CSounds::CHN_MUSIC, SOUND_MENU, 1.0f, vec2(0, 0));
+		if(OldState >= IClient::STATE_ONLINE && NewState < IClient::STATE_QUITING)
+			m_pClient->m_pSounds->Play(CSounds::CHN_MUSIC, SOUND_MENU, 1.0f);
 		m_Popup = POPUP_NONE;
 		if(Client()->ErrorString() && Client()->ErrorString()[0] != 0)
 		{
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/menus_demo.cpp alien-rc4/src//game/client/components/menus_demo.cpp
--- teeworlds-b177-r50edfd37-source/src//game/client/components/menus_demo.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/menus_demo.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -17,6 +17,7 @@
 
 #include <game/generated/client_data.h>
 
+#include "maplayers.h"
 #include "menus.h"
 
 int CMenus::DoButton_DemoPlayer(const void *pID, const char *pText, int Checked, const CUIRect *pRect)
@@ -85,15 +86,28 @@ void CMenus::RenderDemoPlayer(CUIRect Ma
 		void *id = &s_SeekBarID;
 		char aBuffer[128];
 
+		// draw seek bar
 		RenderTools()->DrawUIRect(&SeekBar, vec4(0,0,0,0.5f), CUI::CORNER_ALL, 5.0f);
 
+		// draw filled bar
 		float Amount = CurrentTick/(float)TotalTicks;
-
 		CUIRect FilledBar = SeekBar;
 		FilledBar.w = 10.0f + (FilledBar.w-10.0f)*Amount;
-
 		RenderTools()->DrawUIRect(&FilledBar, vec4(1,1,1,0.5f), CUI::CORNER_ALL, 5.0f);
 
+		// draw markers
+		for(int i = 0; i < pInfo->m_NumTimelineMarkers; i++)
+		{
+			float Ratio = (pInfo->m_aTimelineMarkers[i]-pInfo->m_FirstTick) / (float)TotalTicks;
+			Graphics()->TextureSet(-1);
+			Graphics()->QuadsBegin();
+			Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);
+			IGraphics::CQuadItem QuadItem(SeekBar.x + (SeekBar.w-10.0f)*Ratio, SeekBar.y, UI()->PixelSize(), SeekBar.h);
+			Graphics()->QuadsDrawTL(&QuadItem, 1);
+			Graphics()->QuadsEnd();
+		}
+
+		// draw time
 		str_format(aBuffer, sizeof(aBuffer), "%d:%02d / %d:%02d",
 			CurrentTick/SERVER_TICK_SPEED/60, (CurrentTick/SERVER_TICK_SPEED)%60,
 			TotalTicks/SERVER_TICK_SPEED/60, (TotalTicks/SERVER_TICK_SPEED)%60);
@@ -117,6 +131,8 @@ void CMenus::RenderDemoPlayer(CUIRect Ma
 					m_pClient->m_SuppressEvents = true;
 					DemoPlayer()->SetPos(Amount);
 					m_pClient->m_SuppressEvents = false;
+					m_pClient->m_pMapLayersBackGround->EnvelopeUpdate();
+					m_pClient->m_pMapLayersForeGround->EnvelopeUpdate();
 				}
 			}
 		}
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/menus.h alien-rc4/src//game/client/components/menus.h
--- teeworlds-b177-r50edfd37-source/src//game/client/components/menus.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/menus.h	2012-06-14 23:57:39.000000000 +0200
@@ -40,7 +40,7 @@ class CMenus : public CComponent
 
 	int DoButton_DemoPlayer(const void *pID, const char *pText, int Checked, const CUIRect *pRect);
 	int DoButton_Sprite(const void *pID, int ImageID, int SpriteID, int Checked, const CUIRect *pRect, int Corners);
-	int DoButton_Toggle(const void *pID, int Checked, const CUIRect *pRect);
+	int DoButton_Toggle(const void *pID, int Checked, const CUIRect *pRect, bool Active);
 	int DoButton_Menu(const void *pID, const char *pText, int Checked, const CUIRect *pRect);
 	int DoButton_MenuTab(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Corners);
 
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/menus_ingame.cpp alien-rc4/src//game/client/components/menus_ingame.cpp
--- teeworlds-b177-r50edfd37-source/src//game/client/components/menus_ingame.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/menus_ingame.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -149,7 +149,11 @@ void CMenus::RenderPlayers(CUIRect MainV
 	static int s_aPlayerIDs[MAX_CLIENTS][2] = {{0}};
 	for(int i = 0, Count = 0; i < MAX_CLIENTS; ++i)
 	{
-		if(!m_pClient->m_Snap.m_paPlayerInfos[i] || i == m_pClient->m_Snap.m_LocalClientID)
+		if(!m_pClient->m_Snap.m_paInfoByTeam[i])
+			continue;
+
+		int Index = m_pClient->m_Snap.m_paInfoByTeam[i]->m_ClientID;
+		if(Index == m_pClient->m_Snap.m_LocalClientID)
 			continue;
 
 		Options.HSplitTop(28.0f, &ButtonBar, &Options);
@@ -159,7 +163,7 @@ void CMenus::RenderPlayers(CUIRect MainV
 
 		// player info
 		Player.VSplitLeft(28.0f, &Button, &Player);
-		CTeeRenderInfo Info = m_pClient->m_aClients[i].m_RenderInfo;
+		CTeeRenderInfo Info = m_pClient->m_aClients[Index].m_RenderInfo;
 		Info.m_Size = Button.h;
 		RenderTools()->RenderTee(CAnimState::GetIdle(), &Info, EMOTE_NORMAL, vec2(1.0f, 0.0f), vec2(Button.x+Button.h/2, Button.y+Button.h/2));
 
@@ -168,31 +172,34 @@ void CMenus::RenderPlayers(CUIRect MainV
 		CTextCursor Cursor;
 		TextRender()->SetCursor(&Cursor, Player.x, Player.y, 14.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);
 		Cursor.m_LineWidth = Player.w;
-		TextRender()->TextEx(&Cursor, m_pClient->m_aClients[i].m_aName, -1);
+		TextRender()->TextEx(&Cursor, m_pClient->m_aClients[Index].m_aName, -1);
 
 		TextRender()->SetCursor(&Cursor, Button.x,Button.y, 14.0f, TEXTFLAG_RENDER|TEXTFLAG_STOP_AT_END);
 		Cursor.m_LineWidth = Button.w;
-		TextRender()->TextEx(&Cursor, m_pClient->m_aClients[i].m_aClan, -1);
+		TextRender()->TextEx(&Cursor, m_pClient->m_aClients[Index].m_aClan, -1);
 
 		// ignore button
 		ButtonBar.HMargin(2.0f, &ButtonBar);
 		ButtonBar.VSplitLeft(Width, &Button, &ButtonBar);
 		Button.VSplitLeft((Width-Button.h)/4.0f, 0, &Button);
 		Button.VSplitLeft(Button.h, &Button, 0);
-		if(DoButton_Toggle(&s_aPlayerIDs[i][0], m_pClient->m_aClients[i].m_ChatIgnore, &Button))
-			m_pClient->m_aClients[i].m_ChatIgnore ^= 1;
+		if(&g_Config.m_ClShowChatFriends && !m_pClient->m_aClients[Index].m_Friend)
+			DoButton_Toggle(&s_aPlayerIDs[Index][0], 1, &Button, false);
+		else
+			if(DoButton_Toggle(&s_aPlayerIDs[Index][0], m_pClient->m_aClients[Index].m_ChatIgnore, &Button, true))
+				m_pClient->m_aClients[Index].m_ChatIgnore ^= 1;
 
 		// friend button
 		ButtonBar.VSplitLeft(20.0f, &Button, &ButtonBar);
 		ButtonBar.VSplitLeft(Width, &Button, &ButtonBar);
 		Button.VSplitLeft((Width-Button.h)/4.0f, 0, &Button);
 		Button.VSplitLeft(Button.h, &Button, 0);
-		if(DoButton_Toggle(&s_aPlayerIDs[i][1], m_pClient->m_aClients[i].m_Friend, &Button))
+		if(DoButton_Toggle(&s_aPlayerIDs[Index][1], m_pClient->m_aClients[Index].m_Friend, &Button, true))
 		{
-			if(m_pClient->m_aClients[i].m_Friend)
-				m_pClient->Friends()->RemoveFriend(m_pClient->m_aClients[i].m_aName, m_pClient->m_aClients[i].m_aClan);
+			if(m_pClient->m_aClients[Index].m_Friend)
+				m_pClient->Friends()->RemoveFriend(m_pClient->m_aClients[Index].m_aName, m_pClient->m_aClients[Index].m_aClan);
 			else
-				m_pClient->Friends()->AddFriend(m_pClient->m_aClients[i].m_aName, m_pClient->m_aClients[i].m_aClan);
+				m_pClient->Friends()->AddFriend(m_pClient->m_aClients[Index].m_aName, m_pClient->m_aClients[Index].m_aClan);
 		}
 	}
 
@@ -385,13 +392,15 @@ void CMenus::RenderServerControlKick(CUI
 	static int aPlayerIDs[MAX_CLIENTS];
 	for(int i = 0; i < MAX_CLIENTS; i++)
 	{
-		if(!m_pClient->m_Snap.m_paPlayerInfos[i] || i == m_pClient->m_Snap.m_LocalClientID)
+		if(!m_pClient->m_Snap.m_paInfoByTeam[i])
 			continue;
-		if(FilterSpectators && m_pClient->m_Snap.m_paPlayerInfos[i]->m_Team == TEAM_SPECTATORS)
+
+		int Index = m_pClient->m_Snap.m_paInfoByTeam[i]->m_ClientID;
+		if(Index == m_pClient->m_Snap.m_LocalClientID || (FilterSpectators && m_pClient->m_Snap.m_paInfoByTeam[i]->m_Team == TEAM_SPECTATORS))
 			continue;
-		if(m_CallvoteSelectedPlayer == i)
+		if(m_CallvoteSelectedPlayer == Index)
 			Selected = NumOptions;
-		aPlayerIDs[NumOptions++] = i;
+		aPlayerIDs[NumOptions++] = Index;
 	}
 
 	static int s_VoteList = 0;
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/menus_settings.cpp alien-rc4/src//game/client/components/menus_settings.cpp
--- teeworlds-b177-r50edfd37-source/src//game/client/components/menus_settings.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/menus_settings.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -96,6 +96,12 @@ void CMenus::RenderSettingsGeneral(CUIRe
 		if(DoButton_CheckBox(&g_Config.m_ClShowhud, Localize("Show ingame HUD"), g_Config.m_ClShowhud, &Button))
 			g_Config.m_ClShowhud ^= 1;
 
+		// chat messages
+		Left.HSplitTop(5.0f, 0, &Left);
+		Left.HSplitTop(20.0f, &Button, &Left);
+		if(DoButton_CheckBox(&g_Config.m_ClShowChatFriends, Localize("Show only chat messages from friends"), g_Config.m_ClShowChatFriends, &Button))
+			g_Config.m_ClShowChatFriends ^= 1;
+
 		// name plates
 		Right.HSplitTop(20.0f, &Button, &Right);
 		if(DoButton_CheckBox(&g_Config.m_ClNameplates, Localize("Show name plates"), g_Config.m_ClNameplates, &Button))
@@ -221,13 +227,10 @@ void CMenus::RenderSettingsPlayer(CUIRec
 			float OldWidth = Item.m_Rect.w;
 			Item.m_Rect.w = Item.m_Rect.h*2;
 			Item.m_Rect.x += (OldWidth-Item.m_Rect.w)/ 2.0f;
-			Graphics()->TextureSet(pEntry->m_Texture);
-			Graphics()->QuadsBegin();
-			Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);
-			IGraphics::CQuadItem QuadItem(Item.m_Rect.x, Item.m_Rect.y, Item.m_Rect.w, Item.m_Rect.h);
-			Graphics()->QuadsDrawTL(&QuadItem, 1);
-			Graphics()->QuadsEnd();
-			UI()->DoLabel(&Label, pEntry->m_aCountryCodeString, 10.0f, 0);
+			vec4 Color(1.0f, 1.0f, 1.0f, 1.0f);
+			m_pClient->m_pCountryFlags->Render(pEntry->m_CountryCode, &Color, Item.m_Rect.x, Item.m_Rect.y, Item.m_Rect.w, Item.m_Rect.h);
+			if(pEntry->m_Texture != -1)
+				UI()->DoLabel(&Label, pEntry->m_aCountryCodeString, 10.0f, 0);
 		}
 	}
 
@@ -446,13 +449,14 @@ static CKeyInfo gs_aKeys[] =
 	{ "Remote console", "toggle_remote_console", 0 },
 	{ "Screenshot", "screenshot", 0 },
 	{ "Scoreboard", "+scoreboard", 0 },
+	{ "Respawn", "kill", 0 },
 };
 
 /*	This is for scripts/update_localization.py to work, don't remove!
 	Localize("Move left");Localize("Move right");Localize("Jump");Localize("Fire");Localize("Hook");Localize("Hammer");
 	Localize("Pistol");Localize("Shotgun");Localize("Grenade");Localize("Rifle");Localize("Next weapon");Localize("Prev. weapon");
 	Localize("Vote yes");Localize("Vote no");Localize("Chat");Localize("Team chat");Localize("Show chat");Localize("Emoticon");
-	Localize("Spectator mode");Localize("Spectate next");Localize("Spectate previous");Localize("Console");Localize("Remote console");Localize("Screenshot");Localize("Scoreboard");
+	Localize("Spectator mode");Localize("Spectate next");Localize("Spectate previous");Localize("Console");Localize("Remote console");Localize("Screenshot");Localize("Scoreboard");Localize("Respawn");
 */
 
 const int g_KeyCount = sizeof(gs_aKeys) / sizeof(CKeyInfo);
@@ -504,10 +508,11 @@ void CMenus::RenderSettingsControls(CUIR
 	}
 
 	CUIRect MovementSettings, WeaponSettings, VotingSettings, ChatSettings, MiscSettings, ResetButton;
-	MainView.VSplitLeft(MainView.w/2-5.0f, &MovementSettings, &VotingSettings);
+	MainView.VSplitMid(&MovementSettings, &VotingSettings);
 
 	// movement settings
 	{
+		MovementSettings.VMargin(5.0f, &MovementSettings);
 		MovementSettings.HSplitTop(MainView.h/3+60.0f, &MovementSettings, &WeaponSettings);
 		RenderTools()->DrawUIRect(&MovementSettings, vec4(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f);
 		MovementSettings.Margin(10.0f, &MovementSettings);
@@ -543,21 +548,22 @@ void CMenus::RenderSettingsControls(CUIR
 		WeaponSettings.HSplitTop(14.0f+5.0f+10.0f, 0, &WeaponSettings);
 		UiDoGetButtons(5, 12, WeaponSettings);
 	}
-	
+
 	// defaults
 	{
 		ResetButton.HSplitTop(10.0f, 0, &ResetButton);
 		RenderTools()->DrawUIRect(&ResetButton, vec4(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f);
 		ResetButton.HMargin(10.0f, &ResetButton);
 		ResetButton.VMargin(30.0f, &ResetButton);
+		ResetButton.HSplitTop(20.0f, &ResetButton, 0);
 		static int s_DefaultButton = 0;
 		if(DoButton_Menu((void*)&s_DefaultButton, Localize("Reset to defaults"), 0, &ResetButton))
 			m_pClient->m_pBinds->SetDefaults();
 	}
-	
+
 	// voting settings
 	{
-		VotingSettings.VSplitLeft(10.0f, 0, &VotingSettings);
+		VotingSettings.VMargin(5.0f, &VotingSettings);
 		VotingSettings.HSplitTop(MainView.h/3-75.0f, &VotingSettings, &ChatSettings);
 		RenderTools()->DrawUIRect(&VotingSettings, vec4(1,1,1,0.25f), CUI::CORNER_ALL, 10.0f);
 		VotingSettings.Margin(10.0f, &VotingSettings);
@@ -590,7 +596,7 @@ void CMenus::RenderSettingsControls(CUIR
 		TextRender()->Text(0, MiscSettings.x, MiscSettings.y, 14.0f*UI()->Scale(), Localize("Miscellaneous"), -1);
 
 		MiscSettings.HSplitTop(14.0f+5.0f+10.0f, 0, &MiscSettings);
-		UiDoGetButtons(17, 25, MiscSettings);
+		UiDoGetButtons(17, 26, MiscSettings);
 	}
 
 }
@@ -761,7 +767,7 @@ void CMenus::RenderSettingsSound(CUIRect
 		if(g_Config.m_SndEnable)
 		{
 			if(g_Config.m_SndMusic)
-				m_pClient->m_pSounds->Play(CSounds::CHN_MUSIC, SOUND_MENU, 1.0f, vec2(0, 0));
+				m_pClient->m_pSounds->Play(CSounds::CHN_MUSIC, SOUND_MENU, 1.0f);
 		}
 		else
 			m_pClient->m_pSounds->Stop(SOUND_MENU);
@@ -776,7 +782,7 @@ void CMenus::RenderSettingsSound(CUIRect
 	{
 		g_Config.m_SndMusic ^= 1;
 		if(g_Config.m_SndMusic)
-			m_pClient->m_pSounds->Play(CSounds::CHN_MUSIC, SOUND_MENU, 1.0f, vec2(0, 0));
+			m_pClient->m_pSounds->Play(CSounds::CHN_MUSIC, SOUND_MENU, 1.0f);
 		else
 			m_pClient->m_pSounds->Stop(SOUND_MENU);
 	}
@@ -917,11 +923,8 @@ void CMenus::RenderLanguageSelection(CUI
 			Item.m_Rect.VSplitLeft(Item.m_Rect.h*2.0f, &Rect, &Item.m_Rect);
 			Rect.VMargin(6.0f, &Rect);
 			Rect.HMargin(3.0f, &Rect);
-			Graphics()->TextureSet(m_pClient->m_pCountryFlags->GetByCountryCode(r.front().m_CountryCode)->m_Texture);
-			Graphics()->QuadsBegin();
-			IGraphics::CQuadItem QuadItem(Rect.x, Rect.y, Rect.w, Rect.h);
-			Graphics()->QuadsDrawTL(&QuadItem, 1);
-			Graphics()->QuadsEnd();
+			vec4 Color(1.0f, 1.0f, 1.0f, 1.0f);
+			m_pClient->m_pCountryFlags->Render(r.front().m_CountryCode, &Color, Rect.x, Rect.y, Rect.w, Rect.h);
 			Item.m_Rect.HSplitTop(2.0f, 0, &Item.m_Rect);
  			UI()->DoLabelScaled(&Item.m_Rect, r.front().m_Name, 16.0f, -1);
 		}
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/particles.cpp alien-rc4/src//game/client/components/particles.cpp
--- teeworlds-b177-r50edfd37-source/src//game/client/components/particles.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/particles.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -43,6 +43,11 @@ void CParticles::Add(int Group, CParticl
 		if(pInfo->m_Paused)
 			return;
 	}
+	else
+	{
+		if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED)
+			return;
+	}
 
 	if (m_FirstFree == -1)
 		return;
@@ -142,7 +147,10 @@ void CParticles::OnRender()
 			Update((float)((t-LastTime)/(double)time_freq())*pInfo->m_Speed);
 	}
 	else
-		Update((float)((t-LastTime)/(double)time_freq()));
+	{
+		if(m_pClient->m_Snap.m_pGameInfoObj && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED))
+			Update((float)((t-LastTime)/(double)time_freq()));
+	}
 
 	LastTime = t;
 }
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/players.cpp alien-rc4/src//game/client/components/players.cpp
--- teeworlds-b177-r50edfd37-source/src//game/client/components/players.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/players.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -95,30 +95,7 @@ void CPlayers::RenderHook(
 	Player = *pPlayerChar;
 
 	CNetObj_PlayerInfo pInfo = *pPlayerInfo;
-	CTeeRenderInfo RenderInfo = m_pClient->m_aClients[pInfo.m_ClientID].m_RenderInfo;
-
-	// check for teamplay modes
-	bool IsTeamplay = false;
-	if(m_pClient->m_Snap.m_pGameInfoObj)
-		IsTeamplay = (m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS) != 0;
-
-	// check for ninja
-	if (Player.m_Weapon == WEAPON_NINJA)
-	{
-		// change the skin for the player to the ninja
-		int Skin = m_pClient->m_pSkins->Find("x_ninja");
-		if(Skin != -1)
-		{
-			if(IsTeamplay)
-				RenderInfo.m_Texture = m_pClient->m_pSkins->Get(Skin)->m_ColorTexture;
-			else
-			{
-				RenderInfo.m_Texture = m_pClient->m_pSkins->Get(Skin)->m_OrgTexture;
-				RenderInfo.m_ColorBody = vec4(1,1,1,1);
-				RenderInfo.m_ColorFeet = vec4(1,1,1,1);
-			}
-		}
-	}
+	CTeeRenderInfo RenderInfo = m_aRenderInfo[pInfo.m_ClientID];
 
 	float IntraTick = Client()->IntraGameTick();
 
@@ -218,31 +195,9 @@ void CPlayers::RenderPlayer(
 	Player = *pPlayerChar;
 
 	CNetObj_PlayerInfo pInfo = *pPlayerInfo;
-	CTeeRenderInfo RenderInfo = m_pClient->m_aClients[pInfo.m_ClientID].m_RenderInfo;
+	CTeeRenderInfo RenderInfo = m_aRenderInfo[pInfo.m_ClientID];
 
-	// check for teamplay modes
-	bool IsTeamplay = false;
 	bool NewTick = m_pClient->m_NewTick;
-	if(m_pClient->m_Snap.m_pGameInfoObj)
-		IsTeamplay = (m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS) != 0;
-
-	// check for ninja
-	if (Player.m_Weapon == WEAPON_NINJA)
-	{
-		// change the skin for the player to the ninja
-		int Skin = m_pClient->m_pSkins->Find("x_ninja");
-		if(Skin != -1)
-		{
-			if(IsTeamplay)
-				RenderInfo.m_Texture = m_pClient->m_pSkins->Get(Skin)->m_ColorTexture;
-			else
-			{
-				RenderInfo.m_Texture = m_pClient->m_pSkins->Get(Skin)->m_OrgTexture;
-				RenderInfo.m_ColorBody = vec4(1,1,1,1);
-				RenderInfo.m_ColorFeet = vec4(1,1,1,1);
-			}
-		}
-	}
 
 	// set size
 	RenderInfo.m_Size = 64.0f;
@@ -330,14 +285,17 @@ void CPlayers::RenderPlayer(
 	else if(!WantOtherDir)
 		State.Add(&g_pData->m_aAnimations[ANIM_WALK], WalkTime, 1.0f);
 
+	static float s_LastGameTickTime = Client()->GameTickTime();
+	if(m_pClient->m_Snap.m_pGameInfoObj && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED))
+		s_LastGameTickTime = Client()->GameTickTime();
 	if (Player.m_Weapon == WEAPON_HAMMER)
 	{
-		float ct = (Client()->PrevGameTick()-Player.m_AttackTick)/(float)SERVER_TICK_SPEED + Client()->GameTickTime();
+		float ct = (Client()->PrevGameTick()-Player.m_AttackTick)/(float)SERVER_TICK_SPEED + s_LastGameTickTime;
 		State.Add(&g_pData->m_aAnimations[ANIM_HAMMER_SWING], clamp(ct*5.0f,0.0f,1.0f), 1.0f);
 	}
 	if (Player.m_Weapon == WEAPON_NINJA)
 	{
-		float ct = (Client()->PrevGameTick()-Player.m_AttackTick)/(float)SERVER_TICK_SPEED + Client()->GameTickTime();
+		float ct = (Client()->PrevGameTick()-Player.m_AttackTick)/(float)SERVER_TICK_SPEED + s_LastGameTickTime;
 		State.Add(&g_pData->m_aAnimations[ANIM_NINJA_SWING], clamp(ct*2.0f,0.0f,1.0f), 1.0f);
 	}
 
@@ -347,7 +305,7 @@ void CPlayers::RenderPlayer(
 		static int64 SkidSoundTime = 0;
 		if(time_get()-SkidSoundTime > time_freq()/10)
 		{
-			m_pClient->m_pSounds->Play(CSounds::CHN_WORLD, SOUND_PLAYER_SKID, 0.25f, Position);
+			m_pClient->m_pSounds->PlayAt(CSounds::CHN_WORLD, SOUND_PLAYER_SKID, 0.25f, Position);
 			SkidSoundTime = time_get();
 		}
 
@@ -409,15 +367,22 @@ void CPlayers::RenderPlayer(
 			if ((Client()->GameTick()-Player.m_AttackTick) <= (SERVER_TICK_SPEED / 6) && g_pData->m_Weapons.m_aId[iw].m_NumSpriteMuzzles)
 			{
 				int IteX = rand() % g_pData->m_Weapons.m_aId[iw].m_NumSpriteMuzzles;
+				static int s_LastIteX = IteX;
 				if(Client()->State() == IClient::STATE_DEMOPLAYBACK)
 				{
-					static int s_LastIteX = IteX;
 					const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo();
 					if(pInfo->m_Paused)
 						IteX = s_LastIteX;
 					else
 						s_LastIteX = IteX;
 				}
+				else
+				{
+					if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED)
+						IteX = s_LastIteX;
+					else
+						s_LastIteX = IteX;
+				}
 				if(g_pData->m_Weapons.m_aId[iw].m_aSpriteMuzzles[IteX])
 				{
 					vec2 Dir = vec2(pPlayerChar->m_X,pPlayerChar->m_Y) - vec2(pPrevChar->m_X, pPrevChar->m_Y);
@@ -438,7 +403,11 @@ void CPlayers::RenderPlayer(
 		{
 			// TODO: should be an animation
 			Recoil = 0;
-			float a = (Client()->GameTick()-Player.m_AttackTick+IntraTick)/5.0f;
+			static float s_LastIntraTick = IntraTick;
+			if(m_pClient->m_Snap.m_pGameInfoObj && !(m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED))
+				s_LastIntraTick = IntraTick;
+
+			float a = (Client()->GameTick()-Player.m_AttackTick+s_LastIntraTick)/5.0f;
 			if(a < 1)
 				Recoil = sinf(a*pi);
 			p = Position + Dir * g_pData->m_Weapons.m_aId[iw].m_Offsetx - Dir*Recoil*10.0f;
@@ -460,6 +429,22 @@ void CPlayers::RenderPlayer(
 				}
 
 				int IteX = rand() % g_pData->m_Weapons.m_aId[iw].m_NumSpriteMuzzles;
+				static int s_LastIteX = IteX;
+				if(Client()->State() == IClient::STATE_DEMOPLAYBACK)
+				{
+					const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo();
+					if(pInfo->m_Paused)
+						IteX = s_LastIteX;
+					else
+						s_LastIteX = IteX;
+				}
+				else
+				{
+					if(m_pClient->m_Snap.m_pGameInfoObj && m_pClient->m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_PAUSED)
+						IteX = s_LastIteX;
+					else
+						s_LastIteX = IteX;
+				}
 				if (Alpha > 0.0f && g_pData->m_Weapons.m_aId[iw].m_aSpriteMuzzles[IteX])
 				{
 					float OffsetY = -g_pData->m_Weapons.m_aId[iw].m_Muzzleoffsety;
@@ -546,6 +531,31 @@ void CPlayers::RenderPlayer(
 
 void CPlayers::OnRender()
 {
+	// update RenderInfo for ninja
+	bool IsTeamplay = false;
+	if(m_pClient->m_Snap.m_pGameInfoObj)
+		IsTeamplay = (m_pClient->m_Snap.m_pGameInfoObj->m_GameFlags&GAMEFLAG_TEAMS) != 0;
+	for(int i = 0; i < MAX_CLIENTS; ++i)
+	{
+		m_aRenderInfo[i] = m_pClient->m_aClients[i].m_RenderInfo;
+		if(m_pClient->m_Snap.m_aCharacters[i].m_Cur.m_Weapon == WEAPON_NINJA)
+		{
+			// change the skin for the player to the ninja
+			int Skin = m_pClient->m_pSkins->Find("x_ninja");
+			if(Skin != -1)
+			{
+				if(IsTeamplay)
+					m_aRenderInfo[i].m_Texture = m_pClient->m_pSkins->Get(Skin)->m_ColorTexture;
+				else
+				{
+					m_aRenderInfo[i].m_Texture = m_pClient->m_pSkins->Get(Skin)->m_OrgTexture;
+					m_aRenderInfo[i].m_ColorBody = vec4(1,1,1,1);
+					m_aRenderInfo[i].m_ColorFeet = vec4(1,1,1,1);
+				}
+			}
+		}
+	}
+
 	// render other players in two passes, first pass we render the other, second pass we render our self
 	for(int p = 0; p < 4; p++)
 	{
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/players.h alien-rc4/src//game/client/components/players.h
--- teeworlds-b177-r50edfd37-source/src//game/client/components/players.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/players.h	2012-06-14 23:57:39.000000000 +0200
@@ -6,6 +6,7 @@
 
 class CPlayers : public CComponent
 {
+	CTeeRenderInfo m_aRenderInfo[MAX_CLIENTS];
 	void RenderHand(class CTeeRenderInfo *pInfo, vec2 CenterPos, vec2 Dir, float AngleOffset, vec2 PostRotOffset);
 	void RenderPlayer(
 		const CNetObj_Character *pPrevChar,
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/scoreboard.cpp alien-rc4/src//game/client/components/scoreboard.cpp
--- teeworlds-b177-r50edfd37-source/src//game/client/components/scoreboard.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/scoreboard.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -273,12 +273,9 @@ void CScoreboard::RenderScoreboard(float
 		TextRender()->TextEx(&Cursor, m_pClient->m_aClients[pInfo->m_ClientID].m_aClan, -1);
 
 		// country flag
-		Graphics()->TextureSet(m_pClient->m_pCountryFlags->GetByCountryCode(m_pClient->m_aClients[pInfo->m_ClientID].m_Country)->m_Texture);
-		Graphics()->QuadsBegin();
-		Graphics()->SetColor(1.0f, 1.0f, 1.0f, 0.5f);
-		IGraphics::CQuadItem QuadItem(CountryOffset, y+(Spacing+TeeSizeMod*5.0f)/2.0f, CountryLength, LineHeight-Spacing-TeeSizeMod*5.0f);
-		Graphics()->QuadsDrawTL(&QuadItem, 1);
-		Graphics()->QuadsEnd();
+		vec4 Color(1.0f, 1.0f, 1.0f, 0.5f);
+		m_pClient->m_pCountryFlags->Render(m_pClient->m_aClients[pInfo->m_ClientID].m_Country, &Color,
+											CountryOffset, y+(Spacing+TeeSizeMod*5.0f)/2.0f, CountryLength, LineHeight-Spacing-TeeSizeMod*5.0f);
 
 		// ping
 		str_format(aBuf, sizeof(aBuf), "%d", clamp(pInfo->m_Latency, 0, 1000));
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/skins.cpp alien-rc4/src//game/client/components/skins.cpp
--- teeworlds-b177-r50edfd37-source/src//game/client/components/skins.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/skins.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -7,6 +7,7 @@
 
 #include <engine/graphics.h>
 #include <engine/storage.h>
+#include <engine/shared/config.h>
 
 #include "skins.h"
 
@@ -103,8 +104,11 @@ int CSkins::SkinScan(const char *pName,
 
 	// set skin data
 	str_copy(Skin.m_aName, pName, min((int)sizeof(Skin.m_aName),l-3));
-	str_format(aBuf, sizeof(aBuf), "load skin %s", Skin.m_aName);
-	pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "game", aBuf);
+	if(g_Config.m_Debug)
+	{
+		str_format(aBuf, sizeof(aBuf), "load skin %s", Skin.m_aName);
+		pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_ADDINFO, "game", aBuf);
+	}
 	pSelf->m_aSkins.add(Skin);
 
 	return 0;
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/sounds.cpp alien-rc4/src//game/client/components/sounds.cpp
--- teeworlds-b177-r50edfd37-source/src//game/client/components/sounds.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/sounds.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -34,6 +34,30 @@ static int LoadSoundsThread(void *pUser)
 
 	return 0;
 }
+
+int CSounds::GetSampleId(int SetId)
+{
+	if(!g_Config.m_SndEnable || !Sound()->IsSoundEnabled() || m_WaitForSoundJob || SetId < 0 || SetId >= g_pData->m_NumSounds)
+		return -1;
+	
+	CDataSoundset *pSet = &g_pData->m_aSounds[SetId];
+	if(!pSet->m_NumSounds)
+		return -1;
+
+	if(pSet->m_NumSounds == 1)
+		return pSet->m_aSounds[0].m_Id;
+
+	// return random one
+	int Id;
+	do
+	{
+		Id = rand() % pSet->m_NumSounds;
+	}
+	while(Id == pSet->m_Last);
+	pSet->m_Last = Id;
+	return pSet->m_aSounds[Id].m_Id;
+}
+
 void CSounds::OnInit()
 {
 	// setup sound channels
@@ -98,7 +122,7 @@ void CSounds::OnRender()
 		int64 Now = time_get();
 		if(m_QueueWaitTime <= Now)
 		{
-			Play(m_aQueue[0].m_Channel, m_aQueue[0].m_SetId, 1.0f, vec2(0,0));
+			Play(m_aQueue[0].m_Channel, m_aQueue[0].m_SetId, 1.0f);
 			m_QueueWaitTime = Now+time_freq()*3/10; // wait 300ms before playing the next one
 			if(--m_QueuePos > 0)
 				mem_move(m_aQueue, m_aQueue+1, m_QueuePos*sizeof(QueueEntry));
@@ -132,47 +156,48 @@ void CSounds::PlayAndRecord(int Chn, int
 	Msg.m_SoundID = SetId;
 	Client()->SendPackMsg(&Msg, MSGFLAG_NOSEND|MSGFLAG_RECORD);
 
-	Play(Chn, SetId, Vol, Pos);
+	Play(Chn, SetId, Vol);
 }
 
-void CSounds::Play(int Chn, int SetId, float Vol, vec2 Pos)
+void CSounds::Play(int Chn, int SetId, float Vol)
 {
-	if(!g_Config.m_SndEnable || !Sound()->IsSoundEnabled() || (Chn == CHN_MUSIC && !g_Config.m_SndMusic) || m_WaitForSoundJob || SetId < 0 || SetId >= g_pData->m_NumSounds)
+	if(Chn == CHN_MUSIC && !g_Config.m_SndMusic)
 		return;
 
-	CDataSoundset *pSet = &g_pData->m_aSounds[SetId];
-
-	if(!pSet->m_NumSounds)
+	int SampleId = GetSampleId(SetId);
+	if(SampleId == -1)
 		return;
-	
+
 	int Flags = 0;
 	if(Chn == CHN_MUSIC)
 		Flags = ISound::FLAG_LOOP;
 
-	if(pSet->m_NumSounds == 1)
-	{
-		Sound()->PlayAt(Chn, pSet->m_aSounds[0].m_Id, Flags, Pos.x, Pos.y);
+	Sound()->Play(Chn, SampleId, Flags);
+}
+
+void CSounds::PlayAt(int Chn, int SetId, float Vol, vec2 Pos)
+{
+	if(Chn == CHN_MUSIC && !g_Config.m_SndMusic)
+		return;
+	
+	int SampleId = GetSampleId(SetId);
+	if(SampleId == -1)
 		return;
-	}
 
-	// play a random one
-	int Id;
-	do
-	{
-		Id = rand() % pSet->m_NumSounds;
-	}
-	while(Id == pSet->m_Last);
-	Sound()->PlayAt(Chn, pSet->m_aSounds[Id].m_Id, Flags, Pos.x, Pos.y);
-	pSet->m_Last = Id;
+	int Flags = 0;
+	if(Chn == CHN_MUSIC)
+		Flags = ISound::FLAG_LOOP;
+
+	Sound()->PlayAt(Chn, SampleId, Flags, Pos.x, Pos.y);
 }
 
 void CSounds::Stop(int SetId)
 {
 	if(m_WaitForSoundJob || SetId < 0 || SetId >= g_pData->m_NumSounds)
 		return;
-	
+
 	CDataSoundset *pSet = &g_pData->m_aSounds[SetId];
-	
+
 	for(int i = 0; i < pSet->m_NumSounds; i++)
 		Sound()->Stop(pSet->m_aSounds[i].m_Id);
 }
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/components/sounds.h alien-rc4/src//game/client/components/sounds.h
--- teeworlds-b177-r50edfd37-source/src//game/client/components/sounds.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/components/sounds.h	2012-06-14 23:57:39.000000000 +0200
@@ -19,6 +19,8 @@ class CSounds : public CComponent
 	int64 m_QueueWaitTime;
 	class CJob m_SoundJob;
 	bool m_WaitForSoundJob;
+	
+	int GetSampleId(int SetId);
 
 public:
 	// sound channels
@@ -37,7 +39,8 @@ public:
 
 	void ClearQueue();
 	void Enqueue(int Channel, int SetId);
-	void Play(int Channel, int SetId, float Vol, vec2 Pos);
+	void Play(int Channel, int SetId, float Vol);
+	void PlayAt(int Channel, int SetId, float Vol, vec2 Pos);
 	void PlayAndRecord(int Channel, int SetId, float Vol, vec2 Pos);
 	void Stop(int SetId);
 };
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/gameclient.cpp alien-rc4/src//game/client/gameclient.cpp
--- teeworlds-b177-r50edfd37-source/src//game/client/gameclient.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/gameclient.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -95,7 +95,6 @@ void CGameClient::OnConsoleInit()
 {
 	m_pEngine = Kernel()->RequestInterface<IEngine>();
 	m_pClient = Kernel()->RequestInterface<IClient>();
-	m_pGraphics = Kernel()->RequestInterface<IGraphics>();
 	m_pTextRender = Kernel()->RequestInterface<ITextRender>();
 	m_pSound = Kernel()->RequestInterface<ISound>();
 	m_pInput = Kernel()->RequestInterface<IInput>();
@@ -126,6 +125,8 @@ void CGameClient::OnConsoleInit()
 	m_pVoting = &::gs_Voting;
 	m_pScoreboard = &::gs_Scoreboard;
 	m_pItems = &::gs_Items;
+	m_pMapLayersBackGround = &::gs_MapLayersBackGround;
+	m_pMapLayersForeGround = &::gs_MapLayersForeGround;
 
 	// make a list of all the systems, make sure to add them in the corrent render order
 	m_All.Add(m_pSkins);
@@ -192,12 +193,10 @@ void CGameClient::OnConsoleInit()
 	Console()->Register("force_vote", "ss?r", CFGFLAG_SERVER, 0, 0, "Force a voting option");
 	Console()->Register("clear_votes", "", CFGFLAG_SERVER, 0, 0, "Clears the voting options");
 	Console()->Register("vote", "r", CFGFLAG_SERVER, 0, 0, "Force a vote to yes/no");
+	Console()->Register("swap_teams", "", CFGFLAG_SERVER, 0, 0, "Swap the current teams");
+	Console()->Register("shuffle_teams", "", CFGFLAG_SERVER, 0, 0, "Shuffle the current teams");
 
 
-	// propagate pointers
-	m_UI.SetGraphics(Graphics(), TextRender());
-	m_RenderTools.m_pGraphics = Graphics();
-	m_RenderTools.m_pUI = UI();
 	for(int i = 0; i < m_All.m_Num; i++)
 		m_All.m_paComponents[i]->m_pClient = this;
 
@@ -221,6 +220,13 @@ void CGameClient::OnConsoleInit()
 
 void CGameClient::OnInit()
 {
+	m_pGraphics = Kernel()->RequestInterface<IGraphics>();
+
+	// propagate pointers
+	m_UI.SetGraphics(Graphics(), TextRender());
+	m_RenderTools.m_pGraphics = Graphics();
+	m_RenderTools.m_pUI = UI();
+	
 	int64 Start = time_get();
 
 	// set the language
@@ -443,7 +449,7 @@ void CGameClient::OnRender()
 	m_NewPredictedTick = false;
 
 	// check if client info has to be resent
-	if(m_LastSendInfo && Client()->State() == IClient::STATE_ONLINE && !m_pMenus->IsActive() && m_LastSendInfo+time_freq()*5 < time_get())
+	if(m_LastSendInfo && Client()->State() == IClient::STATE_ONLINE && m_Snap.m_LocalClientID >= 0 && !m_pMenus->IsActive() && m_LastSendInfo+time_freq()*5 < time_get())
 	{
 		// resend if client info differs
 		if(str_comp(g_Config.m_PlayerName, m_aClients[m_Snap.m_LocalClientID].m_aName) ||
@@ -545,7 +551,7 @@ void CGameClient::OnMessage(int MsgId, C
 			pMsg->m_SoundID == SOUND_CTF_GRAB_PL)
 			g_GameClient.m_pSounds->Enqueue(CSounds::CHN_GLOBAL, pMsg->m_SoundID);
 		else
-			g_GameClient.m_pSounds->Play(CSounds::CHN_GLOBAL, pMsg->m_SoundID, 1.0f, vec2(0,0));
+			g_GameClient.m_pSounds->Play(CSounds::CHN_GLOBAL, pMsg->m_SoundID, 1.0f);
 	}
 }
 
@@ -620,7 +626,7 @@ void CGameClient::ProcessEvents()
 		else if(Item.m_Type == NETEVENTTYPE_SOUNDWORLD)
 		{
 			CNetEvent_SoundWorld *ev = (CNetEvent_SoundWorld *)pData;
-			g_GameClient.m_pSounds->Play(CSounds::CHN_WORLD, ev->m_SoundID, 1.0f, vec2(ev->m_X, ev->m_Y));
+			g_GameClient.m_pSounds->PlayAt(CSounds::CHN_WORLD, ev->m_SoundID, 1.0f, vec2(ev->m_X, ev->m_Y));
 		}
 	}
 }
@@ -862,6 +868,17 @@ void CGameClient::OnNewSnapshot()
 			}
 		}
 	}
+	// sort player infos by team
+	int Teams[3] = { TEAM_RED, TEAM_BLUE, TEAM_SPECTATORS };
+	int Index = 0;
+	for(int Team = 0; Team < 3; ++Team)
+	{
+		for(int i = 0; i < MAX_CLIENTS && Index < MAX_CLIENTS; ++i)
+		{
+			if(m_Snap.m_paPlayerInfos[i] && m_Snap.m_paPlayerInfos[i]->m_Team == Teams[Team])
+				m_Snap.m_paInfoByTeam[Index++] = m_Snap.m_paPlayerInfos[i];
+		}
+	}
 
 	CTuningParams StandardTuning;
 	CServerInfo CurrentServerInfo;
@@ -876,6 +893,15 @@ void CGameClient::OnNewSnapshot()
 			m_ServerMode = SERVERMODE_PUREMOD;
 	}
 
+	// add tuning to demo
+	if(DemoRecorder()->IsRecording() && mem_comp(&StandardTuning, &m_Tuning, sizeof(CTuningParams)) != 0)
+	{
+		CMsgPacker Msg(NETMSGTYPE_SV_TUNEPARAMS);
+		int *pParams = (int *)&m_Tuning;
+		for(unsigned i = 0; i < sizeof(m_Tuning)/sizeof(int); i++)
+			Msg.AddInt(pParams[i]);
+		Client()->SendMsg(&Msg, MSGFLAG_RECORD|MSGFLAG_NOSEND);
+	}
 }
 
 void CGameClient::OnPredict()
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/gameclient.h alien-rc4/src//game/client/gameclient.h
--- teeworlds-b177-r50edfd37-source/src//game/client/gameclient.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/gameclient.h	2012-06-14 23:57:39.000000000 +0200
@@ -125,6 +125,7 @@ public:
 
 		const CNetObj_PlayerInfo *m_paPlayerInfos[MAX_CLIENTS];
 		const CNetObj_PlayerInfo *m_paInfoByScore[MAX_CLIENTS];
+		const CNetObj_PlayerInfo *m_paInfoByTeam[MAX_CLIENTS];
 
 		int m_LocalClientID;
 		int m_NumPlayers;
@@ -241,6 +242,8 @@ public:
 	class CVoting *m_pVoting;
 	class CScoreboard *m_pScoreboard;
 	class CItems *m_pItems;
+	class CMapLayers *m_pMapLayersBackGround;
+	class CMapLayers *m_pMapLayersForeGround;
 };
 
 
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/render.cpp alien-rc4/src//game/client/render.cpp
--- teeworlds-b177-r50edfd37-source/src//game/client/render.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/render.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -75,7 +75,7 @@ void CRenderTools::SelectSprite(CDataSpr
 
 void CRenderTools::SelectSprite(int Id, int Flags, int sx, int sy)
 {
-	if(Id < 0 || Id > g_pData->m_NumSprites)
+	if(Id < 0 || Id >= g_pData->m_NumSprites)
 		return;
 	SelectSprite(&g_pData->m_aSprites[Id], Flags, sx, sy);
 }
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/ui.cpp alien-rc4/src//game/client/ui.cpp
--- teeworlds-b177-r50edfd37-source/src//game/client/ui.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/ui.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -74,6 +74,11 @@ CUIRect *CUI::Screen()
 	return &m_Screen;
 }
 
+float CUI::PixelSize()
+{
+	return Screen()->w/Graphics()->ScreenWidth();
+}
+
 void CUI::SetScale(float s)
 {
 	g_Config.m_UiScale = (int)(s*100.0f);
diff -rupN teeworlds-b177-r50edfd37-source/src//game/client/ui.h alien-rc4/src//game/client/ui.h
--- teeworlds-b177-r50edfd37-source/src//game/client/ui.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/client/ui.h	2012-06-14 23:57:39.000000000 +0200
@@ -82,6 +82,7 @@ public:
 	void ConvertMouseMove(float *x, float *y);
 
 	CUIRect *Screen();
+	float PixelSize();
 	void ClipEnable(const CUIRect *pRect);
 	void ClipDisable();
 
diff -rupN teeworlds-b177-r50edfd37-source/src//game/collision.cpp alien-rc4/src//game/collision.cpp
--- teeworlds-b177-r50edfd37-source/src//game/collision.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/collision.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -45,6 +45,24 @@ void CCollision::Init(class CLayers *pLa
 		case TILE_NOHOOK:
 			m_pTiles[i].m_Index = COLFLAG_SOLID|COLFLAG_NOHOOK;
 			break;
+		case TILE_TURRET:
+			m_pTiles[i].m_Index = COLFLAG_TURRET;
+			break;
+		case TILE_INVIS:
+			m_pTiles[i].m_Index = COLFLAG_INVIS;
+			break;
+		case TILE_BIOHAZARD:
+			m_pTiles[i].m_Index = COLFLAG_BIOHAZARD;
+			break;
+		case TILE_BIOINVIS:
+			m_pTiles[i].m_Index = COLFLAG_BIOINVIS;
+			break;
+		case TILE_ENERGYUP:
+			m_pTiles[i].m_Index = COLFLAG_ENERGYUP;
+			break;
+		case TILE_REAPER:
+			m_pTiles[i].m_Index = COLFLAG_REAPER;
+			break;
 		default:
 			m_pTiles[i].m_Index = 0;
 		}
diff -rupN teeworlds-b177-r50edfd37-source/src//game/collision.h alien-rc4/src//game/collision.h
--- teeworlds-b177-r50edfd37-source/src//game/collision.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/collision.h	2012-06-14 23:57:39.000000000 +0200
@@ -21,6 +21,12 @@ public:
 		COLFLAG_SOLID=1,
 		COLFLAG_DEATH=2,
 		COLFLAG_NOHOOK=4,
+		COLFLAG_TURRET=8,
+		COLFLAG_INVIS=16,
+		COLFLAG_BIOHAZARD=32,
+		COLFLAG_BIOINVIS=48,
+		COLFLAG_ENERGYUP=64,
+		COLFLAG_REAPER=128,
 	};
 
 	CCollision();
diff -rupN teeworlds-b177-r50edfd37-source/src//game/editor/auto_map.cpp alien-rc4/src//game/editor/auto_map.cpp
--- teeworlds-b177-r50edfd37-source/src//game/editor/auto_map.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/editor/auto_map.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -20,15 +20,15 @@ void CAutoMapper::Load(const char* pTile
 	IOHANDLE RulesFile = m_pEditor->Storage()->OpenFile(aPath, IOFLAG_READ, IStorage::TYPE_ALL);
 	if(!RulesFile)
 		return;
-	
+
 	CLineReader LineReader;
 	LineReader.Init(RulesFile);
-		
+
 	CConfiguration *pCurrentConf = 0;
 	CIndexRule *pCurrentIndex = 0;
-		
+
 	char aBuf[256];
-		
+
 	// read each line
 	while(char *pLine = LineReader.Get())
 	{
@@ -40,11 +40,11 @@ void CAutoMapper::Load(const char* pTile
 			{
 				// new configuration, get the name
 				pLine++;
-					
+
 				CConfiguration NewConf;
 				int ID = m_lConfigs.add(NewConf);
 				pCurrentConf = &m_lConfigs[ID];
-					
+
 				str_copy(pCurrentConf->m_aName, pLine, str_length(pLine));
 			}
 			else
@@ -54,15 +54,15 @@ void CAutoMapper::Load(const char* pTile
 					// new index
 					int ID = 0;
 					char aFlip[128] = "";
-						
+
 					sscanf(pLine, "Index %d %127s", &ID, aFlip);
-						
+
 					CIndexRule NewIndexRule;
 					NewIndexRule.m_ID = ID;
 					NewIndexRule.m_Flag = 0;
 					NewIndexRule.m_RandomValue = 0;
 					NewIndexRule.m_BaseTile = false;
-						
+
 					if(str_length(aFlip) > 0)
 					{
 						if(!str_comp(aFlip, "XFLIP"))
@@ -70,7 +70,7 @@ void CAutoMapper::Load(const char* pTile
 						else if(!str_comp(aFlip, "YFLIP"))
 							NewIndexRule.m_Flag = TILEFLAG_HFLIP;
 					}
-						
+
 					// add the index rule object and make it current
 					int ArrayID = pCurrentConf->m_aIndexRules.add(NewIndexRule);
 					pCurrentIndex = &pCurrentConf->m_aIndexRules[ArrayID];
@@ -85,9 +85,9 @@ void CAutoMapper::Load(const char* pTile
 					char aValue[128];
 					int Value = CPosRule::EMPTY;
 					bool IndexValue = false;
-						
+
 					sscanf(pLine, "Pos %d %d %127s", &x, &y, aValue);
-						
+
 					if(!str_comp(aValue, "FULL"))
 						Value = CPosRule::FULL;
 					else if(!str_comp_num(aValue, "INDEX", 5))
@@ -106,12 +106,12 @@ void CAutoMapper::Load(const char* pTile
 			}
 		}
 	}
-		
+
 	io_close(RulesFile);
-		
+
 	str_format(aBuf, sizeof(aBuf),"loaded %s", aPath);
 	m_pEditor->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "editor", aBuf);
-		
+
 	m_FileLoaded = true;
 }
 
@@ -127,14 +127,14 @@ void CAutoMapper::Proceed(CLayerTiles *p
 {
 	if(!m_FileLoaded || pLayer->m_Readonly || ConfigID < 0 || ConfigID >= m_lConfigs.size())
 		return;
-	
+
 	CConfiguration *pConf = &m_lConfigs[ConfigID];
-	
+
 	if(!pConf->m_aIndexRules.size())
 		return;
-	
+
 	int BaseTile = 1;
-	
+
 	// find base tile if there is one
 	for(int i = 0; i < pConf->m_aIndexRules.size(); ++i)
 	{
@@ -144,7 +144,7 @@ void CAutoMapper::Proceed(CLayerTiles *p
 			break;
 		}
 	}
-	
+
 	// auto map !
 	int MaxIndex = pLayer->m_Width*pLayer->m_Height;
 	for(int y = 0; y < pLayer->m_Height; y++)
@@ -159,7 +159,7 @@ void CAutoMapper::Proceed(CLayerTiles *p
 
 			if(y == 0 || y == pLayer->m_Height-1 || x == 0 || x == pLayer->m_Width-1)
 				continue;
-				
+
 			for(int i = 0; i < pConf->m_aIndexRules.size(); ++i)
 			{
 				if(pConf->m_aIndexRules[i].m_BaseTile)
@@ -170,7 +170,7 @@ void CAutoMapper::Proceed(CLayerTiles *p
 				{
 					CPosRule *pRule = &pConf->m_aIndexRules[i].m_aRules[j];
 					int CheckIndex = (y+pRule->m_Y)*pLayer->m_Width+(x+pRule->m_X);
-							
+
 					if(CheckIndex < 0 || CheckIndex >= MaxIndex)
 						RespectRules = false;
 					else
@@ -184,15 +184,15 @@ void CAutoMapper::Proceed(CLayerTiles *p
 						{
 							if(pLayer->m_pTiles[CheckIndex].m_Index > 0 && pRule->m_Value == CPosRule::EMPTY)
 								RespectRules = false;
-									
+
 							if(pLayer->m_pTiles[CheckIndex].m_Index == 0 && pRule->m_Value == CPosRule::FULL)
 								RespectRules = false;
 						}
 					}
 				}
-					
+
 				if(RespectRules &&
-					(pConf->m_aIndexRules[i].m_RandomValue <= 1 || (int)((float)rand() / ((float)RAND_MAX + 1) * pConf->m_aIndexRules[i].m_RandomValue)  == 1))
+					(pConf->m_aIndexRules[i].m_RandomValue <= 1 || (int)((float)rand() / ((float)RAND_MAX + 1) * pConf->m_aIndexRules[i].m_RandomValue) == 1))
 				{
 					pTile->m_Index = pConf->m_aIndexRules[i].m_ID;
 					pTile->m_Flags = pConf->m_aIndexRules[i].m_Flag;
diff -rupN teeworlds-b177-r50edfd37-source/src//game/editor/auto_map.h alien-rc4/src//game/editor/auto_map.h
--- teeworlds-b177-r50edfd37-source/src//game/editor/auto_map.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/editor/auto_map.h	2012-06-14 23:57:39.000000000 +0200
@@ -11,7 +11,7 @@ class CAutoMapper
 		int m_Y;
 		int m_Value;
 		bool m_IndexValue;
-		
+
 		enum
 		{
 			EMPTY=0,
@@ -33,16 +33,16 @@ class CAutoMapper
 		array<CIndexRule> m_aIndexRules;
 		char m_aName[128];
 	};
-	
+
 public:
 	CAutoMapper(class CEditor *pEditor);
-	
+
 	void Load(const char* pTileName);
 	void Proceed(class CLayerTiles *pLayer, int ConfigID);
 
 	int ConfigNamesNum() { return m_lConfigs.size(); }
 	const char* GetConfigName(int Index);
-	
+
 	const bool IsLoaded() { return m_FileLoaded; }
 private:
 	array<CConfiguration> m_lConfigs;
diff -rupN teeworlds-b177-r50edfd37-source/src//game/editor/editor.cpp alien-rc4/src//game/editor/editor.cpp
--- teeworlds-b177-r50edfd37-source/src//game/editor/editor.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/editor/editor.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -164,7 +164,7 @@ void CEditorImage::AnalyseTileFlags()
 	int tw = m_Width/16; // tilesizes
 	int th = m_Height/16;
 	if ( tw == th )
-    {
+	{
 		unsigned char *pPixelData = (unsigned char *)m_pData;
 
 		int TileID = 0;
@@ -214,7 +214,6 @@ void CEditor::EnvelopeEval(float TimeOff
 
 // copied from gc_menu.cpp, should be more generalized
 //extern int ui_do_edit_box(void *id, const CUIRect *rect, char *str, int str_size, float font_size, bool hidden=false);
-
 int CEditor::DoEditBox(void *pID, const CUIRect *pRect, char *pStr, unsigned StrSize, float FontSize, float *Offset, bool Hidden, int Corners)
 {
 	int Inside = UI()->MouseInside(pRect);
@@ -228,6 +227,7 @@ int CEditor::DoEditBox(void *pID, const
 
 	if(UI()->LastActiveItem() == pID)
 	{
+		m_EditBoxActive = 2;
 		int Len = str_length(pStr);
 		if(Len == 0)
 			s_AtIndex = 0;
@@ -381,8 +381,8 @@ float CEditor::UiDoScrollbarV(const void
 	Handle.y += (pRect->h-Handle.h)*Current;
 
 	// logic
-    float Ret = Current;
-    int Inside = UI()->MouseInside(&Handle);
+	float Ret = Current;
+	int Inside = UI()->MouseInside(&Handle);
 
 	if(UI()->ActiveItem() == pID)
 	{
@@ -423,7 +423,7 @@ float CEditor::UiDoScrollbarV(const void
 	Slider.Margin(5.0f, &Slider);
 	RenderTools()->DrawUIRect(&Slider, vec4(1,1,1,0.25f)*ButtonColorMul(pID), CUI::CORNER_ALL, 2.5f);
 
-    return Ret;
+	return Ret;
 }
 
 vec4 CEditor::GetButtonColor(const void *pID, int Checked)
@@ -490,7 +490,7 @@ int CEditor::DoButton_File(const void *p
 int CEditor::DoButton_Menu(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip)
 {
 	CUIRect r = *pRect;
-    RenderTools()->DrawUIRect(&r, vec4(0.5f, 0.5f, 0.5f, 1.0f), CUI::CORNER_T, 3.0f);
+	RenderTools()->DrawUIRect(&r, vec4(0.5f, 0.5f, 0.5f, 1.0f), CUI::CORNER_T, 3.0f);
 
 	r = *pRect;
 	r.VMargin(5.0f, &r);
@@ -515,18 +515,18 @@ int CEditor::DoButton_MenuItem(const voi
 int CEditor::DoButton_Tab(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip)
 {
 	RenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), CUI::CORNER_T, 5.0f);
-    CUIRect NewRect = *pRect;
-    NewRect.y += NewRect.h/2.0f-7.0f;
-    UI()->DoLabel(&NewRect, pText, 10, 0, -1);
+	CUIRect NewRect = *pRect;
+	NewRect.y += NewRect.h/2.0f-7.0f;
+	UI()->DoLabel(&NewRect, pText, 10, 0, -1);
 	return DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip);
 }
 
 int CEditor::DoButton_Ex(const void *pID, const char *pText, int Checked, const CUIRect *pRect, int Flags, const char *pToolTip, int Corners, float FontSize)
 {
 	RenderTools()->DrawUIRect(pRect, GetButtonColor(pID, Checked), Corners, 3.0f);
-    CUIRect NewRect = *pRect;
-    NewRect.HMargin(NewRect.h/2.0f-FontSize/2.0f-1.0f, &NewRect);
-    UI()->DoLabel(&NewRect, pText, FontSize, 0, -1);
+	CUIRect NewRect = *pRect;
+	NewRect.HMargin(NewRect.h/2.0f-FontSize/2.0f-1.0f, &NewRect);
+	UI()->DoLabel(&NewRect, pText, FontSize, 0, -1);
 	return DoButton_Editor_Common(pID, pText, Checked, pRect, Flags, pToolTip);
 }
 
@@ -550,7 +550,7 @@ void CEditor::RenderGrid(CLayerGroup *pG
 		return;
 
 	float aGroupPoints[4];
-	pGroup->Mapping(aGroupPoints); 
+	pGroup->Mapping(aGroupPoints);
 
 	float w = UI()->Screen()->w;
 	float h = UI()->Screen()->h;
@@ -562,7 +562,7 @@ void CEditor::RenderGrid(CLayerGroup *pG
 	int XGridOffset = XOffset % m_GridFactor;
 	int YGridOffset = YOffset % m_GridFactor;
 
-	Graphics()->TextureSet(-1);	
+	Graphics()->TextureSet(-1);
 	Graphics()->LinesBegin();
 
 	for(int i = 0; i < (int)w; i++)
@@ -601,9 +601,9 @@ void CEditor::RenderBackground(CUIRect V
 
 int CEditor::UiDoValueSelector(void *pID, CUIRect *pRect, const char *pLabel, int Current, int Min, int Max, int Step, float Scale, const char *pToolTip)
 {
-    // logic
-    static float s_Value;
-    int Inside = UI()->MouseInside(pRect);
+	// logic
+	static float s_Value;
+	int Inside = UI()->MouseInside(pRect);
 
 	if(UI()->ActiveItem() == pID)
 	{
@@ -652,9 +652,9 @@ int CEditor::UiDoValueSelector(void *pID
 	char aBuf[128];
 	str_format(aBuf, sizeof(aBuf),"%s %d", pLabel, Current);
 	RenderTools()->DrawUIRect(pRect, GetButtonColor(pID, 0), CUI::CORNER_ALL, 5.0f);
-    pRect->y += pRect->h/2.0f-7.0f;
-    UI()->DoLabel(pRect, aBuf, 10, 0, -1);
-    
+	pRect->y += pRect->h/2.0f-7.0f;
+	UI()->DoLabel(pRect, aBuf, 10, 0, -1);
+
 	return Current;
 }
 
@@ -713,7 +713,7 @@ void CEditor::CallbackAppendMap(const ch
 		pEditor->m_aFileName[0] = 0;
 	else
 		pEditor->SortImages();
-	
+
 	pEditor->m_Dialog = DIALOG_NONE;
 }
 void CEditor::CallbackSaveMap(const char *pFileName, int StorageType, void *pUser)
@@ -734,7 +734,7 @@ void CEditor::CallbackSaveMap(const char
 		pEditor->m_ValidSaveFilename = StorageType == IStorage::TYPE_SAVE && pEditor->m_pFileDialogPath == pEditor->m_aFileDialogCurrentFolder;
 		pEditor->m_Map.m_Modified = false;
 	}
-	
+
 	pEditor->m_Dialog = DIALOG_NONE;
 }
 
@@ -742,32 +742,38 @@ void CEditor::DoToolbar(CUIRect ToolBar)
 {
 	CUIRect TB_Top, TB_Bottom;
 	CUIRect Button;
-	
+
 	ToolBar.HSplitTop(ToolBar.h/2.0f, &TB_Top, &TB_Bottom);
-	
-    TB_Top.HSplitBottom(2.5f, &TB_Top, 0);
-    TB_Bottom.HSplitTop(2.5f, 0, &TB_Bottom);
+
+	TB_Top.HSplitBottom(2.5f, &TB_Top, 0);
+	TB_Bottom.HSplitTop(2.5f, 0, &TB_Bottom);
 
 	// ctrl+o to open
-	if(Input()->KeyDown('o') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)))
+	if(Input()->KeyDown('o') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)) && m_Dialog == DIALOG_NONE)
 	{
 		if(HasUnsavedData())
 		{
-			m_PopupEventType = POPEVENT_LOAD;
-			m_PopupEventActivated = true;
+			if(!m_PopupEventWasActivated)
+			{
+				m_PopupEventType = POPEVENT_LOAD;
+				m_PopupEventActivated = true;
+			}
 		}
 		else
 			InvokeFileDialog(IStorage::TYPE_ALL, FILETYPE_MAP, "Load map", "Load", "maps", "", CallbackOpenMap, this);
 	}
 
 	// ctrl+s to save
-	if(Input()->KeyDown('s') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)))
+	if(Input()->KeyDown('s') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL)) && m_Dialog == DIALOG_NONE)
 	{
-		if(m_aFileName[0] && m_ValidSaveFilename)	
+		if(m_aFileName[0] && m_ValidSaveFilename)
 		{
-			str_copy(m_aFileSaveName, m_aFileName, sizeof(m_aFileSaveName));
-			m_PopupEventType = POPEVENT_SAVE;
-			m_PopupEventActivated = true;
+			if(!m_PopupEventWasActivated)
+			{
+				str_copy(m_aFileSaveName, m_aFileName, sizeof(m_aFileSaveName));
+				m_PopupEventType = POPEVENT_SAVE;
+				m_PopupEventActivated = true;
+			}
 		}
 		else
 			InvokeFileDialog(IStorage::TYPE_SAVE, FILETYPE_MAP, "Save map", "Save", "maps", "", CallbackSaveMap, this);
@@ -814,6 +820,7 @@ void CEditor::DoToolbar(CUIRect ToolBar)
 		(Input()->KeyDown('i') && (Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL))))
 	{
 		m_ShowTileInfo = !m_ShowTileInfo;
+		m_ShowEnvelopePreview = 0;
 	}
 
 	TB_Top.VSplitLeft(15.0f, 0, &TB_Top);
@@ -821,12 +828,12 @@ void CEditor::DoToolbar(CUIRect ToolBar)
 	// zoom group
 	TB_Top.VSplitLeft(30.0f, &Button, &TB_Top);
 	static int s_ZoomOutButton = 0;
-	if(DoButton_Ex(&s_ZoomOutButton, "ZO", 0, &Button, 0, "[NumPad-] Zoom out", CUI::CORNER_L) || Input()->KeyDown(KEY_KP_MINUS))
+	if(DoButton_Ex(&s_ZoomOutButton, "ZO", 0, &Button, 0, "[NumPad-] Zoom out", CUI::CORNER_L))
 		m_ZoomLevel += 50;
 
 	TB_Top.VSplitLeft(30.0f, &Button, &TB_Top);
 	static int s_ZoomNormalButton = 0;
-	if(DoButton_Ex(&s_ZoomNormalButton, "1:1", 0, &Button, 0, "[NumPad*] Zoom to normal and remove editor offset", 0) || Input()->KeyDown(KEY_KP_MULTIPLY))
+	if(DoButton_Ex(&s_ZoomNormalButton, "1:1", 0, &Button, 0, "[NumPad*] Zoom to normal and remove editor offset", 0))
 	{
 		m_EditorOffsetX = 0;
 		m_EditorOffsetY = 0;
@@ -835,7 +842,7 @@ void CEditor::DoToolbar(CUIRect ToolBar)
 
 	TB_Top.VSplitLeft(30.0f, &Button, &TB_Top);
 	static int s_ZoomInButton = 0;
-	if(DoButton_Ex(&s_ZoomInButton, "ZI", 0, &Button, 0, "[NumPad+] Zoom in", CUI::CORNER_R) || Input()->KeyDown(KEY_KP_PLUS))
+	if(DoButton_Ex(&s_ZoomInButton, "ZI", 0, &Button, 0, "[NumPad+] Zoom in", CUI::CORNER_R))
 		m_ZoomLevel -= 50;
 
 	TB_Top.VSplitLeft(10.0f, 0, &TB_Top);
@@ -859,8 +866,6 @@ void CEditor::DoToolbar(CUIRect ToolBar)
 			m_AnimateSpeed -= 0.5f;
 	}
 
-	m_WorldZoom = m_ZoomLevel/100.0f;
-
 	TB_Top.VSplitLeft(10.0f, &Button, &TB_Top);
 
 
@@ -947,17 +952,17 @@ void CEditor::DoToolbar(CUIRect ToolBar)
 			}
 		}
 	}
-    
+
 	// tile manipulation
 	{
 		TB_Bottom.VSplitLeft(40.0f, &Button, &TB_Bottom);
 		static int s_BorderBut = 0;
 		CLayerTiles *pT = (CLayerTiles *)GetSelectedLayerType(0, LAYERTYPE_TILES);
-		
+
 		if(DoButton_Editor(&s_BorderBut, "Border", pT?0:-1, &Button, 0, "Adds border tiles"))
 		{
 			if(pT)
-                DoMapBorder();
+				DoMapBorder();
 		}
 	}
 
@@ -966,7 +971,7 @@ void CEditor::DoToolbar(CUIRect ToolBar)
 	// refocus button
 	TB_Bottom.VSplitLeft(50.0f, &Button, &TB_Bottom);
 	static int s_RefocusButton = 0;
-	if(DoButton_Editor(&s_RefocusButton, "Refocus", m_WorldOffsetX&&m_WorldOffsetY?0:-1, &Button, 0, "[HOME] Restore map focus") || Input()->KeyDown(KEY_HOME))
+	if(DoButton_Editor(&s_RefocusButton, "Refocus", m_WorldOffsetX&&m_WorldOffsetY?0:-1, &Button, 0, "[HOME] Restore map focus") || (m_EditBoxActive == 0 && Input()->KeyDown(KEY_HOME)))
 	{
 		m_WorldOffsetX = 0;
 		m_WorldOffsetY = 0;
@@ -1046,6 +1051,12 @@ void CEditor::DoQuad(CQuad *q, int Index
 	if(dx*dx+dy*dy < 50)
 		UI()->SetHotItem(pID);
 
+	bool IgnoreGrid;
+	if(Input()->KeyPressed(KEY_LALT) || Input()->KeyPressed(KEY_RALT))
+		IgnoreGrid = true;
+	else
+		IgnoreGrid = false;
+
 	// draw selection background
 	if(m_SelectedQuad == Index)
 	{
@@ -1056,58 +1067,82 @@ void CEditor::DoQuad(CQuad *q, int Index
 
 	if(UI()->ActiveItem() == pID)
 	{
-		// check if we only should move pivot
-		if(s_Operation == OP_MOVE_PIVOT)
+		if(m_MouseDeltaWx*m_MouseDeltaWx+m_MouseDeltaWy*m_MouseDeltaWy > 0.5f)
 		{
-			q->m_aPoints[4].x += f2fx(wx-s_LastWx);
-			q->m_aPoints[4].y += f2fx(wy-s_LastWy);
-		}
-		else if(s_Operation == OP_MOVE_ALL)
-		{
-			// move all points including pivot
-			if(m_GridActive)
+			// check if we only should move pivot
+			if(s_Operation == OP_MOVE_PIVOT)
 			{
-				int LineDistance = GetLineDistance();
+				if(m_GridActive && !IgnoreGrid)
+				{
+					int LineDistance = GetLineDistance();
 
-				float x = 0.0f;
-				float y = 0.0f;
-				if(wx >= 0)
-					x = (int)((wx+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);
-				else
-					x = (int)((wx-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);
-				if(wy >= 0)
-					y = (int)((wy+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);
+					float x = 0.0f;
+					float y = 0.0f;
+					if(wx >= 0)
+						x = (int)((wx+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);
+					else
+						x = (int)((wx-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);
+					if(wy >= 0)
+						y = (int)((wy+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);
+					else
+						y = (int)((wy-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);
+
+					q->m_aPoints[4].x = f2fx(x);
+					q->m_aPoints[4].y = f2fx(y);
+				}
 				else
-					y = (int)((wy-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);
-				
-				int OldX = q->m_aPoints[4].x;
-				int OldY = q->m_aPoints[4].y;
-				q->m_aPoints[4].x = f2fx(x);
-				q->m_aPoints[4].y = f2fx(y);
-				int DiffX = q->m_aPoints[4].x - OldX;
-				int DiffY = q->m_aPoints[4].y - OldY;
-				
-				for(int v = 0; v < 4; v++)
 				{
-					q->m_aPoints[v].x += DiffX;
-					q->m_aPoints[v].y += DiffY;
+					q->m_aPoints[4].x += f2fx(wx-s_LastWx);
+					q->m_aPoints[4].y += f2fx(wy-s_LastWy);
 				}
 			}
-			else
+			else if(s_Operation == OP_MOVE_ALL)
 			{
-				for(int v = 0; v < 5; v++)
+				// move all points including pivot
+				if(m_GridActive && !IgnoreGrid)
 				{
-						q->m_aPoints[v].x += f2fx(wx-s_LastWx);
-						q->m_aPoints[v].y += f2fx(wy-s_LastWy);
+					int LineDistance = GetLineDistance();
+
+					float x = 0.0f;
+					float y = 0.0f;
+					if(wx >= 0)
+						x = (int)((wx+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);
+					else
+						x = (int)((wx-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);
+					if(wy >= 0)
+						y = (int)((wy+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);
+					else
+						y = (int)((wy-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);
+
+					int OldX = q->m_aPoints[4].x;
+					int OldY = q->m_aPoints[4].y;
+					q->m_aPoints[4].x = f2fx(x);
+					q->m_aPoints[4].y = f2fx(y);
+					int DiffX = q->m_aPoints[4].x - OldX;
+					int DiffY = q->m_aPoints[4].y - OldY;
+
+					for(int v = 0; v < 4; v++)
+					{
+						q->m_aPoints[v].x += DiffX;
+						q->m_aPoints[v].y += DiffY;
+					}
+				}
+				else
+				{
+					for(int v = 0; v < 5; v++)
+					{
+							q->m_aPoints[v].x += f2fx(wx-s_LastWx);
+							q->m_aPoints[v].y += f2fx(wy-s_LastWy);
+					}
 				}
 			}
-		}
-		else if(s_Operation == OP_ROTATE)
-		{
-			for(int v = 0; v < 4; v++)
+			else if(s_Operation == OP_ROTATE)
 			{
-				q->m_aPoints[v] = s_RotatePoints[v];
-				Rotate(&q->m_aPoints[4], &q->m_aPoints[v], s_RotateAngle);
+				for(int v = 0; v < 4; v++)
+				{
+					q->m_aPoints[v] = s_RotatePoints[v];
+					Rotate(&q->m_aPoints[4], &q->m_aPoints[v], s_RotateAngle);
+				}
 			}
 		}
 
@@ -1143,7 +1178,7 @@ void CEditor::DoQuad(CQuad *q, int Index
 		ms_pUiGotContext = pID;
 
 		Graphics()->SetColor(1,1,1,1);
-		m_pTooltip = "Left mouse button to move. Hold shift to move pivot. Hold ctrl to rotate.";
+		m_pTooltip = "Left mouse button to move. Hold shift to move pivot. Hold ctrl to rotate. Hold alt to ignore grid.";
 
 		if(UI()->MouseButton(0))
 		{
@@ -1163,6 +1198,8 @@ void CEditor::DoQuad(CQuad *q, int Index
 				s_Operation = OP_MOVE_ALL;
 
 			UI()->SetActiveItem(pID);
+			if(m_SelectedQuad != Index)
+				m_SelectedPoints = 0;
 			m_SelectedQuad = Index;
 			s_LastWx = wx;
 			s_LastWy = wy;
@@ -1170,6 +1207,8 @@ void CEditor::DoQuad(CQuad *q, int Index
 
 		if(UI()->MouseButton(1))
 		{
+			if(m_SelectedQuad != Index)
+				m_SelectedPoints = 0;
 			m_SelectedQuad = Index;
 			s_Operation = OP_CONTEXT_MENU;
 			UI()->SetActiveItem(pID);
@@ -1216,6 +1255,12 @@ void CEditor::DoQuadPoint(CQuad *pQuad,
 	static bool s_Moved;
 	static int s_Operation = OP_NONE;
 
+	bool IgnoreGrid;
+	if(Input()->KeyPressed(KEY_LALT) || Input()->KeyPressed(KEY_RALT))
+		IgnoreGrid = true;
+	else
+		IgnoreGrid = false;
+
 	if(UI()->ActiveItem() == pID)
 	{
 		float dx = m_MouseDeltaWx;
@@ -1230,7 +1275,7 @@ void CEditor::DoQuadPoint(CQuad *pQuad,
 		{
 			if(s_Operation == OP_MOVEPOINT)
 			{
-				if(m_GridActive)
+				if(m_GridActive && !IgnoreGrid)
 				{
 					for(int m = 0; m < 4; m++)
 						if(m_SelectedPoints&(1<<m))
@@ -1267,12 +1312,12 @@ void CEditor::DoQuadPoint(CQuad *pQuad,
 				for(int m = 0; m < 4; m++)
 					if(m_SelectedPoints&(1<<m))
 					{
-						// 0,2;1,3 - line x 
+						// 0,2;1,3 - line x
 						// 0,1;2,3 - line y
 
 						pQuad->m_aTexcoords[m].x += f2fx(dx*0.001f);
 						pQuad->m_aTexcoords[(m+2)%4].x += f2fx(dx*0.001f);
-						
+
 						pQuad->m_aTexcoords[m].y += f2fx(dy*0.001f);
 						pQuad->m_aTexcoords[m^1].y += f2fx(dy*0.001f);
 					}
@@ -1311,7 +1356,7 @@ void CEditor::DoQuadPoint(CQuad *pQuad,
 		ms_pUiGotContext = pID;
 
 		Graphics()->SetColor(1,1,1,1);
-		m_pTooltip = "Left mouse button to move. Hold shift to move the texture.";
+		m_pTooltip = "Left mouse button to move. Hold shift to move the texture. Hold alt to ignore grid.";
 
 		if(UI()->MouseButton(0))
 		{
@@ -1358,6 +1403,218 @@ void CEditor::DoQuadPoint(CQuad *pQuad,
 	Graphics()->QuadsDraw(&QuadItem, 1);
 }
 
+void CEditor::DoQuadEnvelopes(CQuad *pQuad, int Index, int TexID)
+{
+	CEnvelope *pEnvelope = 0x0;
+	if(pQuad->m_PosEnv >= 0 && pQuad->m_PosEnv < m_Map.m_lEnvelopes.size())
+		pEnvelope = m_Map.m_lEnvelopes[pQuad->m_PosEnv];
+	if (!pEnvelope)
+		return;
+
+	//QuadParams
+	CPoint *pPoints = pQuad->m_aPoints;
+
+	//Draw Lines
+	Graphics()->TextureSet(-1);
+	Graphics()->LinesBegin();
+		Graphics()->SetColor(80.0f/255, 150.0f/255, 230.f/255, 0.5f);
+		for(int i = 0; i < pEnvelope->m_lPoints.size()-1; i++)
+		{
+			float OffsetX =  fx2f(pEnvelope->m_lPoints[i].m_aValues[0]);
+			float OffsetY = fx2f(pEnvelope->m_lPoints[i].m_aValues[1]);
+			vec2 Pos0 = vec2(fx2f(pPoints[4].x)+OffsetX, fx2f(pPoints[4].y)+OffsetY);
+
+			OffsetX = fx2f(pEnvelope->m_lPoints[i+1].m_aValues[0]);
+			OffsetY = fx2f(pEnvelope->m_lPoints[i+1].m_aValues[1]);
+			vec2 Pos1 = vec2(fx2f(pPoints[4].x)+OffsetX, fx2f(pPoints[4].y)+OffsetY);
+
+			IGraphics::CLineItem Line = IGraphics::CLineItem(Pos0.x, Pos0.y, Pos1.x, Pos1.y);
+			Graphics()->LinesDraw(&Line, 1);
+		}
+		Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);
+	Graphics()->LinesEnd();
+
+	//Draw Quads
+	for(int i = 0; i < pEnvelope->m_lPoints.size(); i++)
+	{
+		Graphics()->TextureSet(TexID);
+		Graphics()->QuadsBegin();
+		
+		//Calc Env Position
+		float OffsetX =  fx2f(pEnvelope->m_lPoints[i].m_aValues[0]);
+		float OffsetY = fx2f(pEnvelope->m_lPoints[i].m_aValues[1]);
+		float Rot = fx2f(pEnvelope->m_lPoints[i].m_aValues[2])/360.0f*pi*2;
+
+		//Set Colours
+		float Alpha = (m_SelectedQuadEnvelope == pQuad->m_PosEnv && m_SelectedEnvelopePoint == i) ? 0.65f : 0.35f;
+		IGraphics::CColorVertex aArray[4] = {
+			IGraphics::CColorVertex(0, pQuad->m_aColors[0].r, pQuad->m_aColors[0].g, pQuad->m_aColors[0].b, Alpha),
+			IGraphics::CColorVertex(1, pQuad->m_aColors[1].r, pQuad->m_aColors[1].g, pQuad->m_aColors[1].b, Alpha),
+			IGraphics::CColorVertex(2, pQuad->m_aColors[2].r, pQuad->m_aColors[2].g, pQuad->m_aColors[2].b, Alpha),
+			IGraphics::CColorVertex(3, pQuad->m_aColors[3].r, pQuad->m_aColors[3].g, pQuad->m_aColors[3].b, Alpha)};
+		Graphics()->SetColorVertex(aArray, 4);
+
+		//Rotation
+		if(Rot != 0)
+		{
+			static CPoint aRotated[4];
+			aRotated[0] = pQuad->m_aPoints[0];
+			aRotated[1] = pQuad->m_aPoints[1];
+			aRotated[2] = pQuad->m_aPoints[2];
+			aRotated[3] = pQuad->m_aPoints[3];
+			pPoints = aRotated;
+
+			Rotate(&pQuad->m_aPoints[4], &aRotated[0], Rot);
+			Rotate(&pQuad->m_aPoints[4], &aRotated[1], Rot);
+			Rotate(&pQuad->m_aPoints[4], &aRotated[2], Rot);
+			Rotate(&pQuad->m_aPoints[4], &aRotated[3], Rot);
+		}
+
+		//Set Texture Coords
+		Graphics()->QuadsSetSubsetFree(
+			fx2f(pQuad->m_aTexcoords[0].x), fx2f(pQuad->m_aTexcoords[0].y),
+			fx2f(pQuad->m_aTexcoords[1].x), fx2f(pQuad->m_aTexcoords[1].y),
+			fx2f(pQuad->m_aTexcoords[2].x), fx2f(pQuad->m_aTexcoords[2].y),
+			fx2f(pQuad->m_aTexcoords[3].x), fx2f(pQuad->m_aTexcoords[3].y)
+		);
+
+		//Set Quad Coords & Draw
+		IGraphics::CFreeformItem Freeform(
+			fx2f(pPoints[0].x)+OffsetX, fx2f(pPoints[0].y)+OffsetY,
+			fx2f(pPoints[1].x)+OffsetX, fx2f(pPoints[1].y)+OffsetY,
+			fx2f(pPoints[2].x)+OffsetX, fx2f(pPoints[2].y)+OffsetY,
+			fx2f(pPoints[3].x)+OffsetX, fx2f(pPoints[3].y)+OffsetY);
+		Graphics()->QuadsDrawFreeform(&Freeform, 1);
+
+		Graphics()->QuadsEnd();
+		
+		Graphics()->TextureSet(-1);
+		Graphics()->QuadsBegin();
+		DoQuadEnvPoint(pQuad, Index, i);
+		Graphics()->QuadsEnd();
+	}
+}
+
+void CEditor::DoQuadEnvPoint(CQuad *pQuad, int QIndex, int PIndex)
+{
+	enum
+	{
+		OP_NONE=0,
+		OP_MOVE,
+		OP_ROTATE,
+	};
+
+	// some basic values
+	static float s_LastWx;
+	static float s_LastWy;
+	static int s_Operation = OP_NONE;
+	float wx = UI()->MouseWorldX();
+	float wy = UI()->MouseWorldY();
+	CEnvelope *pEnvelope = m_Map.m_lEnvelopes[pQuad->m_PosEnv];
+	void *pID = &pEnvelope->m_lPoints[PIndex];
+	static int s_ActQIndex = -1;
+
+	// get pivot
+	float CenterX = fx2f(pQuad->m_aPoints[4].x)+fx2f(pEnvelope->m_lPoints[PIndex].m_aValues[0]);
+	float CenterY = fx2f(pQuad->m_aPoints[4].y)+fx2f(pEnvelope->m_lPoints[PIndex].m_aValues[1]);
+
+	float dx = (CenterX - wx)/m_WorldZoom;
+	float dy = (CenterY - wy)/m_WorldZoom;
+	if(dx*dx+dy*dy < 50.0f && UI()->ActiveItem() == 0)
+	{
+		UI()->SetHotItem(pID);
+		s_ActQIndex = QIndex;
+	}
+
+	bool IgnoreGrid;
+	if(Input()->KeyPressed(KEY_LALT) || Input()->KeyPressed(KEY_RALT))
+		IgnoreGrid = true;
+	else
+		IgnoreGrid = false;
+
+	if(UI()->ActiveItem() == pID && s_ActQIndex == QIndex)
+	{
+		if(s_Operation == OP_MOVE)
+		{
+			if(m_GridActive && !IgnoreGrid)
+			{
+				int LineDistance = GetLineDistance();
+
+				float x = 0.0f;
+				float y = 0.0f;
+				if(wx >= 0)
+					x = (int)((wx+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);
+				else
+					x = (int)((wx-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);
+				if(wy >= 0)
+					y = (int)((wy+(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);
+				else
+					y = (int)((wy-(LineDistance/2)*m_GridFactor)/(LineDistance*m_GridFactor)) * (LineDistance*m_GridFactor);
+
+				pEnvelope->m_lPoints[PIndex].m_aValues[0] = f2fx(x);
+				pEnvelope->m_lPoints[PIndex].m_aValues[1] = f2fx(y);
+			}
+			else
+			{
+				pEnvelope->m_lPoints[PIndex].m_aValues[0] += f2fx(wx-s_LastWx);
+				pEnvelope->m_lPoints[PIndex].m_aValues[1] += f2fx(wy-s_LastWy);
+			}
+		}
+		else if(s_Operation == OP_ROTATE)
+			pEnvelope->m_lPoints[PIndex].m_aValues[2] += 10*m_MouseDeltaX;
+
+		s_LastWx = wx;
+		s_LastWy = wy;
+
+		if(!UI()->MouseButton(0))
+		{
+			m_LockMouse = false;
+			s_Operation = OP_NONE;
+			UI()->SetActiveItem(0);
+		}
+
+		Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);
+	}
+	else if(UI()->HotItem() == pID && s_ActQIndex == QIndex)
+	{
+		ms_pUiGotContext = pID;
+
+		Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);
+		m_pTooltip = "Left mouse button to move. Hold ctrl to rotate. Hold alt to ignore grid.";
+
+		if(UI()->MouseButton(0))
+		{
+			if(Input()->KeyPressed(KEY_LCTRL) || Input()->KeyPressed(KEY_RCTRL))
+			{
+				m_LockMouse = true;
+				s_Operation = OP_ROTATE;
+			}
+			else
+				s_Operation = OP_MOVE;
+
+			m_SelectedEnvelopePoint = PIndex;
+			m_SelectedQuadEnvelope = pQuad->m_PosEnv;
+
+			UI()->SetActiveItem(pID);
+			if(m_SelectedQuad != QIndex)
+				m_SelectedPoints = 0;
+			m_SelectedQuad = QIndex;
+			s_LastWx = wx;
+			s_LastWy = wy;
+		}
+		else
+		{
+			m_SelectedEnvelopePoint = -1;
+			m_SelectedQuadEnvelope = -1;
+		}
+	}
+	else
+		Graphics()->SetColor(0.0f, 1.0f, 0.0f, 1.0f);
+
+	IGraphics::CQuadItem QuadItem(CenterX, CenterY, 5.0f*m_WorldZoom, 5.0f*m_WorldZoom);
+	Graphics()->QuadsDraw(&QuadItem, 1);
+}
+
 void CEditor::DoMapEditor(CUIRect View, CUIRect ToolBar)
 {
 	// render all good stuff
@@ -1384,6 +1641,12 @@ void CEditor::DoMapEditor(CUIRect View,
 			pT->ShowInfo();
 		}
 	}
+	else
+	{
+		// fix aspect ratio of the image in the picker
+		float Max = min(View.w, View.h);
+		View.w = View.h = Max;
+	}
 
 	static void *s_pEditorID = (void *)&s_pEditorID;
 	int Inside = UI()->MouseInside(&View);
@@ -1563,8 +1826,8 @@ void CEditor::DoMapEditor(CUIRect View,
 				{
 					if(!UI()->MouseButton(0))
 					{
-                        for(int k = 0; k < NumEditLayers; k++)
-                            pEditLayers[k]->FillSelection(m_Brush.IsEmpty(), m_Brush.m_lLayers[0], r);
+						for(int k = 0; k < NumEditLayers; k++)
+							pEditLayers[k]->FillSelection(m_Brush.IsEmpty(), m_Brush.m_lLayers[0], r);
 					}
 					else
 					{
@@ -1596,10 +1859,10 @@ void CEditor::DoMapEditor(CUIRect View,
 						}
 
 					}
-					
+
 					CLayerTiles *pLayer = (CLayerTiles*)GetSelectedLayerType(0, LAYERTYPE_TILES);
 					if((Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT)) && pLayer)
-                        s_Operation = OP_BRUSH_PAINT;
+						s_Operation = OP_BRUSH_PAINT;
 				}
 
 				if(!m_Brush.IsEmpty())
@@ -1656,6 +1919,9 @@ void CEditor::DoMapEditor(CUIRect View,
 					{
 						CLayerQuads *pLayer = (CLayerQuads *)pEditLayers[k];
 
+						if(!m_ShowEnvelopePreview)
+							m_ShowEnvelopePreview = 2;
+
 						Graphics()->TextureSet(-1);
 						Graphics()->QuadsBegin();
 						for(int i = 0; i < pLayer->m_lQuads.size(); i++)
@@ -1705,11 +1971,11 @@ void CEditor::DoMapEditor(CUIRect View,
 		}
 	}
 
-	if(GetSelectedGroup() && GetSelectedGroup()->m_UseClipping)
+	if(!m_ShowPicker && GetSelectedGroup() && GetSelectedGroup()->m_UseClipping)
 	{
 		CLayerGroup *g = m_Map.m_pGameGroup;
 		g->MapScreen();
-	
+
 		Graphics()->TextureSet(-1);
 		Graphics()->LinesBegin();
 
@@ -1813,6 +2079,24 @@ void CEditor::DoMapEditor(CUIRect View,
 		Graphics()->LinesEnd();
 	}
 
+	if (!m_ShowPicker && m_ShowTileInfo && m_ShowEnvelopePreview != 0 && GetSelectedLayer(0) && GetSelectedLayer(0)->m_Type == LAYERTYPE_QUADS)
+	{
+		GetSelectedGroup()->MapScreen();
+
+		CLayerQuads *pLayer = (CLayerQuads*)GetSelectedLayer(0);
+		int TexID = -1;
+		if(pLayer->m_Image >= 0 && pLayer->m_Image < m_Map.m_lImages.size())
+			TexID = m_Map.m_lImages[pLayer->m_Image]->m_TexID;
+
+		for(int i = 0; i < pLayer->m_lQuads.size(); i++)
+		{
+			if((m_ShowEnvelopePreview == 1 && pLayer->m_lQuads[i].m_PosEnv == m_SelectedEnvelope) || m_ShowEnvelopePreview == 2)
+				DoQuadEnvelopes(&pLayer->m_lQuads[i], i, TexID);
+		}
+
+		m_ShowEnvelopePreview = 0;
+    }
+
 	Graphics()->MapScreen(UI()->Screen()->x, UI()->Screen()->y, UI()->Screen()->w, UI()->Screen()->h);
 	//UI()->ClipDisable();
 }
@@ -1908,7 +2192,7 @@ int CEditor::DoProperties(CUIRect *pTool
 			if(pProps[i].m_Value < 0)
 				str_copy(aBuf, "None", sizeof(aBuf));
 			else
-				str_format(aBuf, sizeof(aBuf),"%s",  m_Map.m_lImages[pProps[i].m_Value]->m_aName);
+				str_format(aBuf, sizeof(aBuf),"%s", m_Map.m_lImages[pProps[i].m_Value]->m_aName);
 
 			if(DoButton_Editor(&pIDs[i], aBuf, 0, &Shifter, 0, 0))
 				PopupSelectImageInvoke(pProps[i].m_Value, UI()->MouseX(), UI()->MouseY());
@@ -2052,7 +2336,7 @@ void CEditor::RenderLayers(CUIRect ToolB
 
 					static int s_GroupPopupId = 0;
 					if(Result == 2)
-						UiInvokePopupMenu(&s_GroupPopupId, 0, UI()->MouseX(), UI()->MouseY(), 120, 220, PopupGroup);
+						UiInvokePopupMenu(&s_GroupPopupId, 0, UI()->MouseX(), UI()->MouseY(), 145, 220, PopupGroup);
 
 					if(m_Map.m_lGroups[g]->m_lLayers.size() && Input()->MouseDoubleClick())
 						m_Map.m_lGroups[g]->m_Collapse ^= 1;
@@ -2147,8 +2431,8 @@ void CEditor::ReplaceImage(const char *p
 	pEditor->SortImages();
 	for(int i = 0; i < pEditor->m_Map.m_lImages.size(); ++i)
 	{
-	    if(!str_comp(pEditor->m_Map.m_lImages[i]->m_aName, pImg->m_aName))
-           pEditor->m_SelectedImage = i;
+		if(!str_comp(pEditor->m_Map.m_lImages[i]->m_aName, pImg->m_aName))
+			pEditor->m_SelectedImage = i;
 	}
 	pEditor->m_Dialog = DIALOG_NONE;
 }
@@ -2165,8 +2449,8 @@ void CEditor::AddImage(const char *pFile
 	ExtractName(pFileName, aBuf, sizeof(aBuf));
 	for(int i = 0; i < pEditor->m_Map.m_lImages.size(); ++i)
 	{
-	    if(!str_comp(pEditor->m_Map.m_lImages[i]->m_aName, aBuf))
-            return;
+		if(!str_comp(pEditor->m_Map.m_lImages[i]->m_aName, aBuf))
+			return;
 	}
 
 	CEditorImage *pImg = new CEditorImage(pEditor);
@@ -2292,7 +2576,7 @@ void CEditor::SortImages()
 		gs_pSortedIndex = 0;
 	}
 }
-	
+
 
 void CEditor::RenderImages(CUIRect ToolBox, CUIRect ToolBar, CUIRect View)
 {
@@ -2390,15 +2674,28 @@ void CEditor::RenderImages(CUIRect ToolB
 					r.w = r.h;
 				else
 					r.h = r.w;
+				float Max = (float)(max(m_Map.m_lImages[i]->m_Width, m_Map.m_lImages[i]->m_Height));
+				r.w *= m_Map.m_lImages[i]->m_Width/Max;
+				r.h *= m_Map.m_lImages[i]->m_Height/Max;
 				Graphics()->TextureSet(m_Map.m_lImages[i]->m_TexID);
 				Graphics()->BlendNormal();
+				Graphics()->WrapClamp();
 				Graphics()->QuadsBegin();
 				IGraphics::CQuadItem QuadItem(r.x, r.y, r.w, r.h);
 				Graphics()->QuadsDrawTL(&QuadItem, 1);
 				Graphics()->QuadsEnd();
-
+				Graphics()->WrapNormal();
 			}
 		}
+
+		// separator
+		ToolBox.HSplitTop(5.0f, &Slot, &ToolBox);
+		ImageCur += 5.0f;
+		IGraphics::CLineItem LineItem(Slot.x, Slot.y+Slot.h/2, Slot.x+Slot.w, Slot.y+Slot.h/2);
+		Graphics()->TextureSet(-1);
+		Graphics()->LinesBegin();
+		Graphics()->LinesDraw(&LineItem, 1);
+		Graphics()->LinesEnd();
 	}
 
 	if(ImageCur + 27.0f > ImageStopAt)
@@ -2409,7 +2706,6 @@ void CEditor::RenderImages(CUIRect ToolB
 
 	// new image
 	static int s_NewImageButton = 0;
-	ToolBox.HSplitTop(10.0f, &Slot, &ToolBox);
 	ToolBox.HSplitTop(12.0f, &Slot, &ToolBox);
 	if(DoButton_Editor(&s_NewImageButton, "Add", 0, &Slot, 0, "Load a new image to use in the map"))
 		InvokeFileDialog(IStorage::TYPE_ALL, FILETYPE_IMG, "Add Image", "Add", "mapres", "", AddImage, this);
@@ -2485,11 +2781,13 @@ void CEditor::RenderFileDialog()
 	RenderTools()->DrawUIRect(&View, vec4(0,0,0,0.75f), CUI::CORNER_ALL, 5.0f);
 	View.Margin(10.0f, &View);
 
-	CUIRect Title, FileBox, FileBoxLabel, ButtonBar, Scroll;
+	CUIRect Title, FileBox, FileBoxLabel, ButtonBar, Scroll, PathBox;
 	View.HSplitTop(18.0f, &Title, &View);
 	View.HSplitTop(5.0f, 0, &View); // some spacing
 	View.HSplitBottom(14.0f, &View, &ButtonBar);
 	View.HSplitBottom(10.0f, &View, 0); // some spacing
+	View.HSplitBottom(14.0f, &View, &PathBox);
+	View.HSplitBottom(5.0f, &View, 0); // some spacing
 	View.HSplitBottom(14.0f, &View, &FileBox);
 	FileBox.VSplitLeft(55.0f, &FileBoxLabel, &FileBox);
 	View.HSplitBottom(10.0f, &View, 0); // some spacing
@@ -2500,6 +2798,15 @@ void CEditor::RenderFileDialog()
 	Title.VMargin(10.0f, &Title);
 	UI()->DoLabel(&Title, m_pFileDialogTitle, 12.0f, -1, -1);
 
+	// pathbox
+	char aPath[128], aBuf[128];
+	if(m_FilesSelectedIndex != -1)
+		Storage()->GetCompletePath(m_FileList[m_FilesSelectedIndex].m_StorageType, m_pFileDialogPath, aPath, sizeof(aPath));
+	else
+		aPath[0] = 0;
+	str_format(aBuf, sizeof(aBuf), "Current path: %s", aPath);
+	UI()->DoLabel(&PathBox, aBuf, 10.0f, -1, -1);
+
 	// filebox
 	if(m_FileDialogStorageType == IStorage::TYPE_SAVE)
 	{
@@ -2596,6 +2903,7 @@ void CEditor::RenderFileDialog()
 	static int s_OkButton = 0;
 	static int s_CancelButton = 0;
 	static int s_NewFolderButton = 0;
+	static int s_MapInfoButton = 0;
 
 	CUIRect Button;
 	ButtonBar.VSplitRight(50.0f, &ButtonBar, &Button);
@@ -2671,6 +2979,22 @@ void CEditor::RenderFileDialog()
 			UI()->SetActiveItem(0);
 		}
 	}
+
+	if(m_FileDialogStorageType == IStorage::TYPE_SAVE)
+	{
+		ButtonBar.VSplitLeft(40.0f, 0, &ButtonBar);
+		ButtonBar.VSplitLeft(70.0f, &Button, &ButtonBar);
+		if(DoButton_Editor(&s_MapInfoButton, "Map details", 0, &Button, 0, 0))
+		{
+			str_copy(m_Map.m_MapInfo.m_aAuthorTmp, m_Map.m_MapInfo.m_aAuthor, sizeof(m_Map.m_MapInfo.m_aAuthorTmp));
+			str_copy(m_Map.m_MapInfo.m_aVersionTmp, m_Map.m_MapInfo.m_aVersion, sizeof(m_Map.m_MapInfo.m_aVersionTmp));
+			str_copy(m_Map.m_MapInfo.m_aCreditsTmp, m_Map.m_MapInfo.m_aCredits, sizeof(m_Map.m_MapInfo.m_aCreditsTmp));
+			str_copy(m_Map.m_MapInfo.m_aLicenseTmp, m_Map.m_MapInfo.m_aLicense, sizeof(m_Map.m_MapInfo.m_aLicenseTmp));
+			static int s_MapInfoPopupID = 0;
+			UiInvokePopupMenu(&s_MapInfoPopupID, 0, Width/2.0f-200.0f, Height/2.0f-100.0f, 400.0f, 200.0f, PopupMapInfo);
+			UI()->SetActiveItem(0);
+		}
+	}
 }
 
 void CEditor::FilelistPopulate(int StorageType)
@@ -2711,7 +3035,7 @@ void CEditor::InvokeFileDialog(int Stora
 		str_copy(m_aFileDialogFileName, pDefaultName, sizeof(m_aFileDialogFileName));
 	if(pBasePath)
 		str_copy(m_aFileDialogCurrentFolder, pBasePath, sizeof(m_aFileDialogCurrentFolder));
-	
+
 	FilelistPopulate(m_FileDialogStorageType);
 
 	m_Dialog = DIALOG_FILE;
@@ -2731,10 +3055,10 @@ void CEditor::RenderModebar(CUIRect View
 		const char *pButName = m_Mode == MODE_LAYERS ? "Layers" : "Images";
 		if(DoButton_Tab(&s_Button, pButName, 0, &Button, 0, "Switch between images and layers managment."))
 		{
-		    if(m_Mode == MODE_LAYERS)
-                m_Mode = MODE_IMAGES;
-            else
-                m_Mode = MODE_LAYERS;
+			if(m_Mode == MODE_LAYERS)
+				m_Mode = MODE_IMAGES;
+			else
+				m_Mode = MODE_LAYERS;
 		}
 	}
 
@@ -2908,6 +3232,17 @@ void CEditor::RenderEnvelopeEditor(CUIRe
 				if(DoButton_Editor(&s_aChannelButtons[i], s_paNames[pEnvelope->m_Channels-3][i], s_ActiveChannels&Bit, &Button, 0, paDescriptions[pEnvelope->m_Channels-3][i]))
 					s_ActiveChannels ^= Bit;
 			}
+
+			// sync checkbox
+			ToolBar.VSplitLeft(15.0f, &Button, &ToolBar);
+			ToolBar.VSplitLeft(12.0f, &Button, &ToolBar);
+			static int s_SyncButton;
+			if(DoButton_Editor(&s_SyncButton, pEnvelope->m_Synchronized?"X":"", 0, &Button, 0, "Enable envelope synchronization between clients"))
+				pEnvelope->m_Synchronized = !pEnvelope->m_Synchronized;
+
+			ToolBar.VSplitLeft(4.0f, &Button, &ToolBar);
+			ToolBar.VSplitLeft(80.0f, &Button, &ToolBar);
+			UI()->DoLabel(&Button, "Synchronized", 10.0f, -1, -1);
 		}
 
 		float EndTime = pEnvelope->EndTime();
@@ -2947,6 +3282,7 @@ void CEditor::RenderEnvelopeEditor(CUIRe
 					m_Map.m_Modified = true;
 				}
 
+				m_ShowEnvelopePreview = 1;
 				m_pTooltip = "Press right mouse button to create a new point";
 			}
 		}
@@ -3085,10 +3421,13 @@ void CEditor::RenderEnvelopeEditor(CUIRe
 					{
 						if(!UI()->MouseButton(0))
 						{
+							m_SelectedQuadEnvelope = -1;
+							m_SelectedEnvelopePoint = -1;
+
 							UI()->SetActiveItem(0);
 						}
 						else
-						{							
+						{
 							if(Input()->KeyPressed(KEY_LSHIFT) || Input()->KeyPressed(KEY_RSHIFT))
 							{
 								if(i != 0)
@@ -3110,6 +3449,10 @@ void CEditor::RenderEnvelopeEditor(CUIRe
 								else
 									pEnvelope->m_lPoints[i].m_aValues[c] -= f2fx(m_MouseDeltaY*ValueScale);
 							}
+
+							m_SelectedQuadEnvelope = m_SelectedEnvelope;
+							m_ShowEnvelopePreview = 1;
+							m_SelectedEnvelopePoint = i;
 							m_Map.m_Modified = true;
 						}
 
@@ -3132,6 +3475,7 @@ void CEditor::RenderEnvelopeEditor(CUIRe
 							m_Map.m_Modified = true;
 						}
 
+						m_ShowEnvelopePreview = 1;
 						ColorMod = 100.0f;
 						Graphics()->SetColor(1,0.75f,0.75f,1);
 						m_pTooltip = "Left mouse to drag. Hold ctrl to be more precise. Hold shift to alter time point aswell. Right click to delete.";
@@ -3143,7 +3487,10 @@ void CEditor::RenderEnvelopeEditor(CUIRe
 						CurrentValue = pEnvelope->m_lPoints[i].m_aValues[c];
 					}
 
-					Graphics()->SetColor(aColors[c].r*ColorMod, aColors[c].g*ColorMod, aColors[c].b*ColorMod, 1.0f);
+					if (m_SelectedQuadEnvelope == m_SelectedEnvelope && m_SelectedEnvelopePoint == i)
+						Graphics()->SetColor(1.0f, 1.0f, 1.0f, 1.0f);
+					else
+						Graphics()->SetColor(aColors[c].r*ColorMod, aColors[c].g*ColorMod, aColors[c].b*ColorMod, 1.0f);
 					IGraphics::CQuadItem QuadItem(Final.x, Final.y, Final.w, Final.h);
 					Graphics()->QuadsDrawTL(&QuadItem, 1);
 				}
@@ -3266,10 +3613,15 @@ void CEditor::RenderMenubar(CUIRect Menu
 		(void)0;
 		*/
 
+	CUIRect Info;
 	MenuBar.VSplitLeft(40.0f, 0, &MenuBar);
+	MenuBar.VSplitLeft(MenuBar.w*0.75f, &MenuBar, &Info);
 	char aBuf[128];
 	str_format(aBuf, sizeof(aBuf), "File: %s", m_aFileName);
 	UI()->DoLabel(&MenuBar, aBuf, 10.0f, -1, -1);
+
+	str_format(aBuf, sizeof(aBuf), "Z: %i, A: %.1f, G: %i", m_ZoomLevel, m_AnimateSpeed, m_GridFactor);
+	UI()->DoLabel(&Info, aBuf, 10.0f, 1, -1);
 }
 
 void CEditor::Render()
@@ -3285,6 +3637,9 @@ void CEditor::Render()
 	// reset tip
 	m_pTooltip = 0;
 
+	if(m_EditBoxActive)
+		--m_EditBoxActive;
+
 	// render checker
 	RenderBackground(View, ms_CheckerTexture, 32.0f, 1.0f);
 
@@ -3314,7 +3669,17 @@ void CEditor::Render()
 	if(m_Mode == MODE_LAYERS)
 		DoMapEditor(View, ToolBar);
 
-	// do the scrolling
+	// do zooming
+	if(Input()->KeyDown(KEY_KP_MINUS))
+		m_ZoomLevel += 50;
+	if(Input()->KeyDown(KEY_KP_PLUS))
+		m_ZoomLevel -= 50;
+	if(Input()->KeyDown(KEY_KP_MULTIPLY))
+	{
+		m_EditorOffsetX = 0;
+		m_EditorOffsetY = 0;
+		m_ZoomLevel = 100;
+	}
 	if(m_Dialog == DIALOG_NONE && UI()->MouseInside(&View))
 	{
 		if(Input()->KeyPresses(KEY_MOUSE_WHEEL_UP))
@@ -3322,9 +3687,9 @@ void CEditor::Render()
 
 		if(Input()->KeyPresses(KEY_MOUSE_WHEEL_DOWN))
 			m_ZoomLevel += 20;
-
-		m_ZoomLevel = clamp(m_ZoomLevel, 50, 2000);
 	}
+	m_ZoomLevel = clamp(m_ZoomLevel, 50, 2000);
+	m_WorldZoom = m_ZoomLevel/100.0f;
 
 	if(m_GuiActive)
 	{
@@ -3382,6 +3747,7 @@ void CEditor::Render()
 		static int s_PopupID = 0;
 		UiInvokePopupMenu(&s_PopupID, 0, Width/2.0f-200.0f, Height/2.0f-100.0f, 400.0f, 200.0f, PopupEvent);
 		m_PopupEventActivated = false;
+		m_PopupEventWasActivated = true;
 	}
 
 
@@ -3443,12 +3809,12 @@ void CEditor::Reset(bool CreateDefault)
 	m_SelectedPoints = 0;
 	m_SelectedEnvelope = 0;
 	m_SelectedImage = 0;
-	
+
 	m_WorldOffsetX = 0;
 	m_WorldOffsetY = 0;
 	m_EditorOffsetX = 0.0f;
 	m_EditorOffsetY = 0.0f;
-	
+
 	m_WorldZoom = 1.0f;
 	m_ZoomLevel = 200;
 
@@ -3458,6 +3824,8 @@ void CEditor::Reset(bool CreateDefault)
 	m_MouseDeltaWy = 0;
 
 	m_Map.m_Modified = false;
+
+	m_ShowEnvelopePreview = 0;
 }
 
 int CEditor::GetLineDistance()
@@ -3490,18 +3858,26 @@ void CEditorMap::DeleteEnvelope(int Inde
 		for(int j = 0; j < m_lGroups[i]->m_lLayers.size(); ++j)
 			if(m_lGroups[i]->m_lLayers[j]->m_Type == LAYERTYPE_QUADS)
 			{
-				CLayerQuads *Layer = static_cast<CLayerQuads *>(m_lGroups[i]->m_lLayers[j]);
-				for(int k = 0; k < Layer->m_lQuads.size(); ++k)
+				CLayerQuads *pLayer = static_cast<CLayerQuads *>(m_lGroups[i]->m_lLayers[j]);
+				for(int k = 0; k < pLayer->m_lQuads.size(); ++k)
 				{
-					if(Layer->m_lQuads[k].m_PosEnv == Index)
-						Layer->m_lQuads[k].m_PosEnv = -1;
-					else if(Layer->m_lQuads[k].m_PosEnv > Index)
-						Layer->m_lQuads[k].m_PosEnv--;
-					if(Layer->m_lQuads[k].m_ColorEnv == Index)
-						Layer->m_lQuads[k].m_ColorEnv = -1;
-					else if(Layer->m_lQuads[k].m_ColorEnv > Index)
-						Layer->m_lQuads[k].m_ColorEnv--;
-				}
+					if(pLayer->m_lQuads[k].m_PosEnv == Index)
+						pLayer->m_lQuads[k].m_PosEnv = -1;
+					else if(pLayer->m_lQuads[k].m_PosEnv > Index)
+						pLayer->m_lQuads[k].m_PosEnv--;
+					if(pLayer->m_lQuads[k].m_ColorEnv == Index)
+						pLayer->m_lQuads[k].m_ColorEnv = -1;
+					else if(pLayer->m_lQuads[k].m_ColorEnv > Index)
+						pLayer->m_lQuads[k].m_ColorEnv--;
+				}
+			}
+			else if(m_lGroups[i]->m_lLayers[j]->m_Type == LAYERTYPE_TILES)
+			{
+				CLayerTiles *pLayer = static_cast<CLayerTiles *>(m_lGroups[i]->m_lLayers[j]);
+				if(pLayer->m_ColorEnv == Index)
+					pLayer->m_ColorEnv = -1;
+				if(pLayer->m_ColorEnv > Index)
+					pLayer->m_ColorEnv--;
 			}
 
 	m_lEnvelopes.remove_index(Index);
@@ -3529,6 +3905,8 @@ void CEditorMap::Clean()
 	m_lEnvelopes.delete_all();
 	m_lImages.delete_all();
 
+	m_MapInfo.Reset();
+
 	m_pGameLayer = 0x0;
 	m_pGameGroup = 0x0;
 
@@ -3594,19 +3972,19 @@ void CEditor::Init()
 
 void CEditor::DoMapBorder()
 {
-    CLayerTiles *pT = (CLayerTiles *)GetSelectedLayerType(0, LAYERTYPE_TILES);
-    
-    for(int i = 0; i < pT->m_Width*2; ++i)
-        pT->m_pTiles[i].m_Index = 1;
-        
-    for(int i = 0; i < pT->m_Width*pT->m_Height; ++i)
-    {
-        if(i%pT->m_Width < 2 || i%pT->m_Width > pT->m_Width-3)
-            pT->m_pTiles[i].m_Index = 1;
-    }
-    
-    for(int i = (pT->m_Width*(pT->m_Height-2)); i < pT->m_Width*pT->m_Height; ++i)
-        pT->m_pTiles[i].m_Index = 1;
+	CLayerTiles *pT = (CLayerTiles *)GetSelectedLayerType(0, LAYERTYPE_TILES);
+
+	for(int i = 0; i < pT->m_Width*2; ++i)
+		pT->m_pTiles[i].m_Index = 1;
+
+	for(int i = 0; i < pT->m_Width*pT->m_Height; ++i)
+	{
+		if(i%pT->m_Width < 2 || i%pT->m_Width > pT->m_Width-3)
+			pT->m_pTiles[i].m_Index = 1;
+	}
+
+	for(int i = (pT->m_Width*(pT->m_Height-2)); i < pT->m_Width*pT->m_Height; ++i)
+		pT->m_pTiles[i].m_Index = 1;
 }
 
 void CEditor::UpdateAndRender()
diff -rupN teeworlds-b177-r50edfd37-source/src//game/editor/editor.h alien-rc4/src//game/editor/editor.h
--- teeworlds-b177-r50edfd37-source/src//game/editor/editor.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/editor/editor.h	2012-06-14 23:57:39.000000000 +0200
@@ -51,6 +51,7 @@ public:
 	array<CEnvPoint> m_lPoints;
 	char m_aName[32];
 	float m_Bottom, m_Top;
+	bool m_Synchronized;
 
 	CEnvelope(int Chan)
 	{
@@ -58,6 +59,7 @@ public:
 		m_aName[0] = 0;
 		m_Bottom = 0;
 		m_Top = 0;
+		m_Synchronized = true;
 	}
 
 	void Resort()
@@ -274,6 +276,34 @@ public:
 	array<CEditorImage*> m_lImages;
 	array<CEnvelope*> m_lEnvelopes;
 
+	class CMapInfo
+	{
+	public:
+		char m_aAuthorTmp[32];
+		char m_aVersionTmp[16];
+		char m_aCreditsTmp[128];
+		char m_aLicenseTmp[32];
+
+		char m_aAuthor[32];
+		char m_aVersion[16];
+		char m_aCredits[128];
+		char m_aLicense[32];
+
+		void Reset()
+		{
+			m_aAuthorTmp[0] = 0;
+			m_aVersionTmp[0] = 0;
+			m_aCreditsTmp[0] = 0;
+			m_aLicenseTmp[0] = 0;
+
+			m_aAuthor[0] = 0;
+			m_aVersion[0] = 0;
+			m_aCredits[0] = 0;
+			m_aLicense[0] = 0;
+		}
+	};
+	CMapInfo m_MapInfo;
+
 	class CLayerGame *m_pGameLayer;
 	CLayerGroup *m_pGameGroup;
 
@@ -476,6 +506,7 @@ public:
 
 		m_Mode = MODE_LAYERS;
 		m_Dialog = 0;
+		m_EditBoxActive = 0;
 		m_pTooltip = 0;
 
 		m_GridActive = false;
@@ -486,6 +517,7 @@ public:
 		m_ValidSaveFilename = false;
 
 		m_PopupEventActivated = false;
+		m_PopupEventWasActivated = false;
 
 		m_FileDialogStorageType = 0;
 		m_pFileDialogTitle = 0;
@@ -528,6 +560,10 @@ public:
 
 		m_ShowEnvelopeEditor = 0;
 
+		m_ShowEnvelopePreview = 0;
+		m_SelectedQuadEnvelope = -1;
+		m_SelectedEnvelopePoint = -1;
+
 		ms_CheckerTexture = 0;
 		ms_BackgroundTexture = 0;
 		ms_CursorTexture = 0;
@@ -560,6 +596,7 @@ public:
 
 	int m_Mode;
 	int m_Dialog;
+	int m_EditBoxActive;
 	const char *m_pTooltip;
 
 	bool m_GridActive;
@@ -579,6 +616,7 @@ public:
 
 	int m_PopupEventType;
 	int m_PopupEventActivated;
+	int m_PopupEventWasActivated;
 
 	enum
 	{
@@ -644,6 +682,7 @@ public:
 	float m_AnimateSpeed;
 
 	int m_ShowEnvelopeEditor;
+	int m_ShowEnvelopePreview; //Values: 0-Off|1-Selected Envelope|2-All
 	bool m_ShowPicker;
 
 	int m_SelectedLayer;
@@ -651,6 +690,8 @@ public:
 	int m_SelectedQuad;
 	int m_SelectedPoints;
 	int m_SelectedEnvelope;
+	int m_SelectedEnvelopePoint;
+    int m_SelectedQuadEnvelope;
 	int m_SelectedImage;
 
 	static int ms_CheckerTexture;
@@ -697,6 +738,7 @@ public:
 	static int PopupQuad(CEditor *pEditor, CUIRect View);
 	static int PopupPoint(CEditor *pEditor, CUIRect View);
 	static int PopupNewFolder(CEditor *pEditor, CUIRect View);
+	static int PopupMapInfo(CEditor *pEditor, CUIRect View);
 	static int PopupEvent(CEditor *pEditor, CUIRect View);
 	static int PopupSelectImage(CEditor *pEditor, CUIRect View);
 	static int PopupSelectGametileOp(CEditor *pEditor, CUIRect View);
@@ -713,13 +755,16 @@ public:
 
 	void PopupSelectGametileOpInvoke(float x, float y);
 	int PopupSelectGameTileOpResult();
-	
+
 	void PopupSelectConfigAutoMapInvoke(float x, float y);
 	int PopupSelectConfigAutoMapResult();
 
 	vec4 ButtonColorMul(const void *pID);
 
+	void DoQuadEnvelopes(CQuad *pQuad, int Index, int TexID = -1);
+	void DoQuadEnvPoint(CQuad *pQuad, int QIndex, int pIndex);
 	void DoQuadPoint(CQuad *pQuad, int QuadIndex, int v);
+
 	void DoMapEditor(CUIRect View, CUIRect Toolbar);
 	void DoToolbar(CUIRect Toolbar);
 	void DoQuad(CQuad *pQuad, int Index);
diff -rupN teeworlds-b177-r50edfd37-source/src//game/editor/io.cpp alien-rc4/src//game/editor/io.cpp
--- teeworlds-b177-r50edfd37-source/src//game/editor/io.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/editor/io.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -220,6 +220,31 @@ int CEditorMap::Save(class IStorage *pSt
 		df.AddItem(MAPITEMTYPE_VERSION, 0, sizeof(Item), &Item);
 	}
 
+	// save map info
+	{
+		CMapItemInfo Item;
+		Item.m_Version = 1;
+
+		if(m_MapInfo.m_aAuthor[0])
+			Item.m_Author = df.AddData(str_length(m_MapInfo.m_aAuthor)+1, m_MapInfo.m_aAuthor);
+		else
+			Item.m_Author = -1;
+		if(m_MapInfo.m_aVersion[0])
+			Item.m_MapVersion = df.AddData(str_length(m_MapInfo.m_aVersion)+1, m_MapInfo.m_aVersion);
+		else
+			Item.m_MapVersion = -1;
+		if(m_MapInfo.m_aCredits[0])
+			Item.m_Credits = df.AddData(str_length(m_MapInfo.m_aCredits)+1, m_MapInfo.m_aCredits);
+		else
+			Item.m_Credits = -1;
+		if(m_MapInfo.m_aLicense[0])
+			Item.m_License = df.AddData(str_length(m_MapInfo.m_aLicense)+1, m_MapInfo.m_aLicense);
+		else
+			Item.m_License = -1;
+
+		df.AddItem(MAPITEMTYPE_INFO, 0, sizeof(Item), &Item);
+	}
+
 	// save images
 	for(int i = 0; i < m_lImages.size(); i++)
 	{
@@ -342,10 +367,11 @@ int CEditorMap::Save(class IStorage *pSt
 	for(int e = 0; e < m_lEnvelopes.size(); e++)
 	{
 		CMapItemEnvelope Item;
-		Item.m_Version = 1;
+		Item.m_Version = CMapItemEnvelope::CURRENT_VERSION;
 		Item.m_Channels = m_lEnvelopes[e]->m_Channels;
 		Item.m_StartPoint = PointCount;
 		Item.m_NumPoints = m_lEnvelopes[e]->m_lPoints.size();
+		Item.m_Synchronized = m_lEnvelopes[e]->m_Synchronized;
 		StrToInts(Item.m_aName, sizeof(Item.m_aName)/sizeof(int), m_lEnvelopes[e]->m_aName);
 
 		df.AddItem(MAPITEMTYPE_ENVELOPE, e, sizeof(Item), &Item);
@@ -413,6 +439,22 @@ int CEditorMap::Load(class IStorage *pSt
 	{
 		//editor.reset(false);
 
+		// load map info
+		{
+			CMapItemInfo *pItem = (CMapItemInfo *)DataFile.FindItem(MAPITEMTYPE_INFO, 0);
+			if(pItem && pItem->m_Version == 1)
+			{
+				if(pItem->m_Author > -1)
+					str_copy(m_MapInfo.m_aAuthor, (char *)DataFile.GetData(pItem->m_Author), sizeof(m_MapInfo.m_aAuthor));
+				if(pItem->m_MapVersion > -1)
+					str_copy(m_MapInfo.m_aVersion, (char *)DataFile.GetData(pItem->m_MapVersion), sizeof(m_MapInfo.m_aVersion));
+				if(pItem->m_Credits > -1)
+					str_copy(m_MapInfo.m_aCredits, (char *)DataFile.GetData(pItem->m_Credits), sizeof(m_MapInfo.m_aCredits));
+				if(pItem->m_License > -1)
+					str_copy(m_MapInfo.m_aLicense, (char *)DataFile.GetData(pItem->m_License), sizeof(m_MapInfo.m_aLicense));
+			}
+		}
+
 		// load images
 		{
 			int Start, Num;
@@ -601,6 +643,8 @@ int CEditorMap::Load(class IStorage *pSt
 				if(pItem->m_aName[0] != -1)	// compatibility with old maps
 					IntsToStr(pItem->m_aName, sizeof(pItem->m_aName)/sizeof(int), pEnv->m_aName);
 				m_lEnvelopes.add(pEnv);
+				if(pItem->m_Version >= 2)
+					pEnv->m_Synchronized = pItem->m_Synchronized;
 			}
 		}
 	}
diff -rupN teeworlds-b177-r50edfd37-source/src//game/editor/layer_tiles.cpp alien-rc4/src//game/editor/layer_tiles.cpp
--- teeworlds-b177-r50edfd37-source/src//game/editor/layer_tiles.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/editor/layer_tiles.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -159,6 +159,8 @@ void CLayerTiles::FillSelection(bool Emp
 	if(m_Readonly)
 		return;
 
+	Snap(&Rect);
+
 	int sx = ConvertX(Rect.x);
 	int sy = ConvertY(Rect.y);
 	int w = ConvertX(Rect.w);
@@ -166,9 +168,9 @@ void CLayerTiles::FillSelection(bool Emp
 
 	CLayerTiles *pLt = static_cast<CLayerTiles*>(pBrush);
 
-	for(int y = 0; y <= h; y++)
+	for(int y = 0; y < h; y++)
 	{
-		for(int x = 0; x <= w; x++)
+		for(int x = 0; x < w; x++)
 		{
 			int fx = x+sx;
 			int fy = y+sy;
@@ -363,7 +365,7 @@ void CLayerTiles::ShowInfo()
 int CLayerTiles::RenderProperties(CUIRect *pToolBox)
 {
 	CUIRect Button;
-	
+
 	bool InGameGroup = !find_linear(m_pEditor->m_Map.m_pGameGroup->m_lLayers.all(), this).empty();
 	if(m_pEditor->m_Map.m_pGameLayer != this)
 	{
@@ -373,7 +375,7 @@ int CLayerTiles::RenderProperties(CUIRec
 			pToolBox->HSplitBottom(12.0f, pToolBox, &Button);
 			if(m_pEditor->DoButton_Editor(&s_AutoMapperButton, "Auto map", 0, &Button, 0, ""))
 				m_pEditor->PopupSelectConfigAutoMapInvoke(m_pEditor->UI()->MouseX(), m_pEditor->UI()->MouseY());
-			
+
 			int Result = m_pEditor->PopupSelectConfigAutoMapResult();
 			if(Result > -1)
 			{
@@ -473,7 +475,19 @@ int CLayerTiles::RenderProperties(CUIRec
 		m_Color.a = NewVal&0xff;
 	}
 	if(Prop == PROP_COLOR_ENV)
-		m_ColorEnv = clamp(NewVal-1, -1, m_pEditor->m_Map.m_lEnvelopes.size()-1);
+	{
+		int Index = clamp(NewVal-1, -1, m_pEditor->m_Map.m_lEnvelopes.size()-1);
+		int Step = (Index-m_ColorEnv)%2;
+		if(Step != 0)
+		{
+			for(; Index >= -1 && Index < m_pEditor->m_Map.m_lEnvelopes.size(); Index += Step)
+				if(Index == -1 || m_pEditor->m_Map.m_lEnvelopes[Index]->m_Channels == 4)
+				{
+					m_ColorEnv = Index;
+					break;
+				}
+		}
+	}
 	if(Prop == PROP_COLOR_ENV_OFFSET)
 		m_ColorEnvOffset = NewVal;
 
diff -rupN teeworlds-b177-r50edfd37-source/src//game/editor/popups.cpp alien-rc4/src//game/editor/popups.cpp
--- teeworlds-b177-r50edfd37-source/src//game/editor/popups.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/editor/popups.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -458,9 +458,35 @@ int CEditor::PopupQuad(CEditor *pEditor,
 		for(int k = 0; k < 5; ++k)
 			pQuad->m_aPoints[k].y += Offset;
 	}
-	if(Prop == PROP_POS_ENV) pQuad->m_PosEnv = clamp(NewVal-1, -1, pEditor->m_Map.m_lEnvelopes.size()-1);
+	if(Prop == PROP_POS_ENV)
+	{
+		int Index = clamp(NewVal-1, -1, pEditor->m_Map.m_lEnvelopes.size()-1);
+		int Step = (Index-pQuad->m_PosEnv)%2;
+		if(Step != 0)
+		{
+			for(; Index >= -1 && Index < pEditor->m_Map.m_lEnvelopes.size(); Index += Step)
+				if(Index == -1 || pEditor->m_Map.m_lEnvelopes[Index]->m_Channels == 3)
+				{
+					pQuad->m_PosEnv = Index;
+					break;
+				}
+		}
+	}
 	if(Prop == PROP_POS_ENV_OFFSET) pQuad->m_PosEnvOffset = NewVal;
-	if(Prop == PROP_COLOR_ENV) pQuad->m_ColorEnv = clamp(NewVal-1, -1, pEditor->m_Map.m_lEnvelopes.size()-1);
+	if(Prop == PROP_COLOR_ENV)
+	{
+		int Index = clamp(NewVal-1, -1, pEditor->m_Map.m_lEnvelopes.size()-1);
+		int Step = (Index-pQuad->m_ColorEnv)%2;
+		if(Step != 0)
+		{
+			for(; Index >= -1 && Index < pEditor->m_Map.m_lEnvelopes.size(); Index += Step)
+				if(Index == -1 || pEditor->m_Map.m_lEnvelopes[Index]->m_Channels == 4)
+				{
+					pQuad->m_ColorEnv = Index;
+					break;
+				}
+		}
+	}
 	if(Prop == PROP_COLOR_ENV_OFFSET) pQuad->m_ColorEnvOffset = NewVal;
 
 	return 0;
@@ -609,6 +635,74 @@ int CEditor::PopupNewFolder(CEditor *pEd
 	return 0;
 }
 
+int CEditor::PopupMapInfo(CEditor *pEditor, CUIRect View)
+{
+	CUIRect Label, ButtonBar, Button;
+
+	// title
+	View.HSplitTop(10.0f, 0, &View);
+	View.HSplitTop(30.0f, &Label, &View);
+	pEditor->UI()->DoLabel(&Label, "Map details", 20.0f, 0);
+
+	View.HSplitBottom(10.0f, &View, 0);
+	View.HSplitBottom(20.0f, &View, &ButtonBar);
+
+	View.VMargin(40.0f, &View);
+
+	// author box
+	View.HSplitTop(20.0f, &Label, &View);
+	pEditor->UI()->DoLabel(&Label, "Author:", 10.0f, -1);
+	Label.VSplitLeft(40.0f, 0, &Button);
+	Button.HSplitTop(12.0f, &Button, 0);
+	static float s_AuthorBox = 0;
+	pEditor->DoEditBox(&s_AuthorBox, &Button, pEditor->m_Map.m_MapInfo.m_aAuthorTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aAuthorTmp), 10.0f, &s_AuthorBox);
+
+	// version box
+	View.HSplitTop(20.0f, &Label, &View);
+	pEditor->UI()->DoLabel(&Label, "Version:", 10.0f, -1);
+	Label.VSplitLeft(40.0f, 0, &Button);
+	Button.HSplitTop(12.0f, &Button, 0);
+	static float s_VersionBox = 0;
+	pEditor->DoEditBox(&s_VersionBox, &Button, pEditor->m_Map.m_MapInfo.m_aVersionTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aVersionTmp), 10.0f, &s_VersionBox);
+
+	// credits box
+	View.HSplitTop(20.0f, &Label, &View);
+	pEditor->UI()->DoLabel(&Label, "Credits:", 10.0f, -1);
+	Label.VSplitLeft(40.0f, 0, &Button);
+	Button.HSplitTop(12.0f, &Button, 0);
+	static float s_CreditsBox = 0;
+	pEditor->DoEditBox(&s_CreditsBox, &Button, pEditor->m_Map.m_MapInfo.m_aCreditsTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aCreditsTmp), 10.0f, &s_CreditsBox);
+
+	// license box
+	View.HSplitTop(20.0f, &Label, &View);
+	pEditor->UI()->DoLabel(&Label, "License:", 10.0f, -1);
+	Label.VSplitLeft(40.0f, 0, &Button);
+	Button.HSplitTop(12.0f, &Button, 0);
+	static float s_LicenseBox = 0;
+	pEditor->DoEditBox(&s_LicenseBox, &Button, pEditor->m_Map.m_MapInfo.m_aLicenseTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aLicenseTmp), 10.0f, &s_LicenseBox);
+
+	// button bar
+	ButtonBar.VSplitLeft(30.0f, 0, &ButtonBar);
+	ButtonBar.VSplitLeft(110.0f, &Label, &ButtonBar);
+	static int s_CreateButton = 0;
+	if(pEditor->DoButton_Editor(&s_CreateButton, "Save", 0, &Label, 0, 0))
+	{
+		str_copy(pEditor->m_Map.m_MapInfo.m_aAuthor, pEditor->m_Map.m_MapInfo.m_aAuthorTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aAuthor));
+		str_copy(pEditor->m_Map.m_MapInfo.m_aVersion, pEditor->m_Map.m_MapInfo.m_aVersionTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aVersion));
+		str_copy(pEditor->m_Map.m_MapInfo.m_aCredits, pEditor->m_Map.m_MapInfo.m_aCreditsTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aCredits));
+		str_copy(pEditor->m_Map.m_MapInfo.m_aLicense, pEditor->m_Map.m_MapInfo.m_aLicenseTmp, sizeof(pEditor->m_Map.m_MapInfo.m_aLicense));
+		return 1;
+	}
+
+	ButtonBar.VSplitRight(30.0f, &ButtonBar, 0);
+	ButtonBar.VSplitRight(110.0f, &ButtonBar, &Label);
+	static int s_AbortButton = 0;
+	if(pEditor->DoButton_Editor(&s_AbortButton, "Abort", 0, &Label, 0, 0))
+		return 1;
+
+	return 0;
+}
+
 int CEditor::PopupEvent(CEditor *pEditor, CUIRect View)
 {
 	CUIRect Label, ButtonBar;
@@ -658,13 +752,17 @@ int CEditor::PopupEvent(CEditor *pEditor
 		}
 		else if(pEditor->m_PopupEventType == POPEVENT_SAVE)
 			pEditor->CallbackSaveMap(pEditor->m_aFileSaveName, IStorage::TYPE_SAVE, pEditor);
+		pEditor->m_PopupEventWasActivated = false;
 		return 1;
 	}
 	ButtonBar.VSplitRight(30.0f, &ButtonBar, 0);
 	ButtonBar.VSplitRight(110.0f, &ButtonBar, &Label);
 	static int s_AbortButton = 0;
 	if(pEditor->DoButton_Editor(&s_AbortButton, "Abort", 0, &Label, 0, 0))
+	{
+		pEditor->m_PopupEventWasActivated = false;
 		return 1;
+	}
 
 	return 0;
 }
@@ -703,13 +801,23 @@ int CEditor::PopupSelectImage(CEditor *p
 	}
 
 	if(ShowImage >= 0 && ShowImage < pEditor->m_Map.m_lImages.size())
+	{
+		if(ImageView.h < ImageView.w)
+			ImageView.w = ImageView.h;
+		else
+			ImageView.h = ImageView.w;
+		float Max = (float)(max(pEditor->m_Map.m_lImages[ShowImage]->m_Width, pEditor->m_Map.m_lImages[ShowImage]->m_Height));
+		ImageView.w *= pEditor->m_Map.m_lImages[ShowImage]->m_Width/Max;
+		ImageView.h *= pEditor->m_Map.m_lImages[ShowImage]->m_Height/Max;
 		pEditor->Graphics()->TextureSet(pEditor->m_Map.m_lImages[ShowImage]->m_TexID);
-	else
-		pEditor->Graphics()->TextureSet(-1);
-	pEditor->Graphics()->QuadsBegin();
-	IGraphics::CQuadItem QuadItem(ImageView.x, ImageView.y, ImageView.w, ImageView.h);
-	pEditor->Graphics()->QuadsDrawTL(&QuadItem, 1);
-	pEditor->Graphics()->QuadsEnd();
+		pEditor->Graphics()->BlendNormal();
+		pEditor->Graphics()->WrapClamp();
+		pEditor->Graphics()->QuadsBegin();
+		IGraphics::CQuadItem QuadItem(ImageView.x, ImageView.y, ImageView.w, ImageView.h);
+		pEditor->Graphics()->QuadsDrawTL(&QuadItem, 1);
+		pEditor->Graphics()->QuadsEnd();
+		pEditor->Graphics()->WrapNormal();
+	}
 
 	return 0;
 }
@@ -776,7 +884,7 @@ int CEditor::PopupSelectConfigAutoMap(CE
 	CUIRect Button;
 	static int s_AutoMapperConfigButtons[256];
 	CAutoMapper *pAutoMapper = &pEditor->m_Map.m_lImages[pLayer->m_Image]->m_AutoMapper;
-	
+
 	for(int i = 0; i < pAutoMapper->ConfigNamesNum(); ++i)
 	{
 		View.HSplitTop(2.0f, 0, &View);
@@ -802,7 +910,7 @@ int CEditor::PopupSelectConfigAutoMapRes
 {
 	if(s_AutoMapConfigSelected < 0)
 		return -1;
-	
+
 	int Result = s_AutoMapConfigSelected;
 	s_AutoMapConfigSelected = -1;
 	return Result;
diff -rupN teeworlds-b177-r50edfd37-source/src//game/gamecore.cpp alien-rc4/src//game/gamecore.cpp
--- teeworlds-b177-r50edfd37-source/src//game/gamecore.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/gamecore.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -302,7 +302,7 @@ void CCharacterCore::Tick(bool UseInput)
 		}
 	}
 
-	if(m_pWorld && m_pWorld->m_Tuning.m_PlayerCollision)
+	if(m_pWorld)
 	{
 		for(int i = 0; i < MAX_CLIENTS; i++)
 		{
@@ -317,7 +317,7 @@ void CCharacterCore::Tick(bool UseInput)
 			// handle player <-> player collision
 			float Distance = distance(m_Pos, pCharCore->m_Pos);
 			vec2 Dir = normalize(m_Pos - pCharCore->m_Pos);
-			if(Distance < PhysSize*1.25f && Distance > 0.0f)
+			if(m_pWorld->m_Tuning.m_PlayerCollision && Distance < PhysSize*1.25f && Distance > 0.0f)
 			{
 				float a = (PhysSize*1.45f - Distance);
 				float Velocity = 0.5f;
@@ -332,7 +332,7 @@ void CCharacterCore::Tick(bool UseInput)
 			}
 
 			// handle hook influence
-			if(m_HookedPlayer == i)
+			if(m_HookedPlayer == i && m_pWorld->m_Tuning.m_PlayerHooking)
 			{
 				if(Distance > PhysSize*1.50f) // TODO: fix tweakable variable
 				{
diff -rupN teeworlds-b177-r50edfd37-source/src//game/generated/nethash.cpp alien-rc4/src//game/generated/nethash.cpp
--- teeworlds-b177-r50edfd37-source/src//game/generated/nethash.cpp	2012-01-27 22:23:47.000000000 +0100
+++ alien-rc4/src//game/generated/nethash.cpp	1970-01-01 01:00:00.000000000 +0100
@@ -1 +0,0 @@
-#define GAME_NETVERSION_HASH "626fce9a778df4d4"
diff -rupN teeworlds-b177-r50edfd37-source/src//game/generated/protocol.cpp alien-rc4/src//game/generated/protocol.cpp
--- teeworlds-b177-r50edfd37-source/src//game/generated/protocol.cpp	2012-01-27 22:23:47.000000000 +0100
+++ alien-rc4/src//game/generated/protocol.cpp	1970-01-01 01:00:00.000000000 +0100
@@ -1,560 +0,0 @@
-#include <engine/shared/protocol.h>
-#include <engine/message.h>
-#include "protocol.h"
-CNetObjHandler::CNetObjHandler()
-{
-	m_pMsgFailedOn = "";
-	m_pObjCorrectedOn = "";
-	m_NumObjCorrections = 0;
-}
-
-int CNetObjHandler::NumObjCorrections() { return m_NumObjCorrections; }
-const char *CNetObjHandler::CorrectedObjOn() { return m_pObjCorrectedOn; }
-const char *CNetObjHandler::FailedMsgOn() { return m_pMsgFailedOn; }
-
-
-
-
-
-static const int max_int = 0x7fffffff;
-int CNetObjHandler::ClampInt(const char *pErrorMsg, int Value, int Min, int Max)
-{
-	if(Value < Min) { m_pObjCorrectedOn = pErrorMsg; m_NumObjCorrections++; return Min; }
-	if(Value > Max) { m_pObjCorrectedOn = pErrorMsg; m_NumObjCorrections++; return Max; }
-	return Value;
-}
-const char *CNetObjHandler::ms_apObjNames[] = {
-	"invalid",
-	"PlayerInput",
-	"Projectile",
-	"Laser",
-	"Pickup",
-	"Flag",
-	"GameInfo",
-	"GameData",
-	"CharacterCore",
-	"Character",
-	"PlayerInfo",
-	"ClientInfo",
-	"SpectatorInfo",
-	"Common",
-	"Explosion",
-	"Spawn",
-	"HammerHit",
-	"Death",
-	"SoundGlobal",
-	"SoundWorld",
-	"DamageInd",
-	""
-};
-
-int CNetObjHandler::ms_aObjSizes[] = {
-	0,
-	sizeof(CNetObj_PlayerInput),
-	sizeof(CNetObj_Projectile),
-	sizeof(CNetObj_Laser),
-	sizeof(CNetObj_Pickup),
-	sizeof(CNetObj_Flag),
-	sizeof(CNetObj_GameInfo),
-	sizeof(CNetObj_GameData),
-	sizeof(CNetObj_CharacterCore),
-	sizeof(CNetObj_Character),
-	sizeof(CNetObj_PlayerInfo),
-	sizeof(CNetObj_ClientInfo),
-	sizeof(CNetObj_SpectatorInfo),
-	sizeof(CNetEvent_Common),
-	sizeof(CNetEvent_Explosion),
-	sizeof(CNetEvent_Spawn),
-	sizeof(CNetEvent_HammerHit),
-	sizeof(CNetEvent_Death),
-	sizeof(CNetEvent_SoundGlobal),
-	sizeof(CNetEvent_SoundWorld),
-	sizeof(CNetEvent_DamageInd),
-	0
-};
-
-const char *CNetObjHandler::ms_apMsgNames[] = {
-	"invalid",
-	"Sv_Motd",
-	"Sv_Broadcast",
-	"Sv_Chat",
-	"Sv_KillMsg",
-	"Sv_SoundGlobal",
-	"Sv_TuneParams",
-	"Sv_ExtraProjectile",
-	"Sv_ReadyToEnter",
-	"Sv_WeaponPickup",
-	"Sv_Emoticon",
-	"Sv_VoteClearOptions",
-	"Sv_VoteOptionListAdd",
-	"Sv_VoteOptionAdd",
-	"Sv_VoteOptionRemove",
-	"Sv_VoteSet",
-	"Sv_VoteStatus",
-	"Cl_Say",
-	"Cl_SetTeam",
-	"Cl_SetSpectatorMode",
-	"Cl_StartInfo",
-	"Cl_ChangeInfo",
-	"Cl_Kill",
-	"Cl_Emoticon",
-	"Cl_Vote",
-	"Cl_CallVote",
-	""
-};
-
-const char *CNetObjHandler::GetObjName(int Type)
-{
-	if(Type < 0 || Type >= NUM_NETOBJTYPES) return "(out of range)";
-	return ms_apObjNames[Type];
-};
-
-int CNetObjHandler::GetObjSize(int Type)
-{
-	if(Type < 0 || Type >= NUM_NETOBJTYPES) return 0;
-	return ms_aObjSizes[Type];
-};
-
-const char *CNetObjHandler::GetMsgName(int Type)
-{
-	if(Type < 0 || Type >= NUM_NETMSGTYPES) return "(out of range)";
-	return ms_apMsgNames[Type];
-};
-
-int CNetObjHandler::ValidateObj(int Type, void *pData, int Size)
-{
-	switch(Type)
-	{
-	case NETOBJTYPE_PLAYERINPUT:
-	{
-		CNetObj_PlayerInput *pObj = (CNetObj_PlayerInput *)pData;
-		if(sizeof(*pObj) != Size) return -1;
-		ClampInt("m_PlayerFlags", pObj->m_PlayerFlags, 0, 256);
-		return 0;
-	}
-	
-	case NETOBJTYPE_PROJECTILE:
-	{
-		CNetObj_Projectile *pObj = (CNetObj_Projectile *)pData;
-		if(sizeof(*pObj) != Size) return -1;
-		ClampInt("m_Type", pObj->m_Type, 0, NUM_WEAPONS-1);
-		ClampInt("m_StartTick", pObj->m_StartTick, 0, max_int);
-		return 0;
-	}
-	
-	case NETOBJTYPE_LASER:
-	{
-		CNetObj_Laser *pObj = (CNetObj_Laser *)pData;
-		if(sizeof(*pObj) != Size) return -1;
-		ClampInt("m_StartTick", pObj->m_StartTick, 0, max_int);
-		return 0;
-	}
-	
-	case NETOBJTYPE_PICKUP:
-	{
-		CNetObj_Pickup *pObj = (CNetObj_Pickup *)pData;
-		if(sizeof(*pObj) != Size) return -1;
-		ClampInt("m_Type", pObj->m_Type, 0, max_int);
-		ClampInt("m_Subtype", pObj->m_Subtype, 0, max_int);
-		return 0;
-	}
-	
-	case NETOBJTYPE_FLAG:
-	{
-		CNetObj_Flag *pObj = (CNetObj_Flag *)pData;
-		if(sizeof(*pObj) != Size) return -1;
-		ClampInt("m_Team", pObj->m_Team, TEAM_RED, TEAM_BLUE);
-		return 0;
-	}
-	
-	case NETOBJTYPE_GAMEINFO:
-	{
-		CNetObj_GameInfo *pObj = (CNetObj_GameInfo *)pData;
-		if(sizeof(*pObj) != Size) return -1;
-		ClampInt("m_GameFlags", pObj->m_GameFlags, 0, 256);
-		ClampInt("m_GameStateFlags", pObj->m_GameStateFlags, 0, 256);
-		ClampInt("m_RoundStartTick", pObj->m_RoundStartTick, 0, max_int);
-		ClampInt("m_WarmupTimer", pObj->m_WarmupTimer, 0, max_int);
-		ClampInt("m_ScoreLimit", pObj->m_ScoreLimit, 0, max_int);
-		ClampInt("m_TimeLimit", pObj->m_TimeLimit, 0, max_int);
-		ClampInt("m_RoundNum", pObj->m_RoundNum, 0, max_int);
-		ClampInt("m_RoundCurrent", pObj->m_RoundCurrent, 0, max_int);
-		return 0;
-	}
-	
-	case NETOBJTYPE_GAMEDATA:
-	{
-		CNetObj_GameData *pObj = (CNetObj_GameData *)pData;
-		if(sizeof(*pObj) != Size) return -1;
-		ClampInt("m_FlagCarrierRed", pObj->m_FlagCarrierRed, FLAG_MISSING, MAX_CLIENTS-1);
-		ClampInt("m_FlagCarrierBlue", pObj->m_FlagCarrierBlue, FLAG_MISSING, MAX_CLIENTS-1);
-		return 0;
-	}
-	
-	case NETOBJTYPE_CHARACTERCORE:
-	{
-		CNetObj_CharacterCore *pObj = (CNetObj_CharacterCore *)pData;
-		if(sizeof(*pObj) != Size) return -1;
-		ClampInt("m_Direction", pObj->m_Direction, -1, 1);
-		ClampInt("m_Jumped", pObj->m_Jumped, 0, 3);
-		ClampInt("m_HookedPlayer", pObj->m_HookedPlayer, 0, MAX_CLIENTS-1);
-		ClampInt("m_HookState", pObj->m_HookState, -1, 5);
-		ClampInt("m_HookTick", pObj->m_HookTick, 0, max_int);
-		return 0;
-	}
-	
-	case NETOBJTYPE_CHARACTER:
-	{
-		CNetObj_Character *pObj = (CNetObj_Character *)pData;
-		if(sizeof(*pObj) != Size) return -1;
-		ClampInt("m_PlayerFlags", pObj->m_PlayerFlags, 0, 256);
-		ClampInt("m_Health", pObj->m_Health, 0, 10);
-		ClampInt("m_Armor", pObj->m_Armor, 0, 10);
-		ClampInt("m_AmmoCount", pObj->m_AmmoCount, 0, 10);
-		ClampInt("m_Weapon", pObj->m_Weapon, 0, NUM_WEAPONS-1);
-		ClampInt("m_Emote", pObj->m_Emote, 0, 6);
-		ClampInt("m_AttackTick", pObj->m_AttackTick, 0, max_int);
-		return 0;
-	}
-	
-	case NETOBJTYPE_PLAYERINFO:
-	{
-		CNetObj_PlayerInfo *pObj = (CNetObj_PlayerInfo *)pData;
-		if(sizeof(*pObj) != Size) return -1;
-		ClampInt("m_Local", pObj->m_Local, 0, 1);
-		ClampInt("m_ClientID", pObj->m_ClientID, 0, MAX_CLIENTS-1);
-		ClampInt("m_Team", pObj->m_Team, TEAM_SPECTATORS, TEAM_BLUE);
-		return 0;
-	}
-	
-	case NETOBJTYPE_CLIENTINFO:
-	{
-		CNetObj_ClientInfo *pObj = (CNetObj_ClientInfo *)pData;
-		if(sizeof(*pObj) != Size) return -1;
-		ClampInt("m_UseCustomColor", pObj->m_UseCustomColor, 0, 1);
-		return 0;
-	}
-	
-	case NETOBJTYPE_SPECTATORINFO:
-	{
-		CNetObj_SpectatorInfo *pObj = (CNetObj_SpectatorInfo *)pData;
-		if(sizeof(*pObj) != Size) return -1;
-		ClampInt("m_SpectatorID", pObj->m_SpectatorID, SPEC_FREEVIEW, MAX_CLIENTS-1);
-		return 0;
-	}
-	
-	case NETEVENTTYPE_COMMON:
-	{
-		CNetEvent_Common *pObj = (CNetEvent_Common *)pData;
-		if(sizeof(*pObj) != Size) return -1;
-		return 0;
-	}
-	
-	case NETEVENTTYPE_EXPLOSION:
-	{
-		CNetEvent_Explosion *pObj = (CNetEvent_Explosion *)pData;
-		if(sizeof(*pObj) != Size) return -1;
-		return 0;
-	}
-	
-	case NETEVENTTYPE_SPAWN:
-	{
-		CNetEvent_Spawn *pObj = (CNetEvent_Spawn *)pData;
-		if(sizeof(*pObj) != Size) return -1;
-		return 0;
-	}
-	
-	case NETEVENTTYPE_HAMMERHIT:
-	{
-		CNetEvent_HammerHit *pObj = (CNetEvent_HammerHit *)pData;
-		if(sizeof(*pObj) != Size) return -1;
-		return 0;
-	}
-	
-	case NETEVENTTYPE_DEATH:
-	{
-		CNetEvent_Death *pObj = (CNetEvent_Death *)pData;
-		if(sizeof(*pObj) != Size) return -1;
-		ClampInt("m_ClientID", pObj->m_ClientID, 0, MAX_CLIENTS-1);
-		return 0;
-	}
-	
-	case NETEVENTTYPE_SOUNDGLOBAL:
-	{
-		CNetEvent_SoundGlobal *pObj = (CNetEvent_SoundGlobal *)pData;
-		if(sizeof(*pObj) != Size) return -1;
-		ClampInt("m_SoundID", pObj->m_SoundID, 0, NUM_SOUNDS-1);
-		return 0;
-	}
-	
-	case NETEVENTTYPE_SOUNDWORLD:
-	{
-		CNetEvent_SoundWorld *pObj = (CNetEvent_SoundWorld *)pData;
-		if(sizeof(*pObj) != Size) return -1;
-		ClampInt("m_SoundID", pObj->m_SoundID, 0, NUM_SOUNDS-1);
-		return 0;
-	}
-	
-	case NETEVENTTYPE_DAMAGEIND:
-	{
-		CNetEvent_DamageInd *pObj = (CNetEvent_DamageInd *)pData;
-		if(sizeof(*pObj) != Size) return -1;
-		return 0;
-	}
-	
-	}
-	return -1;
-};
-
-void *CNetObjHandler::SecureUnpackMsg(int Type, CUnpacker *pUnpacker)
-{
-	m_pMsgFailedOn = 0;
-	switch(Type)
-	{
-	case NETMSGTYPE_SV_MOTD:
-	{
-		CNetMsg_Sv_Motd *pMsg = (CNetMsg_Sv_Motd *)m_aMsgData;
-		(void)pMsg;
-		pMsg->m_pMessage = pUnpacker->GetString();
-	} break;
-	
-	case NETMSGTYPE_SV_BROADCAST:
-	{
-		CNetMsg_Sv_Broadcast *pMsg = (CNetMsg_Sv_Broadcast *)m_aMsgData;
-		(void)pMsg;
-		pMsg->m_pMessage = pUnpacker->GetString();
-	} break;
-	
-	case NETMSGTYPE_SV_CHAT:
-	{
-		CNetMsg_Sv_Chat *pMsg = (CNetMsg_Sv_Chat *)m_aMsgData;
-		(void)pMsg;
-		pMsg->m_Team = pUnpacker->GetInt();
-		pMsg->m_ClientID = pUnpacker->GetInt();
-		pMsg->m_pMessage = pUnpacker->GetString();
-		if(pMsg->m_Team < TEAM_SPECTATORS || pMsg->m_Team > TEAM_BLUE) { m_pMsgFailedOn = "m_Team"; break; }
-		if(pMsg->m_ClientID < -1 || pMsg->m_ClientID > MAX_CLIENTS-1) { m_pMsgFailedOn = "m_ClientID"; break; }
-	} break;
-	
-	case NETMSGTYPE_SV_KILLMSG:
-	{
-		CNetMsg_Sv_KillMsg *pMsg = (CNetMsg_Sv_KillMsg *)m_aMsgData;
-		(void)pMsg;
-		pMsg->m_Killer = pUnpacker->GetInt();
-		pMsg->m_Victim = pUnpacker->GetInt();
-		pMsg->m_Weapon = pUnpacker->GetInt();
-		pMsg->m_ModeSpecial = pUnpacker->GetInt();
-		if(pMsg->m_Killer < 0 || pMsg->m_Killer > MAX_CLIENTS-1) { m_pMsgFailedOn = "m_Killer"; break; }
-		if(pMsg->m_Victim < 0 || pMsg->m_Victim > MAX_CLIENTS-1) { m_pMsgFailedOn = "m_Victim"; break; }
-		if(pMsg->m_Weapon < -3 || pMsg->m_Weapon > NUM_WEAPONS-1) { m_pMsgFailedOn = "m_Weapon"; break; }
-	} break;
-	
-	case NETMSGTYPE_SV_SOUNDGLOBAL:
-	{
-		CNetMsg_Sv_SoundGlobal *pMsg = (CNetMsg_Sv_SoundGlobal *)m_aMsgData;
-		(void)pMsg;
-		pMsg->m_SoundID = pUnpacker->GetInt();
-		if(pMsg->m_SoundID < 0 || pMsg->m_SoundID > NUM_SOUNDS-1) { m_pMsgFailedOn = "m_SoundID"; break; }
-	} break;
-	
-	case NETMSGTYPE_SV_TUNEPARAMS:
-	{
-		CNetMsg_Sv_TuneParams *pMsg = (CNetMsg_Sv_TuneParams *)m_aMsgData;
-		(void)pMsg;
-	} break;
-	
-	case NETMSGTYPE_SV_EXTRAPROJECTILE:
-	{
-		CNetMsg_Sv_ExtraProjectile *pMsg = (CNetMsg_Sv_ExtraProjectile *)m_aMsgData;
-		(void)pMsg;
-	} break;
-	
-	case NETMSGTYPE_SV_READYTOENTER:
-	{
-		CNetMsg_Sv_ReadyToEnter *pMsg = (CNetMsg_Sv_ReadyToEnter *)m_aMsgData;
-		(void)pMsg;
-	} break;
-	
-	case NETMSGTYPE_SV_WEAPONPICKUP:
-	{
-		CNetMsg_Sv_WeaponPickup *pMsg = (CNetMsg_Sv_WeaponPickup *)m_aMsgData;
-		(void)pMsg;
-		pMsg->m_Weapon = pUnpacker->GetInt();
-		if(pMsg->m_Weapon < 0 || pMsg->m_Weapon > NUM_WEAPONS-1) { m_pMsgFailedOn = "m_Weapon"; break; }
-	} break;
-	
-	case NETMSGTYPE_SV_EMOTICON:
-	{
-		CNetMsg_Sv_Emoticon *pMsg = (CNetMsg_Sv_Emoticon *)m_aMsgData;
-		(void)pMsg;
-		pMsg->m_ClientID = pUnpacker->GetInt();
-		pMsg->m_Emoticon = pUnpacker->GetInt();
-		if(pMsg->m_ClientID < 0 || pMsg->m_ClientID > MAX_CLIENTS-1) { m_pMsgFailedOn = "m_ClientID"; break; }
-		if(pMsg->m_Emoticon < 0 || pMsg->m_Emoticon > NUM_EMOTICONS-1) { m_pMsgFailedOn = "m_Emoticon"; break; }
-	} break;
-	
-	case NETMSGTYPE_SV_VOTECLEAROPTIONS:
-	{
-		CNetMsg_Sv_VoteClearOptions *pMsg = (CNetMsg_Sv_VoteClearOptions *)m_aMsgData;
-		(void)pMsg;
-	} break;
-	
-	case NETMSGTYPE_SV_VOTEOPTIONLISTADD:
-	{
-		CNetMsg_Sv_VoteOptionListAdd *pMsg = (CNetMsg_Sv_VoteOptionListAdd *)m_aMsgData;
-		(void)pMsg;
-		pMsg->m_NumOptions = pUnpacker->GetInt();
-		pMsg->m_pDescription0 = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		pMsg->m_pDescription1 = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		pMsg->m_pDescription2 = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		pMsg->m_pDescription3 = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		pMsg->m_pDescription4 = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		pMsg->m_pDescription5 = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		pMsg->m_pDescription6 = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		pMsg->m_pDescription7 = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		pMsg->m_pDescription8 = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		pMsg->m_pDescription9 = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		pMsg->m_pDescription10 = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		pMsg->m_pDescription11 = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		pMsg->m_pDescription12 = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		pMsg->m_pDescription13 = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		pMsg->m_pDescription14 = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		if(pMsg->m_NumOptions < 1 || pMsg->m_NumOptions > 15) { m_pMsgFailedOn = "m_NumOptions"; break; }
-	} break;
-	
-	case NETMSGTYPE_SV_VOTEOPTIONADD:
-	{
-		CNetMsg_Sv_VoteOptionAdd *pMsg = (CNetMsg_Sv_VoteOptionAdd *)m_aMsgData;
-		(void)pMsg;
-		pMsg->m_pDescription = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-	} break;
-	
-	case NETMSGTYPE_SV_VOTEOPTIONREMOVE:
-	{
-		CNetMsg_Sv_VoteOptionRemove *pMsg = (CNetMsg_Sv_VoteOptionRemove *)m_aMsgData;
-		(void)pMsg;
-		pMsg->m_pDescription = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-	} break;
-	
-	case NETMSGTYPE_SV_VOTESET:
-	{
-		CNetMsg_Sv_VoteSet *pMsg = (CNetMsg_Sv_VoteSet *)m_aMsgData;
-		(void)pMsg;
-		pMsg->m_Timeout = pUnpacker->GetInt();
-		pMsg->m_pDescription = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		pMsg->m_pReason = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		if(pMsg->m_Timeout < 0 || pMsg->m_Timeout > 60) { m_pMsgFailedOn = "m_Timeout"; break; }
-	} break;
-	
-	case NETMSGTYPE_SV_VOTESTATUS:
-	{
-		CNetMsg_Sv_VoteStatus *pMsg = (CNetMsg_Sv_VoteStatus *)m_aMsgData;
-		(void)pMsg;
-		pMsg->m_Yes = pUnpacker->GetInt();
-		pMsg->m_No = pUnpacker->GetInt();
-		pMsg->m_Pass = pUnpacker->GetInt();
-		pMsg->m_Total = pUnpacker->GetInt();
-		if(pMsg->m_Yes < 0 || pMsg->m_Yes > MAX_CLIENTS) { m_pMsgFailedOn = "m_Yes"; break; }
-		if(pMsg->m_No < 0 || pMsg->m_No > MAX_CLIENTS) { m_pMsgFailedOn = "m_No"; break; }
-		if(pMsg->m_Pass < 0 || pMsg->m_Pass > MAX_CLIENTS) { m_pMsgFailedOn = "m_Pass"; break; }
-		if(pMsg->m_Total < 0 || pMsg->m_Total > MAX_CLIENTS) { m_pMsgFailedOn = "m_Total"; break; }
-	} break;
-	
-	case NETMSGTYPE_CL_SAY:
-	{
-		CNetMsg_Cl_Say *pMsg = (CNetMsg_Cl_Say *)m_aMsgData;
-		(void)pMsg;
-		pMsg->m_Team = pUnpacker->GetInt();
-		pMsg->m_pMessage = pUnpacker->GetString();
-		if(pMsg->m_Team < 0 || pMsg->m_Team > 1) { m_pMsgFailedOn = "m_Team"; break; }
-	} break;
-	
-	case NETMSGTYPE_CL_SETTEAM:
-	{
-		CNetMsg_Cl_SetTeam *pMsg = (CNetMsg_Cl_SetTeam *)m_aMsgData;
-		(void)pMsg;
-		pMsg->m_Team = pUnpacker->GetInt();
-		if(pMsg->m_Team < TEAM_SPECTATORS || pMsg->m_Team > TEAM_BLUE) { m_pMsgFailedOn = "m_Team"; break; }
-	} break;
-	
-	case NETMSGTYPE_CL_SETSPECTATORMODE:
-	{
-		CNetMsg_Cl_SetSpectatorMode *pMsg = (CNetMsg_Cl_SetSpectatorMode *)m_aMsgData;
-		(void)pMsg;
-		pMsg->m_SpectatorID = pUnpacker->GetInt();
-		if(pMsg->m_SpectatorID < SPEC_FREEVIEW || pMsg->m_SpectatorID > MAX_CLIENTS-1) { m_pMsgFailedOn = "m_SpectatorID"; break; }
-	} break;
-	
-	case NETMSGTYPE_CL_STARTINFO:
-	{
-		CNetMsg_Cl_StartInfo *pMsg = (CNetMsg_Cl_StartInfo *)m_aMsgData;
-		(void)pMsg;
-		pMsg->m_pName = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		pMsg->m_pClan = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		pMsg->m_Country = pUnpacker->GetInt();
-		pMsg->m_pSkin = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		pMsg->m_UseCustomColor = pUnpacker->GetInt();
-		pMsg->m_ColorBody = pUnpacker->GetInt();
-		pMsg->m_ColorFeet = pUnpacker->GetInt();
-		if(pMsg->m_UseCustomColor < 0 || pMsg->m_UseCustomColor > 1) { m_pMsgFailedOn = "m_UseCustomColor"; break; }
-	} break;
-	
-	case NETMSGTYPE_CL_CHANGEINFO:
-	{
-		CNetMsg_Cl_ChangeInfo *pMsg = (CNetMsg_Cl_ChangeInfo *)m_aMsgData;
-		(void)pMsg;
-		pMsg->m_pName = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		pMsg->m_pClan = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		pMsg->m_Country = pUnpacker->GetInt();
-		pMsg->m_pSkin = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		pMsg->m_UseCustomColor = pUnpacker->GetInt();
-		pMsg->m_ColorBody = pUnpacker->GetInt();
-		pMsg->m_ColorFeet = pUnpacker->GetInt();
-		if(pMsg->m_UseCustomColor < 0 || pMsg->m_UseCustomColor > 1) { m_pMsgFailedOn = "m_UseCustomColor"; break; }
-	} break;
-	
-	case NETMSGTYPE_CL_KILL:
-	{
-		CNetMsg_Cl_Kill *pMsg = (CNetMsg_Cl_Kill *)m_aMsgData;
-		(void)pMsg;
-	} break;
-	
-	case NETMSGTYPE_CL_EMOTICON:
-	{
-		CNetMsg_Cl_Emoticon *pMsg = (CNetMsg_Cl_Emoticon *)m_aMsgData;
-		(void)pMsg;
-		pMsg->m_Emoticon = pUnpacker->GetInt();
-		if(pMsg->m_Emoticon < 0 || pMsg->m_Emoticon > NUM_EMOTICONS-1) { m_pMsgFailedOn = "m_Emoticon"; break; }
-	} break;
-	
-	case NETMSGTYPE_CL_VOTE:
-	{
-		CNetMsg_Cl_Vote *pMsg = (CNetMsg_Cl_Vote *)m_aMsgData;
-		(void)pMsg;
-		pMsg->m_Vote = pUnpacker->GetInt();
-		if(pMsg->m_Vote < -1 || pMsg->m_Vote > 1) { m_pMsgFailedOn = "m_Vote"; break; }
-	} break;
-	
-	case NETMSGTYPE_CL_CALLVOTE:
-	{
-		CNetMsg_Cl_CallVote *pMsg = (CNetMsg_Cl_CallVote *)m_aMsgData;
-		(void)pMsg;
-		pMsg->m_Type = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		pMsg->m_Value = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-		pMsg->m_Reason = pUnpacker->GetString(CUnpacker::SANITIZE_CC|CUnpacker::SKIP_START_WHITESPACES);
-	} break;
-	
-	default:
-		m_pMsgFailedOn = "(type out of range)";
-		break;
-	}
-	
-	if(pUnpacker->Error())
-		m_pMsgFailedOn = "(unpack error)";
-	
-	if(m_pMsgFailedOn)
-		return 0;
-	m_pMsgFailedOn = "";
-	return m_aMsgData;
-};
-
diff -rupN teeworlds-b177-r50edfd37-source/src//game/generated/protocol.h alien-rc4/src//game/generated/protocol.h
--- teeworlds-b177-r50edfd37-source/src//game/generated/protocol.h	2012-01-27 22:23:46.000000000 +0100
+++ alien-rc4/src//game/generated/protocol.h	1970-01-01 01:00:00.000000000 +0100
@@ -1,773 +0,0 @@
-#ifndef GAME_GENERATED_PROTOCOL_H
-#define GAME_GENERATED_PROTOCOL_H
-
-
-#include <engine/message.h>
-
-enum
-{
-	INPUT_STATE_MASK=0x3f
-};
-
-enum
-{
-	TEAM_SPECTATORS=-1,
-	TEAM_RED,
-	TEAM_BLUE,
-
-	FLAG_MISSING=-3,
-	FLAG_ATSTAND,
-	FLAG_TAKEN,
-
-	SPEC_FREEVIEW=-1,
-};
-
-enum
-{
-	EMOTE_NORMAL=0,
-	EMOTE_PAIN,
-	EMOTE_HAPPY,
-	EMOTE_SURPRISE,
-	EMOTE_ANGRY,
-	EMOTE_BLINK,
-	NUM_EMOTES
-};
-
-enum
-{
-	POWERUP_HEALTH=0,
-	POWERUP_ARMOR,
-	POWERUP_WEAPON,
-	POWERUP_NINJA,
-	NUM_POWERUPS
-};
-
-enum
-{
-	EMOTICON_OOP=0,
-	EMOTICON_EXCLAMATION,
-	EMOTICON_HEARTS,
-	EMOTICON_DROP,
-	EMOTICON_DOTDOT,
-	EMOTICON_MUSIC,
-	EMOTICON_SORRY,
-	EMOTICON_GHOST,
-	EMOTICON_SUSHI,
-	EMOTICON_SPLATTEE,
-	EMOTICON_DEVILTEE,
-	EMOTICON_ZOMG,
-	EMOTICON_ZZZ,
-	EMOTICON_WTF,
-	EMOTICON_EYES,
-	EMOTICON_QUESTION,
-	NUM_EMOTICONS
-};
-
-enum
-{
-	PLAYERFLAG_PLAYING = 1<<0,
-	PLAYERFLAG_IN_MENU = 1<<1,
-	PLAYERFLAG_CHATTING = 1<<2,
-	PLAYERFLAG_SCOREBOARD = 1<<3,
-};
-
-enum
-{
-	GAMEFLAG_TEAMS = 1<<0,
-	GAMEFLAG_FLAGS = 1<<1,
-};
-
-enum
-{
-	GAMESTATEFLAG_GAMEOVER = 1<<0,
-	GAMESTATEFLAG_SUDDENDEATH = 1<<1,
-	GAMESTATEFLAG_PAUSED = 1<<2,
-};
-
-enum
-{
-	NETOBJ_INVALID=0,
-	NETOBJTYPE_PLAYERINPUT,
-	NETOBJTYPE_PROJECTILE,
-	NETOBJTYPE_LASER,
-	NETOBJTYPE_PICKUP,
-	NETOBJTYPE_FLAG,
-	NETOBJTYPE_GAMEINFO,
-	NETOBJTYPE_GAMEDATA,
-	NETOBJTYPE_CHARACTERCORE,
-	NETOBJTYPE_CHARACTER,
-	NETOBJTYPE_PLAYERINFO,
-	NETOBJTYPE_CLIENTINFO,
-	NETOBJTYPE_SPECTATORINFO,
-	NETEVENTTYPE_COMMON,
-	NETEVENTTYPE_EXPLOSION,
-	NETEVENTTYPE_SPAWN,
-	NETEVENTTYPE_HAMMERHIT,
-	NETEVENTTYPE_DEATH,
-	NETEVENTTYPE_SOUNDGLOBAL,
-	NETEVENTTYPE_SOUNDWORLD,
-	NETEVENTTYPE_DAMAGEIND,
-	NUM_NETOBJTYPES
-};
-
-enum
-{
-	NETMSG_INVALID=0,
-	NETMSGTYPE_SV_MOTD,
-	NETMSGTYPE_SV_BROADCAST,
-	NETMSGTYPE_SV_CHAT,
-	NETMSGTYPE_SV_KILLMSG,
-	NETMSGTYPE_SV_SOUNDGLOBAL,
-	NETMSGTYPE_SV_TUNEPARAMS,
-	NETMSGTYPE_SV_EXTRAPROJECTILE,
-	NETMSGTYPE_SV_READYTOENTER,
-	NETMSGTYPE_SV_WEAPONPICKUP,
-	NETMSGTYPE_SV_EMOTICON,
-	NETMSGTYPE_SV_VOTECLEAROPTIONS,
-	NETMSGTYPE_SV_VOTEOPTIONLISTADD,
-	NETMSGTYPE_SV_VOTEOPTIONADD,
-	NETMSGTYPE_SV_VOTEOPTIONREMOVE,
-	NETMSGTYPE_SV_VOTESET,
-	NETMSGTYPE_SV_VOTESTATUS,
-	NETMSGTYPE_CL_SAY,
-	NETMSGTYPE_CL_SETTEAM,
-	NETMSGTYPE_CL_SETSPECTATORMODE,
-	NETMSGTYPE_CL_STARTINFO,
-	NETMSGTYPE_CL_CHANGEINFO,
-	NETMSGTYPE_CL_KILL,
-	NETMSGTYPE_CL_EMOTICON,
-	NETMSGTYPE_CL_VOTE,
-	NETMSGTYPE_CL_CALLVOTE,
-	NUM_NETMSGTYPES
-};
-
-struct CNetObj_PlayerInput
-{
-	int m_Direction;
-	int m_TargetX;
-	int m_TargetY;
-	int m_Jump;
-	int m_Fire;
-	int m_Hook;
-	int m_PlayerFlags;
-	int m_WantedWeapon;
-	int m_NextWeapon;
-	int m_PrevWeapon;
-};
-
-struct CNetObj_Projectile
-{
-	int m_X;
-	int m_Y;
-	int m_VelX;
-	int m_VelY;
-	int m_Type;
-	int m_StartTick;
-};
-
-struct CNetObj_Laser
-{
-	int m_X;
-	int m_Y;
-	int m_FromX;
-	int m_FromY;
-	int m_StartTick;
-};
-
-struct CNetObj_Pickup
-{
-	int m_X;
-	int m_Y;
-	int m_Type;
-	int m_Subtype;
-};
-
-struct CNetObj_Flag
-{
-	int m_X;
-	int m_Y;
-	int m_Team;
-};
-
-struct CNetObj_GameInfo
-{
-	int m_GameFlags;
-	int m_GameStateFlags;
-	int m_RoundStartTick;
-	int m_WarmupTimer;
-	int m_ScoreLimit;
-	int m_TimeLimit;
-	int m_RoundNum;
-	int m_RoundCurrent;
-};
-
-struct CNetObj_GameData
-{
-	int m_TeamscoreRed;
-	int m_TeamscoreBlue;
-	int m_FlagCarrierRed;
-	int m_FlagCarrierBlue;
-};
-
-struct CNetObj_CharacterCore
-{
-	int m_Tick;
-	int m_X;
-	int m_Y;
-	int m_VelX;
-	int m_VelY;
-	int m_Angle;
-	int m_Direction;
-	int m_Jumped;
-	int m_HookedPlayer;
-	int m_HookState;
-	int m_HookTick;
-	int m_HookX;
-	int m_HookY;
-	int m_HookDx;
-	int m_HookDy;
-};
-
-struct CNetObj_Character : public CNetObj_CharacterCore
-{
-	int m_PlayerFlags;
-	int m_Health;
-	int m_Armor;
-	int m_AmmoCount;
-	int m_Weapon;
-	int m_Emote;
-	int m_AttackTick;
-};
-
-struct CNetObj_PlayerInfo
-{
-	int m_Local;
-	int m_ClientID;
-	int m_Team;
-	int m_Score;
-	int m_Latency;
-};
-
-struct CNetObj_ClientInfo
-{
-	int m_Name0;
-	int m_Name1;
-	int m_Name2;
-	int m_Name3;
-	int m_Clan0;
-	int m_Clan1;
-	int m_Clan2;
-	int m_Country;
-	int m_Skin0;
-	int m_Skin1;
-	int m_Skin2;
-	int m_Skin3;
-	int m_Skin4;
-	int m_Skin5;
-	int m_UseCustomColor;
-	int m_ColorBody;
-	int m_ColorFeet;
-};
-
-struct CNetObj_SpectatorInfo
-{
-	int m_SpectatorID;
-	int m_X;
-	int m_Y;
-};
-
-struct CNetEvent_Common
-{
-	int m_X;
-	int m_Y;
-};
-
-struct CNetEvent_Explosion : public CNetEvent_Common
-{
-};
-
-struct CNetEvent_Spawn : public CNetEvent_Common
-{
-};
-
-struct CNetEvent_HammerHit : public CNetEvent_Common
-{
-};
-
-struct CNetEvent_Death : public CNetEvent_Common
-{
-	int m_ClientID;
-};
-
-struct CNetEvent_SoundGlobal : public CNetEvent_Common
-{
-	int m_SoundID;
-};
-
-struct CNetEvent_SoundWorld : public CNetEvent_Common
-{
-	int m_SoundID;
-};
-
-struct CNetEvent_DamageInd : public CNetEvent_Common
-{
-	int m_Angle;
-};
-
-struct CNetMsg_Sv_Motd
-{
-	const char *m_pMessage;
-	int MsgID() const { return NETMSGTYPE_SV_MOTD; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		pPacker->AddString(m_pMessage, -1);
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Sv_Broadcast
-{
-	const char *m_pMessage;
-	int MsgID() const { return NETMSGTYPE_SV_BROADCAST; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		pPacker->AddString(m_pMessage, -1);
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Sv_Chat
-{
-	int m_Team;
-	int m_ClientID;
-	const char *m_pMessage;
-	int MsgID() const { return NETMSGTYPE_SV_CHAT; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		pPacker->AddInt(m_Team);
-		pPacker->AddInt(m_ClientID);
-		pPacker->AddString(m_pMessage, -1);
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Sv_KillMsg
-{
-	int m_Killer;
-	int m_Victim;
-	int m_Weapon;
-	int m_ModeSpecial;
-	int MsgID() const { return NETMSGTYPE_SV_KILLMSG; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		pPacker->AddInt(m_Killer);
-		pPacker->AddInt(m_Victim);
-		pPacker->AddInt(m_Weapon);
-		pPacker->AddInt(m_ModeSpecial);
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Sv_SoundGlobal
-{
-	int m_SoundID;
-	int MsgID() const { return NETMSGTYPE_SV_SOUNDGLOBAL; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		pPacker->AddInt(m_SoundID);
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Sv_TuneParams
-{
-	int MsgID() const { return NETMSGTYPE_SV_TUNEPARAMS; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Sv_ExtraProjectile
-{
-	int MsgID() const { return NETMSGTYPE_SV_EXTRAPROJECTILE; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Sv_ReadyToEnter
-{
-	int MsgID() const { return NETMSGTYPE_SV_READYTOENTER; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Sv_WeaponPickup
-{
-	int m_Weapon;
-	int MsgID() const { return NETMSGTYPE_SV_WEAPONPICKUP; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		pPacker->AddInt(m_Weapon);
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Sv_Emoticon
-{
-	int m_ClientID;
-	int m_Emoticon;
-	int MsgID() const { return NETMSGTYPE_SV_EMOTICON; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		pPacker->AddInt(m_ClientID);
-		pPacker->AddInt(m_Emoticon);
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Sv_VoteClearOptions
-{
-	int MsgID() const { return NETMSGTYPE_SV_VOTECLEAROPTIONS; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Sv_VoteOptionListAdd
-{
-	int m_NumOptions;
-	const char *m_pDescription0;
-	const char *m_pDescription1;
-	const char *m_pDescription2;
-	const char *m_pDescription3;
-	const char *m_pDescription4;
-	const char *m_pDescription5;
-	const char *m_pDescription6;
-	const char *m_pDescription7;
-	const char *m_pDescription8;
-	const char *m_pDescription9;
-	const char *m_pDescription10;
-	const char *m_pDescription11;
-	const char *m_pDescription12;
-	const char *m_pDescription13;
-	const char *m_pDescription14;
-	int MsgID() const { return NETMSGTYPE_SV_VOTEOPTIONLISTADD; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		pPacker->AddInt(m_NumOptions);
-		pPacker->AddString(m_pDescription0, -1);
-		pPacker->AddString(m_pDescription1, -1);
-		pPacker->AddString(m_pDescription2, -1);
-		pPacker->AddString(m_pDescription3, -1);
-		pPacker->AddString(m_pDescription4, -1);
-		pPacker->AddString(m_pDescription5, -1);
-		pPacker->AddString(m_pDescription6, -1);
-		pPacker->AddString(m_pDescription7, -1);
-		pPacker->AddString(m_pDescription8, -1);
-		pPacker->AddString(m_pDescription9, -1);
-		pPacker->AddString(m_pDescription10, -1);
-		pPacker->AddString(m_pDescription11, -1);
-		pPacker->AddString(m_pDescription12, -1);
-		pPacker->AddString(m_pDescription13, -1);
-		pPacker->AddString(m_pDescription14, -1);
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Sv_VoteOptionAdd
-{
-	const char *m_pDescription;
-	int MsgID() const { return NETMSGTYPE_SV_VOTEOPTIONADD; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		pPacker->AddString(m_pDescription, -1);
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Sv_VoteOptionRemove
-{
-	const char *m_pDescription;
-	int MsgID() const { return NETMSGTYPE_SV_VOTEOPTIONREMOVE; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		pPacker->AddString(m_pDescription, -1);
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Sv_VoteSet
-{
-	int m_Timeout;
-	const char *m_pDescription;
-	const char *m_pReason;
-	int MsgID() const { return NETMSGTYPE_SV_VOTESET; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		pPacker->AddInt(m_Timeout);
-		pPacker->AddString(m_pDescription, -1);
-		pPacker->AddString(m_pReason, -1);
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Sv_VoteStatus
-{
-	int m_Yes;
-	int m_No;
-	int m_Pass;
-	int m_Total;
-	int MsgID() const { return NETMSGTYPE_SV_VOTESTATUS; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		pPacker->AddInt(m_Yes);
-		pPacker->AddInt(m_No);
-		pPacker->AddInt(m_Pass);
-		pPacker->AddInt(m_Total);
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Cl_Say
-{
-	int m_Team;
-	const char *m_pMessage;
-	int MsgID() const { return NETMSGTYPE_CL_SAY; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		pPacker->AddInt(m_Team);
-		pPacker->AddString(m_pMessage, -1);
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Cl_SetTeam
-{
-	int m_Team;
-	int MsgID() const { return NETMSGTYPE_CL_SETTEAM; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		pPacker->AddInt(m_Team);
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Cl_SetSpectatorMode
-{
-	int m_SpectatorID;
-	int MsgID() const { return NETMSGTYPE_CL_SETSPECTATORMODE; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		pPacker->AddInt(m_SpectatorID);
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Cl_StartInfo
-{
-	const char *m_pName;
-	const char *m_pClan;
-	int m_Country;
-	const char *m_pSkin;
-	int m_UseCustomColor;
-	int m_ColorBody;
-	int m_ColorFeet;
-	int MsgID() const { return NETMSGTYPE_CL_STARTINFO; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		pPacker->AddString(m_pName, -1);
-		pPacker->AddString(m_pClan, -1);
-		pPacker->AddInt(m_Country);
-		pPacker->AddString(m_pSkin, -1);
-		pPacker->AddInt(m_UseCustomColor);
-		pPacker->AddInt(m_ColorBody);
-		pPacker->AddInt(m_ColorFeet);
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Cl_ChangeInfo
-{
-	const char *m_pName;
-	const char *m_pClan;
-	int m_Country;
-	const char *m_pSkin;
-	int m_UseCustomColor;
-	int m_ColorBody;
-	int m_ColorFeet;
-	int MsgID() const { return NETMSGTYPE_CL_CHANGEINFO; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		pPacker->AddString(m_pName, -1);
-		pPacker->AddString(m_pClan, -1);
-		pPacker->AddInt(m_Country);
-		pPacker->AddString(m_pSkin, -1);
-		pPacker->AddInt(m_UseCustomColor);
-		pPacker->AddInt(m_ColorBody);
-		pPacker->AddInt(m_ColorFeet);
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Cl_Kill
-{
-	int MsgID() const { return NETMSGTYPE_CL_KILL; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Cl_Emoticon
-{
-	int m_Emoticon;
-	int MsgID() const { return NETMSGTYPE_CL_EMOTICON; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		pPacker->AddInt(m_Emoticon);
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Cl_Vote
-{
-	int m_Vote;
-	int MsgID() const { return NETMSGTYPE_CL_VOTE; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		pPacker->AddInt(m_Vote);
-		return pPacker->Error() != 0;
-	}
-};
-
-struct CNetMsg_Cl_CallVote
-{
-	const char *m_Type;
-	const char *m_Value;
-	const char *m_Reason;
-	int MsgID() const { return NETMSGTYPE_CL_CALLVOTE; }
-	
-	bool Pack(CMsgPacker *pPacker)
-	{
-		pPacker->AddString(m_Type, -1);
-		pPacker->AddString(m_Value, -1);
-		pPacker->AddString(m_Reason, -1);
-		return pPacker->Error() != 0;
-	}
-};
-
-enum
-{
-	SOUND_GUN_FIRE=0,
-	SOUND_SHOTGUN_FIRE,
-	SOUND_GRENADE_FIRE,
-	SOUND_HAMMER_FIRE,
-	SOUND_HAMMER_HIT,
-	SOUND_NINJA_FIRE,
-	SOUND_GRENADE_EXPLODE,
-	SOUND_NINJA_HIT,
-	SOUND_RIFLE_FIRE,
-	SOUND_RIFLE_BOUNCE,
-	SOUND_WEAPON_SWITCH,
-	SOUND_PLAYER_PAIN_SHORT,
-	SOUND_PLAYER_PAIN_LONG,
-	SOUND_BODY_LAND,
-	SOUND_PLAYER_AIRJUMP,
-	SOUND_PLAYER_JUMP,
-	SOUND_PLAYER_DIE,
-	SOUND_PLAYER_SPAWN,
-	SOUND_PLAYER_SKID,
-	SOUND_TEE_CRY,
-	SOUND_HOOK_LOOP,
-	SOUND_HOOK_ATTACH_GROUND,
-	SOUND_HOOK_ATTACH_PLAYER,
-	SOUND_HOOK_NOATTACH,
-	SOUND_PICKUP_HEALTH,
-	SOUND_PICKUP_ARMOR,
-	SOUND_PICKUP_GRENADE,
-	SOUND_PICKUP_SHOTGUN,
-	SOUND_PICKUP_NINJA,
-	SOUND_WEAPON_SPAWN,
-	SOUND_WEAPON_NOAMMO,
-	SOUND_HIT,
-	SOUND_CHAT_SERVER,
-	SOUND_CHAT_CLIENT,
-	SOUND_CHAT_HIGHLIGHT,
-	SOUND_CTF_DROP,
-	SOUND_CTF_RETURN,
-	SOUND_CTF_GRAB_PL,
-	SOUND_CTF_GRAB_EN,
-	SOUND_CTF_CAPTURE,
-	SOUND_MENU,
-	NUM_SOUNDS
-};
-enum
-{
-	WEAPON_HAMMER=0,
-	WEAPON_GUN,
-	WEAPON_SHOTGUN,
-	WEAPON_GRENADE,
-	WEAPON_RIFLE,
-	WEAPON_NINJA,
-	NUM_WEAPONS
-};
-
-
-class CNetObjHandler
-{
-	const char *m_pMsgFailedOn;
-	const char *m_pObjCorrectedOn;
-	char m_aMsgData[1024];
-	int m_NumObjCorrections;
-	int ClampInt(const char *pErrorMsg, int Value, int Min, int Max);
-
-	static const char *ms_apObjNames[];
-	static int ms_aObjSizes[];
-	static const char *ms_apMsgNames[];
-
-public:
-	CNetObjHandler();
-
-	int ValidateObj(int Type, void *pData, int Size);
-	const char *GetObjName(int Type);
-	int GetObjSize(int Type);
-	int NumObjCorrections();
-	const char *CorrectedObjOn();
-
-	const char *GetMsgName(int Type);
-	void *SecureUnpackMsg(int Type, CUnpacker *pUnpacker);
-	const char *FailedMsgOn();
-};
-
-
-#endif // GAME_GENERATED_PROTOCOL_H
diff -rupN teeworlds-b177-r50edfd37-source/src//game/generated/server_data.cpp alien-rc4/src//game/generated/server_data.cpp
--- teeworlds-b177-r50edfd37-source/src//game/generated/server_data.cpp	2012-01-27 22:23:51.000000000 +0100
+++ alien-rc4/src//game/generated/server_data.cpp	1970-01-01 01:00:00.000000000 +0100
@@ -1,501 +0,0 @@
-#include "server_data.h"
-static CDataSound x1893[] = {
-	/* x1893[0] */ {  0,  "audio/wp_gun_fire-01.wv", },
-	/* x1893[1] */ {  0,  "audio/wp_gun_fire-02.wv", },
-	/* x1893[2] */ {  0,  "audio/wp_gun_fire-03.wv", },
-};
-static CDataSound x1909[] = {
-	/* x1909[0] */ {  0,  "audio/wp_shotty_fire-01.wv", },
-	/* x1909[1] */ {  0,  "audio/wp_shotty_fire-02.wv", },
-	/* x1909[2] */ {  0,  "audio/wp_shotty_fire-03.wv", },
-};
-static CDataSound x1925[] = {
-	/* x1925[0] */ {  0,  "audio/wp_flump_launch-01.wv", },
-	/* x1925[1] */ {  0,  "audio/wp_flump_launch-02.wv", },
-	/* x1925[2] */ {  0,  "audio/wp_flump_launch-03.wv", },
-};
-static CDataSound x1941[] = {
-	/* x1941[0] */ {  0,  "audio/wp_hammer_swing-01.wv", },
-	/* x1941[1] */ {  0,  "audio/wp_hammer_swing-02.wv", },
-	/* x1941[2] */ {  0,  "audio/wp_hammer_swing-03.wv", },
-};
-static CDataSound x1957[] = {
-	/* x1957[0] */ {  0,  "audio/wp_hammer_hit-01.wv", },
-	/* x1957[1] */ {  0,  "audio/wp_hammer_hit-02.wv", },
-	/* x1957[2] */ {  0,  "audio/wp_hammer_hit-03.wv", },
-};
-static CDataSound x1973[] = {
-	/* x1973[0] */ {  0,  "audio/wp_ninja_attack-01.wv", },
-	/* x1973[1] */ {  0,  "audio/wp_ninja_attack-02.wv", },
-	/* x1973[2] */ {  0,  "audio/wp_ninja_attack-03.wv", },
-};
-static CDataSound x1989[] = {
-	/* x1989[0] */ {  0,  "audio/wp_flump_explo-01.wv", },
-	/* x1989[1] */ {  0,  "audio/wp_flump_explo-02.wv", },
-	/* x1989[2] */ {  0,  "audio/wp_flump_explo-03.wv", },
-};
-static CDataSound x2005[] = {
-	/* x2005[0] */ {  0,  "audio/wp_ninja_hit-01.wv", },
-	/* x2005[1] */ {  0,  "audio/wp_ninja_hit-02.wv", },
-	/* x2005[2] */ {  0,  "audio/wp_ninja_hit-03.wv", },
-};
-static CDataSound x2021[] = {
-	/* x2021[0] */ {  0,  "audio/wp_rifle_fire-01.wv", },
-	/* x2021[1] */ {  0,  "audio/wp_rifle_fire-02.wv", },
-	/* x2021[2] */ {  0,  "audio/wp_rifle_fire-03.wv", },
-};
-static CDataSound x2037[] = {
-	/* x2037[0] */ {  0,  "audio/wp_rifle_bnce-01.wv", },
-	/* x2037[1] */ {  0,  "audio/wp_rifle_bnce-02.wv", },
-	/* x2037[2] */ {  0,  "audio/wp_rifle_bnce-03.wv", },
-};
-static CDataSound x2053[] = {
-	/* x2053[0] */ {  0,  "audio/wp_switch-01.wv", },
-	/* x2053[1] */ {  0,  "audio/wp_switch-02.wv", },
-	/* x2053[2] */ {  0,  "audio/wp_switch-03.wv", },
-};
-static CDataSound x2069[] = {
-	/* x2069[0] */ {  0,  "audio/vo_teefault_pain_short-01.wv", },
-	/* x2069[1] */ {  0,  "audio/vo_teefault_pain_short-02.wv", },
-	/* x2069[2] */ {  0,  "audio/vo_teefault_pain_short-03.wv", },
-	/* x2069[3] */ {  0,  "audio/vo_teefault_pain_short-04.wv", },
-	/* x2069[4] */ {  0,  "audio/vo_teefault_pain_short-05.wv", },
-	/* x2069[5] */ {  0,  "audio/vo_teefault_pain_short-06.wv", },
-	/* x2069[6] */ {  0,  "audio/vo_teefault_pain_short-07.wv", },
-	/* x2069[7] */ {  0,  "audio/vo_teefault_pain_short-08.wv", },
-	/* x2069[8] */ {  0,  "audio/vo_teefault_pain_short-09.wv", },
-	/* x2069[9] */ {  0,  "audio/vo_teefault_pain_short-10.wv", },
-	/* x2069[10] */ {  0,  "audio/vo_teefault_pain_short-11.wv", },
-	/* x2069[11] */ {  0,  "audio/vo_teefault_pain_short-12.wv", },
-};
-static CDataSound x2112[] = {
-	/* x2112[0] */ {  0,  "audio/vo_teefault_pain_long-01.wv", },
-	/* x2112[1] */ {  0,  "audio/vo_teefault_pain_long-02.wv", },
-};
-static CDataSound x2125[] = {
-	/* x2125[0] */ {  0,  "audio/foley_land-01.wv", },
-	/* x2125[1] */ {  0,  "audio/foley_land-02.wv", },
-	/* x2125[2] */ {  0,  "audio/foley_land-03.wv", },
-	/* x2125[3] */ {  0,  "audio/foley_land-04.wv", },
-};
-static CDataSound x2144[] = {
-	/* x2144[0] */ {  0,  "audio/foley_dbljump-01.wv", },
-	/* x2144[1] */ {  0,  "audio/foley_dbljump-02.wv", },
-	/* x2144[2] */ {  0,  "audio/foley_dbljump-03.wv", },
-};
-static CDataSound x2160[] = {
-	/* x2160[0] */ {  0,  "audio/foley_foot_left-01.wv", },
-	/* x2160[1] */ {  0,  "audio/foley_foot_left-02.wv", },
-	/* x2160[2] */ {  0,  "audio/foley_foot_left-03.wv", },
-	/* x2160[3] */ {  0,  "audio/foley_foot_left-04.wv", },
-	/* x2160[4] */ {  0,  "audio/foley_foot_right-01.wv", },
-	/* x2160[5] */ {  0,  "audio/foley_foot_right-02.wv", },
-	/* x2160[6] */ {  0,  "audio/foley_foot_right-03.wv", },
-	/* x2160[7] */ {  0,  "audio/foley_foot_right-04.wv", },
-};
-static CDataSound x2191[] = {
-	/* x2191[0] */ {  0,  "audio/foley_body_splat-01.wv", },
-	/* x2191[1] */ {  0,  "audio/foley_body_splat-02.wv", },
-	/* x2191[2] */ {  0,  "audio/foley_body_splat-03.wv", },
-};
-static CDataSound x2207[] = {
-	/* x2207[0] */ {  0,  "audio/vo_teefault_spawn-01.wv", },
-	/* x2207[1] */ {  0,  "audio/vo_teefault_spawn-02.wv", },
-	/* x2207[2] */ {  0,  "audio/vo_teefault_spawn-03.wv", },
-	/* x2207[3] */ {  0,  "audio/vo_teefault_spawn-04.wv", },
-	/* x2207[4] */ {  0,  "audio/vo_teefault_spawn-05.wv", },
-	/* x2207[5] */ {  0,  "audio/vo_teefault_spawn-06.wv", },
-	/* x2207[6] */ {  0,  "audio/vo_teefault_spawn-07.wv", },
-};
-static CDataSound x2235[] = {
-	/* x2235[0] */ {  0,  "audio/sfx_skid-01.wv", },
-	/* x2235[1] */ {  0,  "audio/sfx_skid-02.wv", },
-	/* x2235[2] */ {  0,  "audio/sfx_skid-03.wv", },
-	/* x2235[3] */ {  0,  "audio/sfx_skid-04.wv", },
-};
-static CDataSound x2254[] = {
-	/* x2254[0] */ {  0,  "audio/vo_teefault_cry-01.wv", },
-	/* x2254[1] */ {  0,  "audio/vo_teefault_cry-02.wv", },
-};
-static CDataSound x2267[] = {
-	/* x2267[0] */ {  0,  "audio/hook_loop-01.wv", },
-	/* x2267[1] */ {  0,  "audio/hook_loop-02.wv", },
-};
-static CDataSound x2280[] = {
-	/* x2280[0] */ {  0,  "audio/hook_attach-01.wv", },
-	/* x2280[1] */ {  0,  "audio/hook_attach-02.wv", },
-	/* x2280[2] */ {  0,  "audio/hook_attach-03.wv", },
-};
-static CDataSound x2296[] = {
-	/* x2296[0] */ {  0,  "audio/foley_body_impact-01.wv", },
-	/* x2296[1] */ {  0,  "audio/foley_body_impact-02.wv", },
-	/* x2296[2] */ {  0,  "audio/foley_body_impact-03.wv", },
-};
-static CDataSound x2312[] = {
-	/* x2312[0] */ {  0,  "audio/hook_noattach-01.wv", },
-	/* x2312[1] */ {  0,  "audio/hook_noattach-02.wv", },
-};
-static CDataSound x2325[] = {
-	/* x2325[0] */ {  0,  "audio/sfx_pickup_hrt-01.wv", },
-	/* x2325[1] */ {  0,  "audio/sfx_pickup_hrt-02.wv", },
-};
-static CDataSound x2338[] = {
-	/* x2338[0] */ {  0,  "audio/sfx_pickup_arm-01.wv", },
-	/* x2338[1] */ {  0,  "audio/sfx_pickup_arm-02.wv", },
-	/* x2338[2] */ {  0,  "audio/sfx_pickup_arm-03.wv", },
-	/* x2338[3] */ {  0,  "audio/sfx_pickup_arm-04.wv", },
-};
-static CDataSound x2357[] = {
-	/* x2357[0] */ {  0,  "audio/sfx_pickup_launcher.wv", },
-};
-static CDataSound x2367[] = {
-	/* x2367[0] */ {  0,  "audio/sfx_pickup_sg.wv", },
-};
-static CDataSound x2377[] = {
-	/* x2377[0] */ {  0,  "audio/sfx_pickup_ninja.wv", },
-};
-static CDataSound x2387[] = {
-	/* x2387[0] */ {  0,  "audio/sfx_spawn_wpn-01.wv", },
-	/* x2387[1] */ {  0,  "audio/sfx_spawn_wpn-02.wv", },
-	/* x2387[2] */ {  0,  "audio/sfx_spawn_wpn-03.wv", },
-};
-static CDataSound x2403[] = {
-	/* x2403[0] */ {  0,  "audio/wp_noammo-01.wv", },
-	/* x2403[1] */ {  0,  "audio/wp_noammo-02.wv", },
-	/* x2403[2] */ {  0,  "audio/wp_noammo-03.wv", },
-	/* x2403[3] */ {  0,  "audio/wp_noammo-04.wv", },
-	/* x2403[4] */ {  0,  "audio/wp_noammo-05.wv", },
-};
-static CDataSound x2425[] = {
-	/* x2425[0] */ {  0,  "audio/sfx_hit_weak-01.wv", },
-	/* x2425[1] */ {  0,  "audio/sfx_hit_weak-02.wv", },
-};
-static CDataSound x2438[] = {
-	/* x2438[0] */ {  0,  "audio/sfx_msg-server.wv", },
-};
-static CDataSound x2448[] = {
-	/* x2448[0] */ {  0,  "audio/sfx_msg-client.wv", },
-};
-static CDataSound x2458[] = {
-	/* x2458[0] */ {  0,  "audio/sfx_msg-highlight.wv", },
-};
-static CDataSound x2468[] = {
-	/* x2468[0] */ {  0,  "audio/sfx_ctf_drop.wv", },
-};
-static CDataSound x2478[] = {
-	/* x2478[0] */ {  0,  "audio/sfx_ctf_rtn.wv", },
-};
-static CDataSound x2488[] = {
-	/* x2488[0] */ {  0,  "audio/sfx_ctf_grab_pl.wv", },
-};
-static CDataSound x2498[] = {
-	/* x2498[0] */ {  0,  "audio/sfx_ctf_grab_en.wv", },
-};
-static CDataSound x2508[] = {
-	/* x2508[0] */ {  0,  "audio/sfx_ctf_cap_pl.wv", },
-};
-static CDataSound x2518[] = {
-	/* x2518[0] */ {  0,  "audio/music_menu.wv", },
-};
-static CDataSoundset x9[] = {
-	/* x9[0] */ {  "gun_fire",  3,x1893,  -1, },
-	/* x9[1] */ {  "shotgun_fire",  3,x1909,  -1, },
-	/* x9[2] */ {  "grenade_fire",  3,x1925,  -1, },
-	/* x9[3] */ {  "hammer_fire",  3,x1941,  -1, },
-	/* x9[4] */ {  "hammer_hit",  3,x1957,  -1, },
-	/* x9[5] */ {  "ninja_fire",  3,x1973,  -1, },
-	/* x9[6] */ {  "grenade_explode",  3,x1989,  -1, },
-	/* x9[7] */ {  "ninja_hit",  3,x2005,  -1, },
-	/* x9[8] */ {  "rifle_fire",  3,x2021,  -1, },
-	/* x9[9] */ {  "rifle_bounce",  3,x2037,  -1, },
-	/* x9[10] */ {  "weapon_switch",  3,x2053,  -1, },
-	/* x9[11] */ {  "player_pain_short",  12,x2069,  -1, },
-	/* x9[12] */ {  "player_pain_long",  2,x2112,  -1, },
-	/* x9[13] */ {  "body_land",  4,x2125,  -1, },
-	/* x9[14] */ {  "player_airjump",  3,x2144,  -1, },
-	/* x9[15] */ {  "player_jump",  8,x2160,  -1, },
-	/* x9[16] */ {  "player_die",  3,x2191,  -1, },
-	/* x9[17] */ {  "player_spawn",  7,x2207,  -1, },
-	/* x9[18] */ {  "player_skid",  4,x2235,  -1, },
-	/* x9[19] */ {  "tee_cry",  2,x2254,  -1, },
-	/* x9[20] */ {  "hook_loop",  2,x2267,  -1, },
-	/* x9[21] */ {  "hook_attach_ground",  3,x2280,  -1, },
-	/* x9[22] */ {  "hook_attach_player",  3,x2296,  -1, },
-	/* x9[23] */ {  "hook_noattach",  2,x2312,  -1, },
-	/* x9[24] */ {  "pickup_health",  2,x2325,  -1, },
-	/* x9[25] */ {  "pickup_armor",  4,x2338,  -1, },
-	/* x9[26] */ {  "pickup_grenade",  1,x2357,  -1, },
-	/* x9[27] */ {  "pickup_shotgun",  1,x2367,  -1, },
-	/* x9[28] */ {  "pickup_ninja",  1,x2377,  -1, },
-	/* x9[29] */ {  "weapon_spawn",  3,x2387,  -1, },
-	/* x9[30] */ {  "weapon_noammo",  5,x2403,  -1, },
-	/* x9[31] */ {  "hit",  2,x2425,  -1, },
-	/* x9[32] */ {  "chat_server",  1,x2438,  -1, },
-	/* x9[33] */ {  "chat_client",  1,x2448,  -1, },
-	/* x9[34] */ {  "chat_highlight",  1,x2458,  -1, },
-	/* x9[35] */ {  "ctf_drop",  1,x2468,  -1, },
-	/* x9[36] */ {  "ctf_return",  1,x2478,  -1, },
-	/* x9[37] */ {  "ctf_grab_pl",  1,x2488,  -1, },
-	/* x9[38] */ {  "ctf_grab_en",  1,x2498,  -1, },
-	/* x9[39] */ {  "ctf_capture",  1,x2508,  -1, },
-	/* x9[40] */ {  "menu",  1,x2518,  -1, },
-};
-static CDataImage x14[] = {
-	/* x14[0] */ {  "null",  "",  -1, },
-	/* x14[1] */ {  "game",  "game.png",  -1, },
-	/* x14[2] */ {  "particles",  "particles.png",  -1, },
-	/* x14[3] */ {  "cursor",  "gui_cursor.png",  -1, },
-	/* x14[4] */ {  "banner",  "gui_logo.png",  -1, },
-	/* x14[5] */ {  "emoticons",  "emoticons.png",  -1, },
-	/* x14[6] */ {  "browseicons",  "browse_icons.png",  -1, },
-	/* x14[7] */ {  "console_bg",  "console.png",  -1, },
-	/* x14[8] */ {  "console_bar",  "console_bar.png",  -1, },
-	/* x14[9] */ {  "demobuttons",  "demo_buttons.png",  -1, },
-	/* x14[10] */ {  "fileicons",  "file_icons.png",  -1, },
-	/* x14[11] */ {  "guibuttons",  "gui_buttons.png",  -1, },
-	/* x14[12] */ {  "guiicons",  "gui_icons.png",  -1, },
-};
-static CDataPickupspec x19[] = {
-	/* x19[0] */ {  "health",  15,  0, },
-	/* x19[1] */ {  "armor",  15,  0, },
-	/* x19[2] */ {  "weapon",  15,  0, },
-	/* x19[3] */ {  "ninja",  90,  90, },
-};
-static CDataSpriteset x28[] = {
-	/* x28[0] */ {  &x14[2],  8,  8, },
-	/* x28[1] */ {  &x14[1],  32,  16, },
-	/* x28[2] */ {  &x14[0],  8,  4, },
-	/* x28[3] */ {  &x14[6],  4,  1, },
-	/* x28[4] */ {  &x14[5],  4,  4, },
-	/* x28[5] */ {  &x14[9],  5,  1, },
-	/* x28[6] */ {  &x14[10],  8,  1, },
-	/* x28[7] */ {  &x14[11],  12,  4, },
-	/* x28[8] */ {  &x14[12],  8,  2, },
-};
-static CDataSprite x44[] = {
-	/* x44[0] */ {  "part_slice",  &x28[0],  0,  0,  1,  1, },
-	/* x44[1] */ {  "part_ball",  &x28[0],  1,  0,  1,  1, },
-	/* x44[2] */ {  "part_splat01",  &x28[0],  2,  0,  1,  1, },
-	/* x44[3] */ {  "part_splat02",  &x28[0],  3,  0,  1,  1, },
-	/* x44[4] */ {  "part_splat03",  &x28[0],  4,  0,  1,  1, },
-	/* x44[5] */ {  "part_smoke",  &x28[0],  0,  1,  1,  1, },
-	/* x44[6] */ {  "part_shell",  &x28[0],  0,  2,  2,  2, },
-	/* x44[7] */ {  "part_expl01",  &x28[0],  0,  4,  4,  4, },
-	/* x44[8] */ {  "part_airjump",  &x28[0],  2,  2,  2,  2, },
-	/* x44[9] */ {  "part_hit01",  &x28[0],  4,  1,  2,  2, },
-	/* x44[10] */ {  "health_full",  &x28[1],  21,  0,  2,  2, },
-	/* x44[11] */ {  "health_empty",  &x28[1],  23,  0,  2,  2, },
-	/* x44[12] */ {  "armor_full",  &x28[1],  21,  2,  2,  2, },
-	/* x44[13] */ {  "armor_empty",  &x28[1],  23,  2,  2,  2, },
-	/* x44[14] */ {  "star1",  &x28[1],  15,  0,  2,  2, },
-	/* x44[15] */ {  "star2",  &x28[1],  17,  0,  2,  2, },
-	/* x44[16] */ {  "star3",  &x28[1],  19,  0,  2,  2, },
-	/* x44[17] */ {  "part1",  &x28[1],  6,  0,  1,  1, },
-	/* x44[18] */ {  "part2",  &x28[1],  6,  1,  1,  1, },
-	/* x44[19] */ {  "part3",  &x28[1],  7,  0,  1,  1, },
-	/* x44[20] */ {  "part4",  &x28[1],  7,  1,  1,  1, },
-	/* x44[21] */ {  "part5",  &x28[1],  8,  0,  1,  1, },
-	/* x44[22] */ {  "part6",  &x28[1],  8,  1,  1,  1, },
-	/* x44[23] */ {  "part7",  &x28[1],  9,  0,  2,  2, },
-	/* x44[24] */ {  "part8",  &x28[1],  11,  0,  2,  2, },
-	/* x44[25] */ {  "part9",  &x28[1],  13,  0,  2,  2, },
-	/* x44[26] */ {  "weapon_gun_body",  &x28[1],  2,  4,  4,  2, },
-	/* x44[27] */ {  "weapon_gun_cursor",  &x28[1],  0,  4,  2,  2, },
-	/* x44[28] */ {  "weapon_gun_proj",  &x28[1],  6,  4,  2,  2, },
-	/* x44[29] */ {  "weapon_gun_muzzle1",  &x28[1],  8,  4,  3,  2, },
-	/* x44[30] */ {  "weapon_gun_muzzle2",  &x28[1],  12,  4,  3,  2, },
-	/* x44[31] */ {  "weapon_gun_muzzle3",  &x28[1],  16,  4,  3,  2, },
-	/* x44[32] */ {  "weapon_shotgun_body",  &x28[1],  2,  6,  8,  2, },
-	/* x44[33] */ {  "weapon_shotgun_cursor",  &x28[1],  0,  6,  2,  2, },
-	/* x44[34] */ {  "weapon_shotgun_proj",  &x28[1],  10,  6,  2,  2, },
-	/* x44[35] */ {  "weapon_shotgun_muzzle1",  &x28[1],  12,  6,  3,  2, },
-	/* x44[36] */ {  "weapon_shotgun_muzzle2",  &x28[1],  16,  6,  3,  2, },
-	/* x44[37] */ {  "weapon_shotgun_muzzle3",  &x28[1],  20,  6,  3,  2, },
-	/* x44[38] */ {  "weapon_grenade_body",  &x28[1],  2,  8,  7,  2, },
-	/* x44[39] */ {  "weapon_grenade_cursor",  &x28[1],  0,  8,  2,  2, },
-	/* x44[40] */ {  "weapon_grenade_proj",  &x28[1],  10,  8,  2,  2, },
-	/* x44[41] */ {  "weapon_hammer_body",  &x28[1],  2,  1,  4,  3, },
-	/* x44[42] */ {  "weapon_hammer_cursor",  &x28[1],  0,  0,  2,  2, },
-	/* x44[43] */ {  "weapon_hammer_proj",  &x28[1],  0,  0,  0,  0, },
-	/* x44[44] */ {  "weapon_ninja_body",  &x28[1],  2,  10,  8,  2, },
-	/* x44[45] */ {  "weapon_ninja_cursor",  &x28[1],  0,  10,  2,  2, },
-	/* x44[46] */ {  "weapon_ninja_proj",  &x28[1],  0,  0,  0,  0, },
-	/* x44[47] */ {  "weapon_rifle_body",  &x28[1],  2,  12,  7,  3, },
-	/* x44[48] */ {  "weapon_rifle_cursor",  &x28[1],  0,  12,  2,  2, },
-	/* x44[49] */ {  "weapon_rifle_proj",  &x28[1],  10,  12,  2,  2, },
-	/* x44[50] */ {  "hook_chain",  &x28[1],  2,  0,  1,  1, },
-	/* x44[51] */ {  "hook_head",  &x28[1],  3,  0,  2,  1, },
-	/* x44[52] */ {  "weapon_ninja_muzzle1",  &x28[1],  25,  0,  7,  4, },
-	/* x44[53] */ {  "weapon_ninja_muzzle2",  &x28[1],  25,  4,  7,  4, },
-	/* x44[54] */ {  "weapon_ninja_muzzle3",  &x28[1],  25,  8,  7,  4, },
-	/* x44[55] */ {  "pickup_health",  &x28[1],  10,  2,  2,  2, },
-	/* x44[56] */ {  "pickup_armor",  &x28[1],  12,  2,  2,  2, },
-	/* x44[57] */ {  "pickup_weapon",  &x28[1],  3,  0,  6,  2, },
-	/* x44[58] */ {  "pickup_ninja",  &x28[1],  2,  10,  8,  2, },
-	/* x44[59] */ {  "flag_blue",  &x28[1],  12,  8,  4,  8, },
-	/* x44[60] */ {  "flag_red",  &x28[1],  16,  8,  4,  8, },
-	/* x44[61] */ {  "tee_body",  &x28[2],  0,  0,  3,  3, },
-	/* x44[62] */ {  "tee_body_outline",  &x28[2],  3,  0,  3,  3, },
-	/* x44[63] */ {  "tee_foot",  &x28[2],  6,  1,  2,  1, },
-	/* x44[64] */ {  "tee_foot_outline",  &x28[2],  6,  2,  2,  1, },
-	/* x44[65] */ {  "tee_hand",  &x28[2],  6,  0,  1,  1, },
-	/* x44[66] */ {  "tee_hand_outline",  &x28[2],  7,  0,  1,  1, },
-	/* x44[67] */ {  "tee_eye_normal",  &x28[2],  2,  3,  1,  1, },
-	/* x44[68] */ {  "tee_eye_angry",  &x28[2],  3,  3,  1,  1, },
-	/* x44[69] */ {  "tee_eye_pain",  &x28[2],  4,  3,  1,  1, },
-	/* x44[70] */ {  "tee_eye_happy",  &x28[2],  5,  3,  1,  1, },
-	/* x44[71] */ {  "tee_eye_dead",  &x28[2],  6,  3,  1,  1, },
-	/* x44[72] */ {  "tee_eye_surprise",  &x28[2],  7,  3,  1,  1, },
-	/* x44[73] */ {  "oop",  &x28[4],  0,  0,  1,  1, },
-	/* x44[74] */ {  "exclamation",  &x28[4],  1,  0,  1,  1, },
-	/* x44[75] */ {  "hearts",  &x28[4],  2,  0,  1,  1, },
-	/* x44[76] */ {  "drop",  &x28[4],  3,  0,  1,  1, },
-	/* x44[77] */ {  "dotdot",  &x28[4],  0,  1,  1,  1, },
-	/* x44[78] */ {  "music",  &x28[4],  1,  1,  1,  1, },
-	/* x44[79] */ {  "sorry",  &x28[4],  2,  1,  1,  1, },
-	/* x44[80] */ {  "ghost",  &x28[4],  3,  1,  1,  1, },
-	/* x44[81] */ {  "sushi",  &x28[4],  0,  2,  1,  1, },
-	/* x44[82] */ {  "splattee",  &x28[4],  1,  2,  1,  1, },
-	/* x44[83] */ {  "deviltee",  &x28[4],  2,  2,  1,  1, },
-	/* x44[84] */ {  "zomg",  &x28[4],  3,  2,  1,  1, },
-	/* x44[85] */ {  "zzz",  &x28[4],  0,  3,  1,  1, },
-	/* x44[86] */ {  "wtf",  &x28[4],  1,  3,  1,  1, },
-	/* x44[87] */ {  "eyes",  &x28[4],  2,  3,  1,  1, },
-	/* x44[88] */ {  "question",  &x28[4],  3,  3,  1,  1, },
-	/* x44[89] */ {  "browse_lock",  &x28[3],  0,  0,  1,  1, },
-	/* x44[90] */ {  "browse_heart",  &x28[3],  1,  0,  1,  1, },
-	/* x44[91] */ {  "browse_unpure",  &x28[3],  3,  0,  1,  1, },
-	/* x44[92] */ {  "demobutton_play",  &x28[5],  0,  0,  1,  1, },
-	/* x44[93] */ {  "demobutton_pause",  &x28[5],  1,  0,  1,  1, },
-	/* x44[94] */ {  "demobutton_stop",  &x28[5],  2,  0,  1,  1, },
-	/* x44[95] */ {  "demobutton_slower",  &x28[5],  3,  0,  1,  1, },
-	/* x44[96] */ {  "demobutton_faster",  &x28[5],  4,  0,  1,  1, },
-	/* x44[97] */ {  "file_demo1",  &x28[6],  0,  0,  1,  1, },
-	/* x44[98] */ {  "file_demo2",  &x28[6],  1,  0,  1,  1, },
-	/* x44[99] */ {  "file_folder",  &x28[6],  2,  0,  1,  1, },
-	/* x44[100] */ {  "file_map1",  &x28[6],  5,  0,  1,  1, },
-	/* x44[101] */ {  "file_map2",  &x28[6],  6,  0,  1,  1, },
-	/* x44[102] */ {  "guibutton_off",  &x28[7],  0,  0,  4,  4, },
-	/* x44[103] */ {  "guibutton_on",  &x28[7],  4,  0,  4,  4, },
-	/* x44[104] */ {  "guibutton_hover",  &x28[7],  8,  0,  4,  4, },
-	/* x44[105] */ {  "guiicon_mute",  &x28[8],  0,  0,  4,  2, },
-	/* x44[106] */ {  "guiicon_friend",  &x28[8],  4,  0,  4,  2, },
-};
-static CAnimKeyframe x4276[] = {
-	/* x4276[0] */ {  0.000000,  0.000000,  -4.000000,  0.000000, },
-};
-static CAnimKeyframe x4283[] = {
-	/* x4283[0] */ {  0.000000,  0.000000,  10.000000,  0.000000, },
-};
-static CAnimKeyframe x4290[] = {
-	/* x4290[0] */ {  0.000000,  0.000000,  10.000000,  0.000000, },
-};
-static CAnimKeyframe *x4297 = 0;
-static CAnimKeyframe *x4321 = 0;
-static CAnimKeyframe x4328[] = {
-	/* x4328[0] */ {  0.000000,  -7.000000,  0.000000,  0.000000, },
-};
-static CAnimKeyframe x4335[] = {
-	/* x4335[0] */ {  0.000000,  7.000000,  0.000000,  0.000000, },
-};
-static CAnimKeyframe *x4342 = 0;
-static CAnimKeyframe *x4361 = 0;
-static CAnimKeyframe x4368[] = {
-	/* x4368[0] */ {  0.000000,  -3.000000,  0.000000,  -0.100000, },
-};
-static CAnimKeyframe x4375[] = {
-	/* x4375[0] */ {  0.000000,  3.000000,  0.000000,  -0.100000, },
-};
-static CAnimKeyframe *x4382 = 0;
-static CAnimKeyframe x4401[] = {
-	/* x4401[0] */ {  0.000000,  0.000000,  0.000000,  0.000000, },
-	/* x4401[1] */ {  0.200000,  0.000000,  -1.000000,  0.000000, },
-	/* x4401[2] */ {  0.400000,  0.000000,  0.000000,  0.000000, },
-	/* x4401[3] */ {  0.600000,  0.000000,  0.000000,  0.000000, },
-	/* x4401[4] */ {  0.800000,  0.000000,  -1.000000,  0.000000, },
-	/* x4401[5] */ {  1.000000,  0.000000,  0.000000,  0.000000, },
-};
-static CAnimKeyframe x4408[] = {
-	/* x4408[0] */ {  0.000000,  8.000000,  0.000000,  0.000000, },
-	/* x4408[1] */ {  0.200000,  -8.000000,  0.000000,  0.000000, },
-	/* x4408[2] */ {  0.400000,  -10.000000,  -4.000000,  0.200000, },
-	/* x4408[3] */ {  0.600000,  -8.000000,  -8.000000,  0.300000, },
-	/* x4408[4] */ {  0.800000,  4.000000,  -4.000000,  -0.200000, },
-	/* x4408[5] */ {  1.000000,  8.000000,  0.000000,  0.000000, },
-};
-static CAnimKeyframe x4415[] = {
-	/* x4415[0] */ {  0.000000,  -10.000000,  -4.000000,  0.200000, },
-	/* x4415[1] */ {  0.200000,  -8.000000,  -8.000000,  0.300000, },
-	/* x4415[2] */ {  0.400000,  4.000000,  -4.000000,  -0.200000, },
-	/* x4415[3] */ {  0.600000,  8.000000,  0.000000,  0.000000, },
-	/* x4415[4] */ {  0.800000,  8.000000,  0.000000,  0.000000, },
-	/* x4415[5] */ {  1.000000,  -10.000000,  -4.000000,  0.200000, },
-};
-static CAnimKeyframe *x4422 = 0;
-static CAnimKeyframe *x4521 = 0;
-static CAnimKeyframe *x4528 = 0;
-static CAnimKeyframe *x4535 = 0;
-static CAnimKeyframe x4542[] = {
-	/* x4542[0] */ {  0.000000,  0.000000,  0.000000,  -0.100000, },
-	/* x4542[1] */ {  0.300000,  0.000000,  0.000000,  0.250000, },
-	/* x4542[2] */ {  0.400000,  0.000000,  0.000000,  0.300000, },
-	/* x4542[3] */ {  0.500000,  0.000000,  0.000000,  0.250000, },
-	/* x4542[4] */ {  1.000000,  0.000000,  0.000000,  -0.100000, },
-};
-static CAnimKeyframe *x4576 = 0;
-static CAnimKeyframe *x4583 = 0;
-static CAnimKeyframe *x4590 = 0;
-static CAnimKeyframe x4597[] = {
-	/* x4597[0] */ {  0.000000,  0.000000,  0.000000,  -0.250000, },
-	/* x4597[1] */ {  0.100000,  0.000000,  0.000000,  -0.050000, },
-	/* x4597[2] */ {  0.150000,  0.000000,  0.000000,  0.350000, },
-	/* x4597[3] */ {  0.420000,  0.000000,  0.000000,  0.400000, },
-	/* x4597[4] */ {  0.500000,  0.000000,  0.000000,  0.350000, },
-	/* x4597[5] */ {  1.000000,  0.000000,  0.000000,  -0.250000, },
-};
-static CAnimation x75[] = {
-	/* x75[0] */ {  "base",  /* x75[0].body */ {  1,x4276, },  /* x75[0].back_foot */ {  1,x4283, },  /* x75[0].front_foot */ {  1,x4290, },  /* x75[0].attach */ {  0,x4297, }, },
-	/* x75[1] */ {  "idle",  /* x75[1].body */ {  0,x4321, },  /* x75[1].back_foot */ {  1,x4328, },  /* x75[1].front_foot */ {  1,x4335, },  /* x75[1].attach */ {  0,x4342, }, },
-	/* x75[2] */ {  "inair",  /* x75[2].body */ {  0,x4361, },  /* x75[2].back_foot */ {  1,x4368, },  /* x75[2].front_foot */ {  1,x4375, },  /* x75[2].attach */ {  0,x4382, }, },
-	/* x75[3] */ {  "walk",  /* x75[3].body */ {  6,x4401, },  /* x75[3].back_foot */ {  6,x4408, },  /* x75[3].front_foot */ {  6,x4415, },  /* x75[3].attach */ {  0,x4422, }, },
-	/* x75[4] */ {  "hammer_swing",  /* x75[4].body */ {  0,x4521, },  /* x75[4].back_foot */ {  0,x4528, },  /* x75[4].front_foot */ {  0,x4535, },  /* x75[4].attach */ {  5,x4542, }, },
-	/* x75[5] */ {  "ninja_swing",  /* x75[5].body */ {  0,x4576, },  /* x75[5].back_foot */ {  0,x4583, },  /* x75[5].front_foot */ {  0,x4590, },  /* x75[5].attach */ {  6,x4597, }, },
-};
-static CDataSprite* *x4754 = 0;
-static CDataSprite* x4891[] = {
-	&x44[29],
-	&x44[30],
-	&x44[31],
-};
-static CDataSprite* x5076[] = {
-	&x44[35],
-	&x44[36],
-	&x44[37],
-};
-static CDataSprite* *x5261 = 0;
-static CDataSprite* *x5398 = 0;
-static CDataSprite* x5535[] = {
-	&x44[52],
-	&x44[53],
-	&x44[54],
-};
-static CDataWeaponspec x1887[] = {
-	/* x1887[0] */ {  "hammer",  &x44[41],  &x44[42],  &x44[43],  0,x4754,  96,  125,  10,  0,  3,  4.000000,  -20.000000,  0.000000,  0.000000,  5.000000, },
-	/* x1887[1] */ {  "gun",  &x44[26],  &x44[27],  &x44[28],  3,x4891,  64,  125,  10,  500,  1,  32.000000,  -4.000000,  50.000000,  6.000000,  5.000000, },
-	/* x1887[2] */ {  "shotgun",  &x44[32],  &x44[33],  &x44[34],  3,x5076,  96,  500,  10,  0,  1,  24.000000,  -2.000000,  70.000000,  6.000000,  5.000000, },
-	/* x1887[3] */ {  "grenade",  &x44[38],  &x44[39],  &x44[40],  0,x5261,  96,  500,  10,  0,  1,  24.000000,  -2.000000,  0.000000,  0.000000,  5.000000, },
-	/* x1887[4] */ {  "rifle",  &x44[47],  &x44[48],  &x44[49],  0,x5398,  92,  800,  10,  0,  5,  24.000000,  -2.000000,  0.000000,  0.000000,  5.000000, },
-	/* x1887[5] */ {  "ninja",  &x44[44],  &x44[45],  &x44[46],  3,x5535,  96,  800,  10,  0,  9,  0.000000,  0.000000,  40.000000,  -4.000000,  5.000000, },
-};
-CDataContainer datacontainer = 
-/* datacontainer */ {
-	41,x9,
-	13,x14,
-	4,x19,
-	9,x28,
-	107,x44,
-	6,x75,
-	/* datacontainer.weapons */ { 	/* datacontainer.weapons.hammer */ { 	&x1887[0], }, 	/* datacontainer.weapons.gun */ { 	&x1887[1], 	1.250000, 	2200.000000, 	2.000000, }, 	/* datacontainer.weapons.shotgun */ { 	&x1887[2], 	1.250000, 	2200.000000, 	0.800000, 	0.250000, }, 	/* datacontainer.weapons.grenade */ { 	&x1887[3], 	7.000000, 	1000.000000, 	2.000000, }, 	/* datacontainer.weapons.rifle */ { 	&x1887[4], 	800.000000, 	150, 	1, 	0.000000, }, 	/* datacontainer.weapons.ninja */ { 	&x1887[5], 	15000, 	200, 	50, }, 	6,x1887, },
-}
-;
-CDataContainer *g_pData = &datacontainer;
diff -rupN teeworlds-b177-r50edfd37-source/src//game/generated/server_data.h alien-rc4/src//game/generated/server_data.h
--- teeworlds-b177-r50edfd37-source/src//game/generated/server_data.h	2012-01-27 22:23:47.000000000 +0100
+++ alien-rc4/src//game/generated/server_data.h	1970-01-01 01:00:00.000000000 +0100
@@ -1,288 +0,0 @@
-#ifndef SERVER_CONTENT_HEADER
-#define SERVER_CONTENT_HEADER
-struct CDataSound
-{
-	int m_Id;
-	const char* m_pFilename;
-};
-struct CDataSoundset
-{
-	const char* m_pName;
-	int m_NumSounds;
-	CDataSound *m_aSounds;
-	int m_Last;
-};
-struct CDataImage
-{
-	const char* m_pName;
-	const char* m_pFilename;
-	int m_Id;
-};
-struct CDataSpriteset
-{
-	CDataImage* m_pImage;
-	int m_Gridx;
-	int m_Gridy;
-};
-struct CDataSprite
-{
-	const char* m_pName;
-	CDataSpriteset* m_pSet;
-	int m_X;
-	int m_Y;
-	int m_W;
-	int m_H;
-};
-struct CDataPickupspec
-{
-	const char* m_pName;
-	int m_Respawntime;
-	int m_Spawndelay;
-};
-struct CAnimKeyframe
-{
-	float m_Time;
-	float m_X;
-	float m_Y;
-	float m_Angle;
-};
-struct CAnimSequence
-{
-	int m_NumFrames;
-	CAnimKeyframe *m_aFrames;
-};
-struct CAnimation
-{
-	const char* m_pName;
-	CAnimSequence m_Body;
-	CAnimSequence m_BackFoot;
-	CAnimSequence m_FrontFoot;
-	CAnimSequence m_Attach;
-};
-struct CDataWeaponspec
-{
-	const char* m_pName;
-	CDataSprite* m_pSpriteBody;
-	CDataSprite* m_pSpriteCursor;
-	CDataSprite* m_pSpriteProj;
-	int m_NumSpriteMuzzles;
-	CDataSprite* *m_aSpriteMuzzles;
-	int m_VisualSize;
-	int m_Firedelay;
-	int m_Maxammo;
-	int m_Ammoregentime;
-	int m_Damage;
-	float m_Offsetx;
-	float m_Offsety;
-	float m_Muzzleoffsetx;
-	float m_Muzzleoffsety;
-	float m_Muzzleduration;
-};
-struct CDataWeaponspecHammer
-{
-	CDataWeaponspec* m_pBase;
-};
-struct CDataWeaponspecGun
-{
-	CDataWeaponspec* m_pBase;
-	float m_Curvature;
-	float m_Speed;
-	float m_Lifetime;
-};
-struct CDataWeaponspecShotgun
-{
-	CDataWeaponspec* m_pBase;
-	float m_Curvature;
-	float m_Speed;
-	float m_Speeddiff;
-	float m_Lifetime;
-};
-struct CDataWeaponspecGrenade
-{
-	CDataWeaponspec* m_pBase;
-	float m_Curvature;
-	float m_Speed;
-	float m_Lifetime;
-};
-struct CDataWeaponspecRifle
-{
-	CDataWeaponspec* m_pBase;
-	float m_Reach;
-	int m_BounceDelay;
-	int m_BounceNum;
-	float m_BounceCost;
-};
-struct CDataWeaponspecNinja
-{
-	CDataWeaponspec* m_pBase;
-	int m_Duration;
-	int m_Movetime;
-	int m_Velocity;
-};
-struct CDataWeaponspecs
-{
-	CDataWeaponspecHammer m_Hammer;
-	CDataWeaponspecGun m_Gun;
-	CDataWeaponspecShotgun m_Shotgun;
-	CDataWeaponspecGrenade m_Grenade;
-	CDataWeaponspecRifle m_Rifle;
-	CDataWeaponspecNinja m_Ninja;
-	int m_NumId;
-	CDataWeaponspec *m_aId;
-};
-struct CDataContainer
-{
-	int m_NumSounds;
-	CDataSoundset *m_aSounds;
-	int m_NumImages;
-	CDataImage *m_aImages;
-	int m_NumPickups;
-	CDataPickupspec *m_aPickups;
-	int m_NumSpritesets;
-	CDataSpriteset *m_aSpritesets;
-	int m_NumSprites;
-	CDataSprite *m_aSprites;
-	int m_NumAnimations;
-	CAnimation *m_aAnimations;
-	CDataWeaponspecs m_Weapons;
-};
-extern CDataContainer *g_pData;
-enum
-{
-	IMAGE_NULL=0,
-	IMAGE_GAME,
-	IMAGE_PARTICLES,
-	IMAGE_CURSOR,
-	IMAGE_BANNER,
-	IMAGE_EMOTICONS,
-	IMAGE_BROWSEICONS,
-	IMAGE_CONSOLE_BG,
-	IMAGE_CONSOLE_BAR,
-	IMAGE_DEMOBUTTONS,
-	IMAGE_FILEICONS,
-	IMAGE_GUIBUTTONS,
-	IMAGE_GUIICONS,
-	NUM_IMAGES
-};
-enum
-{
-	ANIM_BASE=0,
-	ANIM_IDLE,
-	ANIM_INAIR,
-	ANIM_WALK,
-	ANIM_HAMMER_SWING,
-	ANIM_NINJA_SWING,
-	NUM_ANIMS
-};
-enum
-{
-	SPRITE_PART_SLICE=0,
-	SPRITE_PART_BALL,
-	SPRITE_PART_SPLAT01,
-	SPRITE_PART_SPLAT02,
-	SPRITE_PART_SPLAT03,
-	SPRITE_PART_SMOKE,
-	SPRITE_PART_SHELL,
-	SPRITE_PART_EXPL01,
-	SPRITE_PART_AIRJUMP,
-	SPRITE_PART_HIT01,
-	SPRITE_HEALTH_FULL,
-	SPRITE_HEALTH_EMPTY,
-	SPRITE_ARMOR_FULL,
-	SPRITE_ARMOR_EMPTY,
-	SPRITE_STAR1,
-	SPRITE_STAR2,
-	SPRITE_STAR3,
-	SPRITE_PART1,
-	SPRITE_PART2,
-	SPRITE_PART3,
-	SPRITE_PART4,
-	SPRITE_PART5,
-	SPRITE_PART6,
-	SPRITE_PART7,
-	SPRITE_PART8,
-	SPRITE_PART9,
-	SPRITE_WEAPON_GUN_BODY,
-	SPRITE_WEAPON_GUN_CURSOR,
-	SPRITE_WEAPON_GUN_PROJ,
-	SPRITE_WEAPON_GUN_MUZZLE1,
-	SPRITE_WEAPON_GUN_MUZZLE2,
-	SPRITE_WEAPON_GUN_MUZZLE3,
-	SPRITE_WEAPON_SHOTGUN_BODY,
-	SPRITE_WEAPON_SHOTGUN_CURSOR,
-	SPRITE_WEAPON_SHOTGUN_PROJ,
-	SPRITE_WEAPON_SHOTGUN_MUZZLE1,
-	SPRITE_WEAPON_SHOTGUN_MUZZLE2,
-	SPRITE_WEAPON_SHOTGUN_MUZZLE3,
-	SPRITE_WEAPON_GRENADE_BODY,
-	SPRITE_WEAPON_GRENADE_CURSOR,
-	SPRITE_WEAPON_GRENADE_PROJ,
-	SPRITE_WEAPON_HAMMER_BODY,
-	SPRITE_WEAPON_HAMMER_CURSOR,
-	SPRITE_WEAPON_HAMMER_PROJ,
-	SPRITE_WEAPON_NINJA_BODY,
-	SPRITE_WEAPON_NINJA_CURSOR,
-	SPRITE_WEAPON_NINJA_PROJ,
-	SPRITE_WEAPON_RIFLE_BODY,
-	SPRITE_WEAPON_RIFLE_CURSOR,
-	SPRITE_WEAPON_RIFLE_PROJ,
-	SPRITE_HOOK_CHAIN,
-	SPRITE_HOOK_HEAD,
-	SPRITE_WEAPON_NINJA_MUZZLE1,
-	SPRITE_WEAPON_NINJA_MUZZLE2,
-	SPRITE_WEAPON_NINJA_MUZZLE3,
-	SPRITE_PICKUP_HEALTH,
-	SPRITE_PICKUP_ARMOR,
-	SPRITE_PICKUP_WEAPON,
-	SPRITE_PICKUP_NINJA,
-	SPRITE_FLAG_BLUE,
-	SPRITE_FLAG_RED,
-	SPRITE_TEE_BODY,
-	SPRITE_TEE_BODY_OUTLINE,
-	SPRITE_TEE_FOOT,
-	SPRITE_TEE_FOOT_OUTLINE,
-	SPRITE_TEE_HAND,
-	SPRITE_TEE_HAND_OUTLINE,
-	SPRITE_TEE_EYE_NORMAL,
-	SPRITE_TEE_EYE_ANGRY,
-	SPRITE_TEE_EYE_PAIN,
-	SPRITE_TEE_EYE_HAPPY,
-	SPRITE_TEE_EYE_DEAD,
-	SPRITE_TEE_EYE_SURPRISE,
-	SPRITE_OOP,
-	SPRITE_EXCLAMATION,
-	SPRITE_HEARTS,
-	SPRITE_DROP,
-	SPRITE_DOTDOT,
-	SPRITE_MUSIC,
-	SPRITE_SORRY,
-	SPRITE_GHOST,
-	SPRITE_SUSHI,
-	SPRITE_SPLATTEE,
-	SPRITE_DEVILTEE,
-	SPRITE_ZOMG,
-	SPRITE_ZZZ,
-	SPRITE_WTF,
-	SPRITE_EYES,
-	SPRITE_QUESTION,
-	SPRITE_BROWSE_LOCK,
-	SPRITE_BROWSE_HEART,
-	SPRITE_BROWSE_UNPURE,
-	SPRITE_DEMOBUTTON_PLAY,
-	SPRITE_DEMOBUTTON_PAUSE,
-	SPRITE_DEMOBUTTON_STOP,
-	SPRITE_DEMOBUTTON_SLOWER,
-	SPRITE_DEMOBUTTON_FASTER,
-	SPRITE_FILE_DEMO1,
-	SPRITE_FILE_DEMO2,
-	SPRITE_FILE_FOLDER,
-	SPRITE_FILE_MAP1,
-	SPRITE_FILE_MAP2,
-	SPRITE_GUIBUTTON_OFF,
-	SPRITE_GUIBUTTON_ON,
-	SPRITE_GUIBUTTON_HOVER,
-	SPRITE_GUIICON_MUTE,
-	SPRITE_GUIICON_FRIEND,
-	NUM_SPRITES
-};
-#endif
diff -rupN teeworlds-b177-r50edfd37-source/src//game/layers.cpp alien-rc4/src//game/layers.cpp
--- teeworlds-b177-r50edfd37-source/src//game/layers.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/layers.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -29,7 +29,7 @@ void CLayers::Init(class IKernel *pKerne
 			if(pLayer->m_Type == LAYERTYPE_TILES)
 			{
 				CMapItemLayerTilemap *pTilemap = reinterpret_cast<CMapItemLayerTilemap *>(pLayer);
-				if(pTilemap->m_Flags&1)
+				if(pTilemap->m_Flags&TILESLAYERFLAG_GAME)
 				{
 					m_pGameLayer = pTilemap;
 					m_pGameGroup = pGroup;
diff -rupN teeworlds-b177-r50edfd37-source/src//game/mapitems.h alien-rc4/src//game/mapitems.h
--- teeworlds-b177-r50edfd37-source/src//game/mapitems.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/mapitems.h	2012-06-14 23:57:39.000000000 +0200
@@ -40,12 +40,22 @@ enum
 	ENTITY_WEAPON_GRENADE,
 	ENTITY_POWERUP_NINJA,
 	ENTITY_WEAPON_RIFLE,
+	ENTITY_POWERUP_HAMMER,
+	ENTITY_SPARK,
+	ENTITY_LASERTURRET,
+	ENTITY_SINGULARITY,
 	NUM_ENTITIES,
 
 	TILE_AIR=0,
 	TILE_SOLID,
 	TILE_DEATH,
 	TILE_NOHOOK,
+	TILE_TURRET,
+	TILE_INVIS,
+	TILE_BIOHAZARD,
+	TILE_BIOINVIS,
+	TILE_ENERGYUP,
+	TILE_REAPER,
 
 	TILEFLAG_VFLIP=1,
 	TILEFLAG_HFLIP=2,
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/entities/character.cpp alien-rc4/src//game/server/entities/character.cpp
--- teeworlds-b177-r50edfd37-source/src//game/server/entities/character.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/server/entities/character.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -4,10 +4,13 @@
 #include <engine/shared/config.h>
 #include <game/server/gamecontext.h>
 #include <game/mapitems.h>
+#include <game/server/gamemodes/mod.h>
 
 #include "character.h"
 #include "laser.h"
+#include "laserwall.h"
 #include "projectile.h"
+#include "singularinator.h"
 
 //input count
 struct CInputCount
@@ -45,6 +48,10 @@ CCharacter::CCharacter(CGameWorld *pWorl
 	m_ProximityRadius = ms_PhysSize;
 	m_Health = 0;
 	m_Armor = 0;
+
+	// Mutator
+	m_LaserWall = 0;
+	m_QueuedLaser = LASER_SUBTYPE_NORMAL;	
 }
 
 void CCharacter::Reset()
@@ -62,7 +69,7 @@ bool CCharacter::Spawn(CPlayer *pPlayer,
 
 	m_pPlayer = pPlayer;
 	m_Pos = Pos;
-
+	
 	m_Core.Reset();
 	m_Core.Init(&GameServer()->m_World.m_Core, GameServer()->Collision());
 	m_Core.m_Pos = m_Pos;
@@ -75,11 +82,99 @@ bool CCharacter::Spawn(CPlayer *pPlayer,
 	GameServer()->m_World.InsertEntity(this);
 	m_Alive = true;
 
-	GameServer()->m_pController->OnCharacterSpawn(this);
+	// No nead for next line ... we had to change too much stuff already here anyway ... 
+	// GameServer()->m_pController->OnCharacterSpawn(this);
 
+	// Mutator
+	
+	// Init Eyes
+	m_MutanticEmoteTick = Server()->Tick() + 500 * Server()->TickSpeed() / 1000;
+	if(GetPlayer()->m_MutatorTeam > TEAM_REAPER)
+		SetEmote(EMOTE_NORMAL,-1);
+	else
+		SetEmote(EMOTE_ANGRY,m_MutanticEmoteTick);
+	
+	m_MutanticEyeOn = 0;
+
+	// Default settings of health and hammer	
+	IncreaseHealth(10);
+	GiveWeapon(WEAPON_HAMMER, -1);
+
+	// Laser Subtype stuff
+	m_QueuedLaser = LASER_SUBTYPE_NORMAL;
+	m_aWeapons[WEAPON_RIFLE].m_SpecialAmmo = 0;
+	m_aWeapons[WEAPON_RIFLE].m_NormalAmmo = 0;
+	m_LaserCycleInfoSwitch = 0;
+	mem_zero(&m_OwnLaserSubType,sizeof(m_OwnLaserSubType));
+	m_OwnLaserSubType[0] = true; // always own knowledge of normal laser :)
+	if(m_pPlayer->m_ScienceExplored&SCIENCE_LASER_RIDDLE)
+		m_OwnLaserSubType[1] = true;
+	if(m_pPlayer->m_ScienceExplored&SCIENCE_LASER_TELE)
+		m_OwnLaserSubType[2] = true;
+	if(m_pPlayer->m_ScienceExplored&SCIENCE_LASER_HEALING)
+		m_OwnLaserSubType[3] = true;
+
+	// On tile or entity switches
+	m_OnTurret = 0;
+	m_PrevOnTurret = 0;
+	m_TurretAmmo = 0;
+	m_TurretActive = 0;
+	m_OnScience = 0;
+	m_PrevOnScience = 0;
+	m_Invisible = 0;
+	m_OnEnergyUp = 0;
+	m_PrevOnEnergyUp = 0;
+	m_OnReapinator = 0;
+	m_PrevOnReapinator = 0;
+
+	m_pPlayer->m_MultiScore = 0;
+
+	// Timer
+	m_BioHazardDamageTick = Server()->Tick();
+	m_pPlayer->m_MultiScoreTick = Server()->Tick();
+	m_ShowInfoTick = Server()->Tick();
+	m_EnergyUpTick = Server()->Tick();
+	
+	
+	// Multijump
+	m_MutanticArmorDJCount = 0;
+
+	// Owner of airstrike
+	m_OwnAirstrike = 0;
+
+	// Set right team depending on gamestatus 
+	if(GameServer()->m_pController->MutGameRunning() == 0)
+		m_pPlayer->m_MutatorTeam = TEAM_HUMAN;
+	else if(m_pPlayer->m_MutatorTeam >= TEAM_HUMAN)
+		m_pPlayer->m_MutatorTeam = TEAM_MUTANT;
+
+	// Give weapons depending on team
+	if(m_pPlayer->m_MutatorTeam <= TEAM_MUTANT)
+	{
+		SetWeapon(WEAPON_HAMMER);
+		m_MutanticSpawnProtection = Server()->Tick() + 1000 * Server()->TickSpeed() / 1000;;
+		if(m_pPlayer->m_MutaticLevels&MUTATOR_START_SHIELDS)
+			IncreaseArmor(10);
+	}
+	else if(m_pPlayer->m_MutatorTeam < TEAM_HERO)
+	{
+		GiveWeapon(WEAPON_GUN, 10);
+		SetWeapon(WEAPON_GUN);
+	}
+	else
+	{	
+		GiveWeapon(WEAPON_GUN, 5);
+		GiveWeapon(WEAPON_SHOTGUN, 10);
+		SetWeapon(WEAPON_SHOTGUN);
+	}
 	return true;
 }
 
+void CCharacter::SetPreStartGame()
+{
+	m_MutanticEmoteTick = Server()->Tick();
+}
+
 void CCharacter::Destroy()
 {
 	GameServer()->m_World.m_Core.m_apCharacters[m_pPlayer->GetCID()] = 0;
@@ -109,7 +204,6 @@ bool CCharacter::IsGrounded()
 	return false;
 }
 
-
 void CCharacter::HandleNinja()
 {
 	if(m_ActiveWeapon != WEAPON_NINJA)
@@ -193,11 +287,58 @@ void CCharacter::HandleNinja()
 void CCharacter::DoWeaponSwitch()
 {
 	// make sure we can switch
-	if(m_ReloadTimer != 0 || m_QueuedWeapon == -1 || m_aWeapons[WEAPON_NINJA].m_Got)
+	if(m_ReloadTimer != 0 || m_QueuedWeapon == -1 || m_aWeapons[WEAPON_NINJA].m_Got || m_pPlayer->m_MutatorTeam == TEAM_MUTANT 
+				|| (m_pPlayer->m_MutatorTeam == TEAM_REAPER && !(m_QueuedWeapon == WEAPON_HAMMER || m_QueuedWeapon == WEAPON_RIFLE)) || m_OnTurret)
 		return;
 
+	// Backup Ammo state if laser (healing laser is different ammo)
+	if(m_ActiveWeapon == WEAPON_RIFLE)
+	{
+		if(m_aWeapons[WEAPON_RIFLE].m_SubType == LASER_SUBTYPE_HEALING)
+			m_aWeapons[WEAPON_RIFLE].m_SpecialAmmo = m_aWeapons[WEAPON_RIFLE].m_Ammo;
+
+		else
+			m_aWeapons[WEAPON_RIFLE].m_NormalAmmo = m_aWeapons[WEAPON_RIFLE].m_Ammo;
+	}
+
 	// switch Weapon
 	SetWeapon(m_QueuedWeapon);
+
+	// Handle LaserSubtype Ammo and Broadcast-info-timer
+	if(m_ActiveWeapon == WEAPON_RIFLE && m_pPlayer->m_MutatorTeam >= TEAM_HUMAN)
+	{
+		if(m_aWeapons[WEAPON_RIFLE].m_SubType == LASER_SUBTYPE_HEALING)
+		{
+			// Drop HEALING_LASER from cycle if no ammo is available anymore
+			if(m_aWeapons[WEAPON_RIFLE].m_SpecialAmmo < 1 || m_OwnLaserSubType[LASER_SUBTYPE_HEALING] == false)
+			{
+				m_OwnLaserSubType[LASER_SUBTYPE_HEALING] = false;
+				m_aWeapons[WEAPON_RIFLE].m_SubType = LASER_SUBTYPE_NORMAL;
+			}
+		}
+
+		// Use better riddle-laser if available
+		if(m_aWeapons[WEAPON_RIFLE].m_SubType == LASER_SUBTYPE_NORMAL && m_OwnLaserSubType[LASER_SUBTYPE_RIDDLE])
+			m_aWeapons[WEAPON_RIFLE].m_SubType = LASER_SUBTYPE_RIDDLE;
+
+		// Just inform if some special type was choosen
+		if(m_aWeapons[WEAPON_RIFLE].m_SubType != LASER_SUBTYPE_NORMAL)
+		{
+			m_LaserCycleTick = Server()->Tick() + 250 * Server()->TickSpeed() / 1000; // Avoid flood at fast cycling (just inform if he keep it)
+			m_LaserCycleInfoSwitch = 1;
+		}
+		
+		// Use right ammo-type
+		switch(m_aWeapons[WEAPON_RIFLE].m_SubType)
+		{
+			case LASER_SUBTYPE_NORMAL:
+			case LASER_SUBTYPE_RIDDLE:
+			case LASER_SUBTYPE_TELE:
+				m_aWeapons[WEAPON_RIFLE].m_Ammo = m_aWeapons[WEAPON_RIFLE].m_NormalAmmo; break;
+			case LASER_SUBTYPE_HEALING:
+				m_aWeapons[WEAPON_RIFLE].m_Ammo = m_aWeapons[WEAPON_RIFLE].m_SpecialAmmo; break; 
+		}
+	}
 }
 
 void CCharacter::HandleWeaponSwitch()
@@ -205,7 +346,7 @@ void CCharacter::HandleWeaponSwitch()
 	int WantedWeapon = m_ActiveWeapon;
 	if(m_QueuedWeapon != -1)
 		WantedWeapon = m_QueuedWeapon;
-
+	
 	// select Weapon
 	int Next = CountInput(m_LatestPrevInput.m_NextWeapon, m_LatestInput.m_NextWeapon).m_Presses;
 	int Prev = CountInput(m_LatestPrevInput.m_PrevWeapon, m_LatestInput.m_PrevWeapon).m_Presses;
@@ -231,16 +372,94 @@ void CCharacter::HandleWeaponSwitch()
 	}
 
 	// Direct Weapon selection
-	if(m_LatestInput.m_WantedWeapon)
+	if(m_LatestInput.m_WantedWeapon > 0)
 		WantedWeapon = m_Input.m_WantedWeapon-1;
 
-	// check for insane values
 	if(WantedWeapon >= 0 && WantedWeapon < NUM_WEAPONS && WantedWeapon != m_ActiveWeapon && m_aWeapons[WantedWeapon].m_Got)
 		m_QueuedWeapon = WantedWeapon;
 
 	DoWeaponSwitch();
 }
 
+void CCharacter::CycleLaserSubTypes()
+{
+	if(m_pPlayer->m_MutatorTeam <= TEAM_MUTANT || !m_aWeapons[WEAPON_RIFLE].m_Got)
+		return;
+
+	int ActiveLaser = m_aWeapons[WEAPON_RIFLE].m_SubType;
+
+	// Drop Healing-Laser if not available anymore
+	if(m_aWeapons[WEAPON_RIFLE].m_SpecialAmmo == 0)
+		m_OwnLaserSubType[LASER_SUBTYPE_HEALING] = false;
+
+	for(int i = 0; i < LASER_MAX_SUBTYPE; i++)
+	{
+		m_QueuedLaser = ++m_QueuedLaser%LASER_MAX_SUBTYPE;
+		
+		if(m_QueuedLaser == LASER_SUBTYPE_NORMAL && m_OwnLaserSubType[LASER_SUBTYPE_RIDDLE])
+			m_QueuedLaser = LASER_SUBTYPE_RIDDLE;
+
+		if(m_OwnLaserSubType[m_QueuedLaser])
+			break;
+	}
+		
+	if(ActiveLaser == m_QueuedLaser)
+		return;
+	else
+	{
+		if(ActiveLaser == LASER_SUBTYPE_HEALING)
+                        m_aWeapons[WEAPON_RIFLE].m_SpecialAmmo = m_aWeapons[WEAPON_RIFLE].m_Ammo;
+		else
+			m_aWeapons[WEAPON_RIFLE].m_NormalAmmo = m_aWeapons[WEAPON_RIFLE].m_Ammo;
+		
+		m_aWeapons[WEAPON_RIFLE].m_SubType = m_QueuedLaser;
+	}
+
+	if(m_ActiveWeapon == WEAPON_RIFLE)
+		SetWeapon(WEAPON_HAMMER);
+
+	m_QueuedWeapon = WEAPON_RIFLE;
+	DoWeaponSwitch();
+}
+
+void CCharacter::AirStrike()
+{
+	if(!m_OwnAirstrike)
+	{
+		GameServer()->SendChatTarget(m_pPlayer->GetCID(),"No airstrike available.");
+		return;
+	}
+	else if(m_pPlayer->m_MutatorTeam <= TEAM_MUTANT)
+	{
+		GameServer()->SendChatTarget(m_pPlayer->GetCID(),"Mutants don't need airstrikes.");
+		return;
+	}
+	
+	m_OwnAirstrike--;
+
+	vec2 pStrikeDir = normalize(vec2(m_LatestInput.m_TargetX, m_LatestInput.m_TargetY)); 
+        for(int bomb = -320; bomb < (GameServer()->Collision()->GetWidth()+10)*32; bomb += g_Config.m_SvHumAirStrikeStep)
+        {
+		CProjectile *pProj = new CProjectile(GameWorld(), WEAPON_GRENADE,
+			m_pPlayer->GetCID(),
+			vec2(bomb,0),
+			pStrikeDir,
+			g_Config.m_SvAirStrikeTTL,
+			1, true, 0, SOUND_GRENADE_EXPLODE, WEAPON_GRENADE,
+			g_Config.m_SvAirStrikeClusters, WEAPON_GRENADE, Server()->TickSpeed()*GameServer()->Tuning()->m_GrenadeLifetime, 1, 1, 0, SOUND_GRENADE_EXPLODE);
+
+		// pack the Projectile and send it to the client Directly
+		CNetObj_Projectile p;
+		pProj->FillInfo(&p);
+
+		CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE);
+		Msg.AddInt(1);
+		for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++)
+			Msg.AddInt(((int *)&p)[i]);
+		Server()->SendMsg(&Msg, 0, m_pPlayer->GetCID());
+        }
+}
+
 void CCharacter::FireWeapon()
 {
 	if(m_ReloadTimer != 0)
@@ -250,10 +469,9 @@ void CCharacter::FireWeapon()
 	vec2 Direction = normalize(vec2(m_LatestInput.m_TargetX, m_LatestInput.m_TargetY));
 
 	bool FullAuto = false;
-	if(m_ActiveWeapon == WEAPON_GRENADE || m_ActiveWeapon == WEAPON_SHOTGUN || m_ActiveWeapon == WEAPON_RIFLE)
+	if(m_ActiveWeapon == WEAPON_GRENADE || m_ActiveWeapon == WEAPON_SHOTGUN || m_ActiveWeapon == WEAPON_RIFLE || m_TurretActive)
 		FullAuto = true;
 
-
 	// check if we gonna fire
 	bool WillFire = false;
 	if(CountInput(m_LatestPrevInput.m_Fire, m_LatestInput.m_Fire).m_Presses)
@@ -280,6 +498,25 @@ void CCharacter::FireWeapon()
 	{
 		case WEAPON_HAMMER:
 		{
+			// Create laserwall if human and not on Science station
+			if(m_pPlayer->m_MutatorTeam >= TEAM_HUMAN)
+			{
+				if(!m_OnScience && !m_OnEnergyUp)
+				{
+					if(m_LaserWall)
+					{
+						DestroyLaserWall();
+						GameServer()->CreateSound(m_Pos, SOUND_RIFLE_BOUNCE);
+					}
+					else if(m_Armor > 0)
+					{
+						DecreaseArmor(1);
+						m_LaserWall = new CLaserWall(GameWorld(), m_Pos, Direction, g_Config.m_SvLaserWallLength ,m_pPlayer->GetCID());
+						GameServer()->CreateSound(m_Pos, SOUND_WEAPON_NOAMMO);
+					}
+				}
+			}
+
 			// reset objects Hit
 			m_NumObjectsHit = 0;
 			GameServer()->CreateSound(m_Pos, SOUND_HAMMER_FIRE);
@@ -321,31 +558,96 @@ void CCharacter::FireWeapon()
 
 		case WEAPON_GUN:
 		{
-			CProjectile *pProj = new CProjectile(GameWorld(), WEAPON_GUN,
-				m_pPlayer->GetCID(),
-				ProjStartPos,
-				Direction,
-				(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GunLifetime),
-				1, 0, 0, -1, WEAPON_GUN);
-
-			// pack the Projectile and send it to the client Directly
-			CNetObj_Projectile p;
-			pProj->FillInfo(&p);
-
-			CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE);
-			Msg.AddInt(1);
-			for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++)
-				Msg.AddInt(((int *)&p)[i]);
-
-			Server()->SendMsg(&Msg, 0, m_pPlayer->GetCID());
-
-			GameServer()->CreateSound(m_Pos, SOUND_GUN_FIRE);
+			switch(m_TurretActive)
+			{
+				// normal gun behavior
+				case 0:
+				{
+					CProjectile *pProj;
+					if(m_pPlayer->m_ScienceExplored&SCIENCE_GUN_MK2)
+					{
+						pProj = new CProjectile(GameWorld(), WEAPON_GUN,
+							m_pPlayer->GetCID(),
+							ProjStartPos,
+							Direction,
+							(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GunLifetime),
+							1, 0, float(g_Config.m_SvGunMK2Force), -1, WEAPON_GUN);
+					}
+					else
+					{
+						pProj = new CProjectile(GameWorld(), WEAPON_GUN,
+							m_pPlayer->GetCID(),
+							ProjStartPos,
+							Direction,
+							(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GunLifetime),
+							1, 0, 0, -1, WEAPON_GUN);
+					}
+						
+
+					// pack the Projectile and send it to the client Directly
+					CNetObj_Projectile p;
+					pProj->FillInfo(&p);
+
+					CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE);
+					Msg.AddInt(1);
+					for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++)
+						Msg.AddInt(((int *)&p)[i]);
+	
+					Server()->SendMsg(&Msg, 0, m_pPlayer->GetCID());
+
+					GameServer()->CreateSound(m_Pos, SOUND_GUN_FIRE);
+				} break;
+				// Fire turret
+				case 1:
+				{
+					CProjectile *pProj = new CProjectile(GameWorld(), WEAPON_SHOTGUN,
+						m_pPlayer->GetCID(),
+						ProjStartPos,
+						Direction,
+						(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GunLifetime),
+						g_Config.m_SvSGTurretNonExpDmg, 1, 2.f, SOUND_GRENADE_EXPLODE, WEAPON_SHOTGUN);
+
+					// pack the Projectile and send it to the client Directly
+					CNetObj_Projectile p;
+					pProj->FillInfo(&p);
+
+					CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE);
+					Msg.AddInt(1);
+					for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++)
+						Msg.AddInt(((int *)&p)[i]);
+
+					Server()->SendMsg(&Msg, 0, m_pPlayer->GetCID());
+
+					GameServer()->CreateSound(m_Pos, SOUND_SHOTGUN_FIRE);
+					GameServer()->CreateSound(m_Pos, SOUND_WEAPON_NOAMMO);
+					GameServer()->CreateSound(m_Pos, SOUND_RIFLE_FIRE);
+				} break;
+			}
 		} break;
 
 		case WEAPON_SHOTGUN:
 		{
 			int ShotSpread = 2;
+			float HeroBonus;
+			int DoExplode;
+			int ExplodeSound;
 
+			if(m_pPlayer->m_MutatorTeam == TEAM_HERO || m_pPlayer->m_ScienceExplored&SCIENCE_SHOTGUN_FORCEX2)
+				HeroBonus = float(g_Config.m_SvShotMK2Force);
+			else
+				HeroBonus = 0;
+
+			if(m_pPlayer->m_ScienceExplored&SCIENCE_SHOTGUN_EXPL)
+			{
+				DoExplode = 1;
+				ExplodeSound = SOUND_GRENADE_EXPLODE;
+			}
+			else
+			{
+				DoExplode = 0;
+				ExplodeSound = -1;
+			}
+				
 			CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE);
 			Msg.AddInt(ShotSpread*2+1);
 
@@ -361,7 +663,7 @@ void CCharacter::FireWeapon()
 					ProjStartPos,
 					vec2(cosf(a), sinf(a))*Speed,
 					(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_ShotgunLifetime),
-					1, 0, 0, -1, WEAPON_SHOTGUN);
+					1, DoExplode, HeroBonus, ExplodeSound, WEAPON_SHOTGUN);
 
 				// pack the Projectile and send it to the client Directly
 				CNetObj_Projectile p;
@@ -378,13 +680,29 @@ void CCharacter::FireWeapon()
 
 		case WEAPON_GRENADE:
 		{
-			CProjectile *pProj = new CProjectile(GameWorld(), WEAPON_GRENADE,
-				m_pPlayer->GetCID(),
-				ProjStartPos,
-				Direction,
-				(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GrenadeLifetime),
-				1, true, 0, SOUND_GRENADE_EXPLODE, WEAPON_GRENADE);
-
+			CProjectile *pProj;
+			// Clusterbombs
+			if(m_pPlayer->m_ScienceExplored&SCIENCE_GRENADE_CLUSTER)
+			{
+				pProj = new CProjectile(GameWorld(), WEAPON_GRENADE,
+					m_pPlayer->GetCID(),
+					ProjStartPos,
+					Direction,
+					(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GrenadeLifetime),
+					1, true, 0, SOUND_GRENADE_EXPLODE, WEAPON_GRENADE,
+					g_Config.m_SvClusters, WEAPON_GRENADE, Server()->TickSpeed()*GameServer()->Tuning()->m_GrenadeLifetime, 1, 1, 0, SOUND_GRENADE_EXPLODE);
+			}
+			// Normal grenades
+			else
+			{
+				pProj = new CProjectile(GameWorld(), WEAPON_GRENADE,
+					m_pPlayer->GetCID(),
+					ProjStartPos,
+					Direction,
+					(int)(Server()->TickSpeed()*GameServer()->Tuning()->m_GrenadeLifetime),
+					1, true, 0, SOUND_GRENADE_EXPLODE, WEAPON_GRENADE);
+			}
+				
 			// pack the Projectile and send it to the client Directly
 			CNetObj_Projectile p;
 			pProj->FillInfo(&p);
@@ -400,8 +718,27 @@ void CCharacter::FireWeapon()
 
 		case WEAPON_RIFLE:
 		{
-			new CLaser(GameWorld(), m_Pos, Direction, GameServer()->Tuning()->m_LaserReach, m_pPlayer->GetCID());
-			GameServer()->CreateSound(m_Pos, SOUND_RIFLE_FIRE);
+			if(m_pPlayer->m_MutatorTeam == TEAM_REAPER)
+			// Black hole weapon
+			{
+				new CSingularinator(GameWorld(), m_Pos, Direction, GameServer()->Tuning()->m_LaserReach, m_pPlayer->GetCID(), Server()->Tick() + g_Config.m_SvSingularinatorTTL * Server()->TickSpeed());
+				GameServer()->CreateSound(m_Pos, SOUND_RIFLE_FIRE);
+				GameServer()->CreateSound(m_Pos, SOUND_SHOTGUN_FIRE);
+			}
+			else
+			// Human lasers
+			{
+				new CLaser(GameWorld(), m_Pos, Direction, GameServer()->Tuning()->m_LaserReach, m_pPlayer->GetCID(), m_aWeapons[WEAPON_RIFLE].m_SubType);
+				GameServer()->CreateSound(m_Pos, SOUND_RIFLE_FIRE);
+				if(m_aWeapons[WEAPON_RIFLE].m_SubType == LASER_SUBTYPE_HEALING)
+				{
+					m_aWeapons[WEAPON_RIFLE].m_SpecialAmmo--;
+					if(m_aWeapons[WEAPON_RIFLE].m_SpecialAmmo < 1)
+						m_OwnLaserSubType[LASER_SUBTYPE_HEALING] = 0;
+				}
+				else
+					m_aWeapons[WEAPON_RIFLE].m_NormalAmmo--;
+			}
 		} break;
 
 		case WEAPON_NINJA:
@@ -419,11 +756,18 @@ void CCharacter::FireWeapon()
 	}
 
 	m_AttackTick = Server()->Tick();
+	m_aWeapons[m_ActiveWeapon].m_Ammo--;
 
-	if(m_aWeapons[m_ActiveWeapon].m_Ammo > 0) // -1 == unlimited
-		m_aWeapons[m_ActiveWeapon].m_Ammo--;
-
-	if(!m_ReloadTimer)
+	if(m_pPlayer->m_MutatorTeam >= TEAM_HUMAN)
+	{
+		if(m_TurretActive) // use slower reload time for Turret 
+			m_ReloadTimer = Server()->TickSpeed()/10;
+		else if(m_pPlayer->m_ScienceExplored&SCIENCE_SHOTGUN_FASTRELOAD && m_ActiveWeapon == WEAPON_SHOTGUN)
+			m_ReloadTimer = (g_pData->m_Weapons.m_aId[m_ActiveWeapon].m_Firedelay/2) * Server()->TickSpeed() / 1000;
+		else if(!m_ReloadTimer)
+			m_ReloadTimer = g_pData->m_Weapons.m_aId[m_ActiveWeapon].m_Firedelay * Server()->TickSpeed() / 1000;
+	}
+	else if(!m_ReloadTimer)
 		m_ReloadTimer = g_pData->m_Weapons.m_aId[m_ActiveWeapon].m_Firedelay * Server()->TickSpeed() / 1000;
 }
 
@@ -443,6 +787,9 @@ void CCharacter::HandleWeapons()
 	FireWeapon();
 
 	// ammo regen
+	if(m_TurretActive)
+		return;
+
 	int AmmoRegenTime = g_pData->m_Weapons.m_aId[m_ActiveWeapon].m_Ammoregentime;
 	if(AmmoRegenTime)
 	{
@@ -468,9 +815,31 @@ void CCharacter::HandleWeapons()
 	return;
 }
 
-bool CCharacter::GiveWeapon(int Weapon, int Ammo)
+bool CCharacter::GiveWeapon(int Weapon, int Ammo, int Special)
 {
-	if(m_aWeapons[Weapon].m_Ammo < g_pData->m_Weapons.m_aId[Weapon].m_Maxammo || !m_aWeapons[Weapon].m_Got)
+	if(Weapon == WEAPON_RIFLE)
+	{
+		if(Special == 1)
+		{
+			if(m_aWeapons[Weapon].m_SpecialAmmo < g_pData->m_Weapons.m_aId[Weapon].m_Maxammo)
+			{
+				m_aWeapons[Weapon].m_Got = true;
+				m_aWeapons[Weapon].m_SpecialAmmo = min(g_pData->m_Weapons.m_aId[Weapon].m_Maxammo, Ammo);
+				if(m_ActiveWeapon == WEAPON_RIFLE && m_aWeapons[WEAPON_RIFLE].m_SubType == LASER_SUBTYPE_HEALING)
+					m_aWeapons[WEAPON_RIFLE].m_Ammo = m_aWeapons[WEAPON_RIFLE].m_SpecialAmmo;
+				return true;
+			}
+		}
+		else if(m_aWeapons[Weapon].m_NormalAmmo < g_pData->m_Weapons.m_aId[Weapon].m_Maxammo || !m_aWeapons[Weapon].m_Got)
+		{
+			m_aWeapons[Weapon].m_Got = true;
+			m_aWeapons[Weapon].m_NormalAmmo = min(g_pData->m_Weapons.m_aId[Weapon].m_Maxammo, Ammo);
+			if(m_ActiveWeapon == WEAPON_RIFLE && m_aWeapons[WEAPON_RIFLE].m_SubType != LASER_SUBTYPE_HEALING)
+				m_aWeapons[WEAPON_RIFLE].m_Ammo = m_aWeapons[WEAPON_RIFLE].m_NormalAmmo;
+			return true;
+		}
+	}
+	else if(m_aWeapons[Weapon].m_Ammo < g_pData->m_Weapons.m_aId[Weapon].m_Maxammo || !m_aWeapons[Weapon].m_Got)
 	{
 		m_aWeapons[Weapon].m_Got = true;
 		m_aWeapons[Weapon].m_Ammo = min(g_pData->m_Weapons.m_aId[Weapon].m_Maxammo, Ammo);
@@ -495,6 +864,15 @@ void CCharacter::SetEmote(int Emote, int
 {
 	m_EmoteType = Emote;
 	m_EmoteStop = Tick;
+	if(Emote == EMOTE_FLASHING)
+	{	
+		m_MutanticEyeOn = 1;
+	        m_MutanticEyeFlip = 1;
+		m_MutanticEyeFlipTick = Server()->Tick() + 250 * Server()->TickSpeed() / 1000;
+		m_EmoteType = EMOTE_NORMAL;
+	}	
+	else
+		m_MutanticEyeOn = 0;
 }
 
 void CCharacter::OnPredictedInput(CNetObj_PlayerInput *pNewInput)
@@ -517,6 +895,10 @@ void CCharacter::OnDirectInput(CNetObj_P
 	mem_copy(&m_LatestPrevInput, &m_LatestInput, sizeof(m_LatestInput));
 	mem_copy(&m_LatestInput, pNewInput, sizeof(m_LatestInput));
 
+        // it is not allowed to aim in the center
+	if(m_LatestInput.m_TargetX == 0 && m_LatestInput.m_TargetY == 0)
+		m_LatestInput.m_TargetY = -1;
+
 	if(m_NumInputs > 2 && m_pPlayer->GetTeam() != TEAM_SPECTATORS)
 	{
 		HandleWeaponSwitch();
@@ -540,33 +922,295 @@ void CCharacter::ResetInput()
 
 void CCharacter::Tick()
 {
-	if(m_pPlayer->m_ForceBalanced)
+	// useless for this mod
+	/*if(m_pPlayer->m_ForceBalanced)
 	{
 		char Buf[128];
 		str_format(Buf, sizeof(Buf), "You were moved to %s due to team balancing", GameServer()->m_pController->GetTeamName(m_pPlayer->GetTeam()));
 		GameServer()->SendBroadcast(Buf, m_pPlayer->GetCID());
 
 		m_pPlayer->m_ForceBalanced = false;
-	}
-
+	}*/
+	
+	// Get Input 	
 	m_Core.m_Input = m_Input;
 	m_Core.Tick(true);
 
+	// Reset to check again later
+	m_OnTurret = 0;
+	m_OnEnergyUp = 0;
+	m_OnReapinator = 0;
+	
+	// Get collisions
+	m_Col1 = GameServer()->Collision()->GetCollisionAt(m_Pos.x+m_ProximityRadius/3.f, m_Pos.y-m_ProximityRadius/3.f);
+	m_Col2 = GameServer()->Collision()->GetCollisionAt(m_Pos.x+m_ProximityRadius/3.f, m_Pos.y+m_ProximityRadius/3.f);
+	m_Col3 = GameServer()->Collision()->GetCollisionAt(m_Pos.x-m_ProximityRadius/3.f, m_Pos.y+m_ProximityRadius/3.f);
+	m_Col4 = GameServer()->Collision()->GetCollisionAt(m_Pos.x-m_ProximityRadius/3.f, m_Pos.y+m_ProximityRadius/3.f);
+
 	// handle death-tiles and leaving gamelayer
-	if(GameServer()->Collision()->GetCollisionAt(m_Pos.x+m_ProximityRadius/3.f, m_Pos.y-m_ProximityRadius/3.f)&CCollision::COLFLAG_DEATH ||
-		GameServer()->Collision()->GetCollisionAt(m_Pos.x+m_ProximityRadius/3.f, m_Pos.y+m_ProximityRadius/3.f)&CCollision::COLFLAG_DEATH ||
-		GameServer()->Collision()->GetCollisionAt(m_Pos.x-m_ProximityRadius/3.f, m_Pos.y-m_ProximityRadius/3.f)&CCollision::COLFLAG_DEATH ||
-		GameServer()->Collision()->GetCollisionAt(m_Pos.x-m_ProximityRadius/3.f, m_Pos.y+m_ProximityRadius/3.f)&CCollision::COLFLAG_DEATH ||
-		GameLayerClipped(m_Pos))
-	{
+	if(m_Col1&CCollision::COLFLAG_DEATH || m_Col2&CCollision::COLFLAG_DEATH || m_Col3&CCollision::COLFLAG_DEATH || m_Col4&CCollision::COLFLAG_DEATH 
+			|| GameLayerClipped(m_Pos))
 		Die(m_pPlayer->GetCID(), WEAPON_WORLD);
-	}
 
+	// handle invisible tiles
+	if(m_Col1&CCollision::COLFLAG_INVIS || m_Col2&CCollision::COLFLAG_INVIS || m_Col3&CCollision::COLFLAG_INVIS || m_Col4&CCollision::COLFLAG_INVIS)
+		m_Invisible = 1;
+	else
+		m_Invisible = 0;
+
+	if(m_Col1&CCollision::COLFLAG_BIOHAZARD || m_Col2&CCollision::COLFLAG_BIOHAZARD 
+			|| m_Col3&CCollision::COLFLAG_BIOHAZARD || m_Col4&CCollision::COLFLAG_BIOHAZARD)
+	{
+		if(m_pPlayer->m_MutatorTeam > TEAM_REAPER && !(m_pPlayer->m_MutatorTeam == TEAM_MUTANT && m_pPlayer->m_MutaticLevels&MUTATOR_NOBIOHAZARD))
+		{
+		        if(!m_MutanticEyeOn && Server()->Tick() - m_BioHazardDamageTick > 0)
+			{
+                		TakeMinorDamage();
+				GameServer()->CreateSound(m_Pos, SOUND_PLAYER_PAIN_SHORT);
+				m_BioHazardDamageTick = Server()->Tick() + 150 * Server()->TickSpeed() / 1000;
+				m_EmoteType = EMOTE_PAIN;
+				m_EmoteStop = Server()->Tick() + 500 * Server()->TickSpeed() / 1000;
+        		}	
+		}
+	}
+	else if(m_Col1&CCollision::COLFLAG_REAPER || m_Col2&CCollision::COLFLAG_REAPER
+			|| m_Col3&CCollision::COLFLAG_REAPER || m_Col4&CCollision::COLFLAG_REAPER)
+	{
+		m_OnReapinator = 1;
+	}
+	else if(m_Col1&CCollision::COLFLAG_ENERGYUP || m_Col2&CCollision::COLFLAG_ENERGYUP
+			|| m_Col3&CCollision::COLFLAG_ENERGYUP || m_Col4&CCollision::COLFLAG_ENERGYUP)
+	{
+		m_OnEnergyUp = 1;
+	}
+	// handle human only tiles
+	else if(m_pPlayer->m_MutatorTeam >= TEAM_HUMAN)
+	{
+		// set on turret switch
+		if(m_Col1&CCollision::COLFLAG_TURRET || m_Col2&CCollision::COLFLAG_TURRET 
+				|| m_Col3&CCollision::COLFLAG_TURRET || m_Col4&CCollision::COLFLAG_TURRET)
+			m_OnTurret = 1; 
+	}
+	
 	// handle Weapons
 	HandleWeapons();
 
+	// handle human stuff
+	if(m_pPlayer->m_MutatorTeam >= TEAM_HUMAN)
+	{
+		// OnScience Reset
+		if(m_OnScience && Server()->Tick() - m_OnScienceOffTick > 0)
+			m_OnScience = 0;
+
+		// turret 
+		if(m_OnTurret)
+		{
+			m_TurretActive = 1;
+			if(!m_PrevOnTurret)
+			{
+				m_LastWeapon = m_ActiveWeapon;
+				m_PrevTurretSwitchAmmo = m_aWeapons[WEAPON_GUN].m_Ammo;
+				m_PrevTurretSwitchGot = m_aWeapons[WEAPON_GUN].m_Got;
+				SetWeapon(WEAPON_GUN);
+				m_aWeapons[m_ActiveWeapon].m_Ammo = m_TurretAmmo;
+				m_aWeapons[m_ActiveWeapon].m_Got = true;
+				
+			}
+			if(m_aWeapons[m_ActiveWeapon].m_Ammo < 1 && m_Armor > 0)
+			{
+				m_aWeapons[m_ActiveWeapon].m_Ammo = 10;
+				m_Armor--;
+			}
+		}	
+		else
+		{
+			// reset weapon on turret leave 
+			if(m_PrevOnTurret)
+			{
+				m_TurretAmmo = m_aWeapons[WEAPON_GUN].m_Ammo;
+				m_aWeapons[WEAPON_GUN].m_Ammo = m_PrevTurretSwitchAmmo;
+				m_aWeapons[WEAPON_GUN].m_Got = m_PrevTurretSwitchGot;
+				SetWeapon(m_LastWeapon);
+				m_PrevOnTurret = 0;
+				m_TurretActive = 0;
+			}
+		}
+
+		// Reapinator 
+		if(m_OnReapinator)
+		{
+			if(!m_PrevOnReapinator && Server()->Tick() - m_ShowInfoTick > 0)
+			{
+				if(GameServer()->m_pController->ReapinatorOnline())
+					GameServer()->SendChatTarget(m_pPlayer->GetCID(),"Reapinator: Prototype restriction: Mutant required.");
+				else
+					GameServer()->SendChatTarget(m_pPlayer->GetCID(),"Reapinator: Warmup in progress. Please come again later.");
+				m_ShowInfoTick = Server()->Tick() + 2 * Server()->TickSpeed();
+			}
+		}
+		// Energynator
+		else if(m_OnEnergyUp)
+		{
+			if(Server()->Tick() - m_EnergyUpTick > 0)
+			{
+				if(GameServer()->m_pController->MutPowerSupply())
+				{
+					if(m_LaserWall)
+					{
+						GameServer()->SendChatTarget(m_pPlayer->GetCID(),"Deactivating laserwall for fillup.");
+						DestroyLaserWall();
+                                                GameServer()->CreateSound(m_Pos, SOUND_RIFLE_BOUNCE);
+					}
+
+					m_EnergyUpTick = Server()->Tick() + 200 * Server()->TickSpeed() / 1000;
+					if(m_Armor < 10)
+					{
+						GameServer()->CreateSound(m_Pos, SOUND_PICKUP_ARMOR);
+						IncreaseArmor(1);
+					}
+	
+					if(m_Health < 10)
+					{
+						GameServer()->CreateSound(m_Pos, SOUND_PICKUP_HEALTH);
+						IncreaseHealth(1);
+					}
+				}
+				else if(!m_PrevOnEnergyUp)
+				{
+					m_EnergyUpTick = Server()->Tick() + 4 * Server()->TickSpeed();
+					GameServer()->SendChatTarget(m_pPlayer->GetCID(),"Generator is down!");
+				}	
+			}
+		}
+
+		// show laser subtype as broadcast
+		if (m_LaserCycleInfoSwitch == 1 && Server()->Tick() - m_LaserCycleTick > 0)
+		{
+			m_LaserCycleInfoSwitch = 0;
+			if(m_ActiveWeapon == WEAPON_RIFLE)
+				GameServer()->SendBroadcast(CLaser::m_SubDescription[m_aWeapons[WEAPON_RIFLE].m_SubType], m_pPlayer->GetCID());
+				
+		}
+	}
+	else
+	{
+		// Reapinator
+		if(m_OnReapinator)
+		{
+			if(GameServer()->m_pController->ReapinatorOnline())
+			{
+				if(m_pPlayer->m_MutatorTeam == TEAM_MUTANT)
+				{
+					if(m_pPlayer->m_Score >= g_Config.m_SvReapinatorMinScore)
+					{
+						char aBuf[512];
+						str_format(aBuf,sizeof(aBuf),"Alica-KI: WARNING: %s metamorphosed and became an alien-reaper!",Server()->ClientName(m_pPlayer->GetCID()));
+						GameServer()->SendChatTarget(-1,aBuf);
+						BecameReaper();
+					}
+					else if(!m_PrevOnReapinator && Server()->Tick() - m_ShowInfoTick > 0)
+					{
+						GameServer()->SendChatTarget(m_pPlayer->GetCID(),"Reapinator: Too less score for metamorphose. Please come again later.");
+						m_ShowInfoTick = Server()->Tick() + 2 * Server()->TickSpeed();	
+					}	
+				}
+				else if(!m_PrevOnReapinator && Server()->Tick() - m_ShowInfoTick > 0)
+				{
+					if(g_Config.m_SvHappyMsgOn)
+					{
+						switch(rand()%5)
+						{
+							case 0: GameServer()->SendChatTarget(m_pPlayer->GetCID(),g_Config.m_SvHappyReapinatorA); break;
+							case 1: GameServer()->SendChatTarget(m_pPlayer->GetCID(),g_Config.m_SvHappyReapinatorB); break;
+							case 2: GameServer()->SendChatTarget(m_pPlayer->GetCID(),g_Config.m_SvHappyReapinatorC); break;
+							case 3:	GameServer()->SendChatTarget(m_pPlayer->GetCID(),g_Config.m_SvHappyReapinatorD); break;
+							case 4: GameServer()->SendChatTarget(m_pPlayer->GetCID(),g_Config.m_SvHappyReapinatorE); break;
+						}
+						m_ShowInfoTick = Server()->Tick() + 2 * Server()->TickSpeed();	
+					}
+				}
+			}
+			else if(!m_PrevOnReapinator && Server()->Tick() - m_ShowInfoTick > 0)
+			{
+				GameServer()->SendChatTarget(m_pPlayer->GetCID(),"Reapinator: Warmup in progress. Please come again later.");
+				m_ShowInfoTick = Server()->Tick() + 2 * Server()->TickSpeed();	
+			}
+		}
+		// Sceptic Energynator text 
+		else if(m_OnEnergyUp && GameServer()->m_pController->MutPowerSupply())
+		{
+			if(g_Config.m_SvScepticMsgOn && !m_PrevOnEnergyUp && Server()->Tick() - m_ShowInfoTick > 0)
+			{
+				switch(rand()%5)
+				{
+					case 0: GameServer()->SendChatTarget(m_pPlayer->GetCID(),g_Config.m_SvScepticEnergynatorA); break;
+					case 1: GameServer()->SendChatTarget(m_pPlayer->GetCID(),g_Config.m_SvScepticEnergynatorB); break;
+					case 2: GameServer()->SendChatTarget(m_pPlayer->GetCID(),g_Config.m_SvScepticEnergynatorC); break;
+					case 3:	GameServer()->SendChatTarget(m_pPlayer->GetCID(),g_Config.m_SvScepticEnergynatorD); break;
+					case 4: GameServer()->SendChatTarget(-1,g_Config.m_SvScepticEnergynatorE); break;
+				}
+				m_ShowInfoTick = Server()->Tick() + 2 * Server()->TickSpeed();	
+			}
+		}
+
+		// Mutantic emote (add random)
+		if(Server()->Tick() - m_MutanticEmoteTick > 0)
+		{
+			SetEmote(EMOTE_FLASHING, Server()->Tick() + 2000 * Server()->TickSpeed() / 1000);
+			m_MutanticEmoteTick = Server()->Tick() + (1000 * g_Config.m_SvMutEmoteDelay + (1000 * rand()%10)) * Server()->TickSpeed() / 1000;
+		}
+		
+		if((m_pPlayer->m_MutatorTeam == TEAM_REAPER || m_pPlayer->m_MutaticLevels&MUTATOR_SELFHEAL) && Server()->Tick() - m_AlienMetaTick > 0)
+		{
+			IncreaseHealth(1);
+			IncreaseArmor(1);
+			m_AlienMetaTick = Server()->Tick() + 2 * Server()->TickSpeed();
+		}
+
+		// Alien Multijump
+		if(m_pPlayer->m_MutatorTeam == TEAM_REAPER || m_pPlayer->m_MutaticLevels&MUTATOR_JUMP)
+		{
+			if(m_Core.m_Jumped&2 && m_Input.m_Jump && !m_PrevInput.m_Jump && m_LatestInput.m_Jump)
+			{
+				m_MutanticArmorDJCount++;
+				if(m_MutanticArmorDJCount < 5) 
+					m_Core.m_Jumped = 1;	
+				// skip on step to avoid decrease of shield by mistake
+				else if(m_MutanticArmorDJCount > 6 && m_Armor)
+				{
+					m_Core.m_Jumped = 1;	
+					GameServer()->CreateSound(m_Pos, SOUND_BODY_LAND);
+					m_Armor--;
+					if(m_MutanticArmorDJCount > 10)
+						SetEmote(EMOTE_FLASHING, Server()->Tick() + 2000 * Server()->TickSpeed() / 1000);
+				}
+			}
+			else if(m_MutanticArmorDJCount && IsGrounded()) 
+				m_MutanticArmorDJCount = 0;
+		}
+		else
+		{
+			if(m_Core.m_Jumped&2 && m_Input.m_Jump && !m_PrevInput.m_Jump && m_LatestInput.m_Jump)
+			{
+				m_MutanticArmorDJCount++;
+				if(m_MutanticArmorDJCount < 2)
+					m_Core.m_Jumped = 1;
+			}
+			else if(m_MutanticArmorDJCount && IsGrounded())
+			m_MutanticArmorDJCount = 0;
+		}
+	
+		// Alien Hook
+		if(m_pPlayer->m_MutaticLevels&MUTATOR_ENDLESSHOOK)
+			m_Core.m_HookTick = 0;
+	}
+
 	// Previnput
 	m_PrevInput = m_Input;
+	m_PrevOnTurret = m_OnTurret;	
+	m_PrevOnScience = m_OnScience;
+	m_PrevOnEnergyUp = m_OnEnergyUp;
+	m_PrevOnReapinator = m_OnReapinator;
 	return;
 }
 
@@ -653,6 +1297,23 @@ void CCharacter::TickDefered()
 	}
 }
 
+void CCharacter::TickPaused()
+{
+	if(GameServer()->m_pController->MutGameRunning() == 0)
+		return;
+
+	++m_AttackTick;
+	++m_DamageTakenTick;
+	++m_Ninja.m_ActivationTick;
+	++m_ReckoningTick;
+	if(m_LastAction != -1)
+		++m_LastAction;
+	if(m_aWeapons[m_ActiveWeapon].m_AmmoRegenStart > -1)
+		++m_aWeapons[m_ActiveWeapon].m_AmmoRegenStart;
+	if(m_EmoteStop > -1)
+		++m_EmoteStop;
+}
+
 bool CCharacter::IncreaseHealth(int Amount)
 {
 	if(m_Health >= 10)
@@ -669,17 +1330,33 @@ bool CCharacter::IncreaseArmor(int Amoun
 	return true;
 }
 
+bool CCharacter::DecreaseArmor(int Amount)
+{
+        if(m_Armor <= 0)
+                return false;
+        m_Armor = clamp(m_Armor-Amount, 0, 10);
+        return true;
+}
+
 void CCharacter::Die(int Killer, int Weapon)
 {
+	int ModeSpecial = 0;
 	// we got to wait 0.5 secs before respawning
 	m_pPlayer->m_RespawnTick = Server()->Tick()+Server()->TickSpeed()/2;
-	int ModeSpecial = GameServer()->m_pController->OnCharacterDeath(this, GameServer()->m_apPlayers[Killer], Weapon);
+	if(Killer < 0 && Weapon > -1)
+	{
+		Killer = m_pPlayer->GetCID();
+		Weapon = -1;
+	}
 
-	char aBuf[256];
+	if(Killer >= 0)
+		ModeSpecial = GameServer()->m_pController->OnCharacterDeath(this, GameServer()->m_apPlayers[Killer], Weapon);
+		
+	/*char aBuf[256];
 	str_format(aBuf, sizeof(aBuf), "kill killer='%d:%s' victim='%d:%s' weapon=%d special=%d",
 		Killer, Server()->ClientName(Killer),
 		m_pPlayer->GetCID(), Server()->ClientName(m_pPlayer->GetCID()), Weapon, ModeSpecial);
-	GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf);
+	GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf);*/
 
 	// send the kill message
 	CNetMsg_Sv_KillMsg Msg;
@@ -688,10 +1365,128 @@ void CCharacter::Die(int Killer, int Wea
 	Msg.m_Weapon = Weapon;
 	Msg.m_ModeSpecial = ModeSpecial;
 	Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, -1);
-
 	// a nice sound
 	GameServer()->CreateSound(m_Pos, SOUND_PLAYER_DIE);
 
+	// Victim is human
+	if(m_pPlayer->m_MutatorTeam >= TEAM_HUMAN)
+        {
+		if(GameServer()->m_pController->MutGameRunning())
+			GameServer()->SendBroadcast("You are now a Mutant!", m_pPlayer->GetCID());
+
+		if(Killer != m_pPlayer->GetCID() && Killer >= 0)	
+		{
+			if(GameServer()->m_apPlayers[Killer])
+			{
+				// Killer was human (teamkiller)
+				if(GameServer()->m_apPlayers[Killer]->m_MutatorTeam > TEAM_MUTANT)
+				{
+					GameServer()->m_apPlayers[Killer]->m_Score--;
+					GameServer()->m_apPlayers[Killer]->m_BonusScore--;
+					GameServer()->m_apPlayers[Killer]->m_BonusScore2--;
+					GameServer()->m_apPlayers[Killer]->m_MultiScore = 0;
+					GameServer()->m_apPlayers[Killer]->m_MultiScoreTick = Server()->Tick();
+					Mutate();
+					GameServer()->CreateSound(m_Pos, SOUND_PLAYER_PAIN_LONG);
+					if(GameServer()->m_pController->MutGameRunning())
+                				return;
+				}
+				// Killer was mutant
+				else 
+				{	
+					if(Server()->Tick() - GameServer()->m_apPlayers[Killer]->m_MultiScoreTick >= 0)
+						GameServer()->m_apPlayers[Killer]->m_MultiScore = 1; 
+					else
+						GameServer()->m_apPlayers[Killer]->m_MultiScore++;
+
+					GameServer()->m_apPlayers[Killer]->m_Score += (1 * GameServer()->m_apPlayers[Killer]->m_MultiScore);
+
+					// Extra bonus for hero
+					if(m_pPlayer->m_MutatorTeam == TEAM_HERO)
+					{
+						GameServer()->m_apPlayers[Killer]->m_Score++;
+						GameServer()->m_apPlayers[Killer]->m_BonusScore++;
+					}
+
+					GameServer()->m_apPlayers[Killer]->m_MultiScoreTick = Server()->Tick() + 2 * Server()->TickSpeed();
+					GameServer()->m_apPlayers[Killer]->m_BonusScore++;
+					if(GameServer()->m_apPlayers[Killer]->m_BonusScore >= g_Config.m_SvMetamorphoseCount)
+					{
+						GameServer()->m_apPlayers[Killer]->m_BonusScore = 0;
+						CCharacter * pMutChar = GameServer()->m_apPlayers[Killer]->GetCharacter();
+						if(pMutChar)
+							pMutChar->Metamorphose();	
+					}
+					if(Weapon != WEAPON_RIFLE) // if not black-hole weapon
+					{
+						Mutate();
+						GameServer()->CreateSound(m_Pos, SOUND_PLAYER_PAIN_LONG);
+                				return;
+					}
+				}
+			}
+		}
+		else
+		// Killer was "world"
+		{
+			Mutate();
+			m_pPlayer->m_Score--;	
+		}
+        }
+	else // Victim is mutant
+	{
+		if(Killer != m_pPlayer->GetCID() && Killer >= 0)
+		{
+			if(GameServer()->m_apPlayers[Killer])
+			{
+				// Killer is human 
+				if(GameServer()->m_apPlayers[Killer]->m_MutatorTeam >= TEAM_HUMAN)
+				{
+					if(Server()->Tick() - GameServer()->m_apPlayers[Killer]->m_MultiScoreTick >= 0)
+						GameServer()->m_apPlayers[Killer]->m_MultiScore = 1; 
+					else
+						GameServer()->m_apPlayers[Killer]->m_MultiScore++;
+
+					GameServer()->m_apPlayers[Killer]->m_Score += (1 * GameServer()->m_apPlayers[Killer]->m_MultiScore);
+					GameServer()->m_apPlayers[Killer]->m_MultiScoreTick = Server()->Tick() + 2 * Server()->TickSpeed();
+					
+					if(GameServer()->m_apPlayers[Killer]->m_MutatorTeam != TEAM_HERO)
+						GameServer()->m_apPlayers[Killer]->m_BonusScore++;
+
+					if(GameServer()->m_apPlayers[Killer]->m_BonusScore >= g_Config.m_SvHeroBecameScore && GameServer()->m_apPlayers[Killer]->m_MutatorTeam != TEAM_HERO)
+					{
+						CCharacter * pHeroChar;
+						pHeroChar = GameServer()->m_apPlayers[Killer]->GetCharacter();
+						if(pHeroChar)
+						{
+							GameServer()->SendBroadcast("You became a hero", GameServer()->m_apPlayers[Killer]->GetCID());
+							char bBuf[512];
+							str_format(bBuf,sizeof(bBuf),"%s becames a hero", 
+									Server()->ClientName(GameServer()->m_apPlayers[Killer]->GetCID()));
+        						GameServer()->SendChatTarget(-1, bBuf);
+							pHeroChar->BecameHero(1);
+						}
+					}
+					else if(g_Config.m_SvAutoResearchScore)
+					{
+						GameServer()->m_apPlayers[Killer]->m_BonusScore2++;
+						if(GameServer()->m_apPlayers[Killer]->m_BonusScore2 >= g_Config.m_SvAutoResearchScore)
+						{
+							GameServer()->m_apPlayers[Killer]->m_BonusScore2 = 0;
+							if(!g_Config.m_SvEmptyResearch || (g_Config.m_SvEmptyResearch && !GameServer()->m_pController->FoundHammerPickups()))
+							{
+								CCharacter * pHumChar = GameServer()->m_apPlayers[Killer]->GetCharacter();
+								if(pHumChar)
+									pHumChar->ScienceResearch(1);
+							}
+						}
+					}
+				}
+			}
+		}
+	}
+		
+
 	// this is for auto respawn after 3 secs
 	m_pPlayer->m_DieTick = Server()->Tick();
 
@@ -701,12 +1496,97 @@ void CCharacter::Die(int Killer, int Wea
 	GameServer()->CreateDeath(m_Pos, m_pPlayer->GetCID());
 }
 
+void CCharacter::TakeMinorDamage()
+{
+	m_DamageTaken++;
+	if(Server()->Tick() < m_DamageTakenTick+25)
+		GameServer()->CreateDamageInd(m_Pos, m_DamageTaken*0.25f, 1);
+	else
+	{
+		m_DamageTaken = 0;
+		GameServer()->CreateDamageInd(m_Pos, 0, 1);
+	}
+	m_DamageTakenTick = Server()->Tick();
+
+        m_Health--;
+	if(m_Health < 1)
+		Die(m_pPlayer->GetCID(), WEAPON_WORLD);
+}
+
 bool CCharacter::TakeDamage(vec2 Force, int Dmg, int From, int Weapon)
 {
 	m_Core.m_Vel += Force;
 
-	if(GameServer()->m_pController->IsFriendlyFire(m_pPlayer->GetCID(), From) && !g_Config.m_SvTeamdamage)
-		return false;
+	// Friendly fire is checked somewhat different below 
+	/*if(GameServer()->m_pController->IsFriendlyFire(m_pPlayer->GetCID(), From) && !g_Config.m_SvTeamdamage)
+		return false;*/
+
+	// Mutator 
+	if(From >= 0)
+	{
+		if(!g_Config.m_SvTeamdamage && From != m_pPlayer->GetCID() && GameServer()->m_apPlayers[From] 
+				&& (GameServer()->m_apPlayers[From]->m_MutatorTeam >= TEAM_HUMAN && m_pPlayer->m_MutatorTeam >= TEAM_HUMAN && !(m_Pos.y < 0 && Weapon == WEAPON_HAMMER)))
+			return false;	
+		if(GameServer()->m_apPlayers[From] && GameServer()->m_apPlayers[From]->m_MutatorTeam <= TEAM_MUTANT) 
+		{
+			if(Weapon != WEAPON_HAMMER)
+				return false;
+
+			if(m_pPlayer->m_MutatorTeam <= TEAM_MUTANT)
+			{
+				if((IncreaseHealth(3) + IncreaseArmor(3)) > 0)
+				{
+					m_DamageTaken++;
+					if(Server()->Tick() < m_DamageTakenTick+25)
+        				{
+						// make sure that the damage indicators doesn't group together
+						GameServer()->CreateDamageInd(m_Pos, m_DamageTaken*0.25f, 3);
+					}
+					else
+					{
+ 						m_DamageTaken = 0;
+						GameServer()->CreateDamageInd(m_Pos, 0, 3);
+					}
+					m_DamageTakenTick = Server()->Tick();
+				}
+				return false;
+			}
+			else if(m_pPlayer->m_MutatorTeam == TEAM_HERO)
+			{
+				Dmg = 8;
+			}
+			else
+			{
+				Die(From, Weapon);
+				return true;
+			}
+		}
+	}
+
+	if(m_pPlayer->m_MutatorTeam <= TEAM_MUTANT)
+	{
+		// Spawn Protection 
+		if(Server()->Tick() - m_MutanticSpawnProtection < 0)
+			return false;
+		
+		// Mutatic special protection (flashing eyes)
+		if(m_MutanticEyeOn == 1)
+		{
+			if(m_pPlayer->m_MutatorTeam == TEAM_MUTANT)
+				Dmg = 1;
+			else // Reaper that got flashing eyes increase health when hit...
+			{
+				IncreaseArmor(Dmg);
+				IncreaseHealth(Dmg);
+				int Mask = CmaskOne(m_pPlayer->GetCID());
+				GameServer()->CreateSound(m_Pos, SOUND_HIT, Mask);
+				return false;
+			}
+		}
+		else if(m_pPlayer->m_MutatorTeam == TEAM_REAPER && Weapon != WEAPON_RIFLE)
+			Dmg = max(1, Dmg/3);
+			
+	}
 
 	// m_pPlayer only inflicts half damage on self
 	if(From == m_pPlayer->GetCID())
@@ -777,7 +1657,7 @@ bool CCharacter::TakeDamage(vec2 Force,
 			if (pChr)
 			{
 				pChr->m_EmoteType = EMOTE_HAPPY;
-				pChr->m_EmoteStop = Server()->Tick() + Server()->TickSpeed();
+				pChr->m_EmoteStop = Server()->Tick() + 2 * Server()->TickSpeed();
 			}
 		}
 
@@ -799,6 +1679,19 @@ void CCharacter::Snap(int SnappingClient
 {
 	if(NetworkClipped(SnappingClient))
 		return;
+	
+
+	// Mutator - handle invisible 
+	if(m_Invisible)
+	{
+		if(m_pPlayer->m_MutatorTeam <= TEAM_MUTANT)
+		{
+			if(GameServer()->m_apPlayers[SnappingClient]->m_MutatorTeam >= TEAM_HUMAN)  
+				return;
+		}
+		else if(GameServer()->m_apPlayers[SnappingClient]->m_MutatorTeam <= TEAM_MUTANT)
+			return;
+	}
 
 	CNetObj_Character *pCharacter = static_cast<CNetObj_Character *>(Server()->SnapNewItem(NETOBJTYPE_CHARACTER, m_pPlayer->GetCID(), sizeof(CNetObj_Character)));
 	if(!pCharacter)
@@ -819,10 +1712,29 @@ void CCharacter::Snap(int SnappingClient
 	}
 
 	// set emote
-	if (m_EmoteStop < Server()->Tick())
+	if(m_EmoteStop < Server()->Tick())
 	{
-		m_EmoteType = EMOTE_NORMAL;
+		if(m_pPlayer->m_MutatorTeam > TEAM_REAPER)
+			m_EmoteType = EMOTE_NORMAL;
+		else
+			m_EmoteType = EMOTE_ANGRY;
+
 		m_EmoteStop = -1;
+		m_MutanticEyeOn = 0;
+	} 
+	else if(m_MutanticEyeOn == 1)
+	{
+		if(Server()->Tick() - m_MutanticEyeFlipTick > 0)
+		{
+			m_MutanticEyeFlip = 1 - m_MutanticEyeFlip;
+		
+			m_MutanticEyeFlipTick = Server()->Tick() + 200 * Server()->TickSpeed() / 1000;
+			switch(m_MutanticEyeFlip)
+			{
+				case 0: m_EmoteType = EMOTE_NORMAL; break;
+				case 1: m_EmoteType = EMOTE_SURPRISE; break;
+			}
+		}
 	}
 
 	pCharacter->m_Emote = m_EmoteType;
@@ -853,3 +1765,464 @@ void CCharacter::Snap(int SnappingClient
 
 	pCharacter->m_PlayerFlags = GetPlayer()->m_PlayerFlags;
 }
+
+void CCharacter::Mutate()
+{
+	m_pPlayer->m_MutatorTeam = TEAM_MUTANT;
+	GiveWeapon(WEAPON_HAMMER, -1);
+	m_TurretActive = 0;
+	m_OnTurret = 0;
+	m_PrevOnTurret = 0;
+	m_pPlayer->m_ScienceCount = 0;
+	SetWeapon(WEAPON_HAMMER);
+	SetEmote(EMOTE_FLASHING,Server()->Tick() + 2500 * Server()->TickSpeed() / 1000);
+	m_AlienMetaTick = Server()->Tick() + 30 * Server()->TickSpeed();
+	IncreaseHealth(10);
+	m_Armor = 0;
+	m_pPlayer->m_MyHumanScore = m_pPlayer->m_Score;
+	m_pPlayer->m_Score = 0;
+	m_pPlayer->m_BonusScore = 0;
+	m_pPlayer->m_MultiScore = 0;
+	m_pPlayer->m_MultiScoreTick = Server()->Tick();
+	m_OnReapinator = 0;
+	m_PrevOnReapinator = 0;
+}
+
+void CCharacter::ReMutate()
+{
+	m_pPlayer->m_MutatorTeam = TEAM_HUMAN;
+	GiveWeapon(WEAPON_GUN,10);
+	GiveWeapon(WEAPON_HAMMER,-1);
+	m_OnTurret = 0;
+	m_PrevOnTurret = 0;
+	m_pPlayer->m_ScienceCount = 0;
+	SetWeapon(WEAPON_GUN);
+	SetEmote(EMOTE_FLASHING,Server()->Tick() + 2500 * Server()->TickSpeed() / 1000);
+	IncreaseHealth(10);
+	m_aWeapons[WEAPON_GUN].m_Got = 1;
+	m_pPlayer->m_MyMutantScore = m_pPlayer->m_Score;
+	m_pPlayer->m_Score = m_pPlayer->m_MyHumanScore;
+	m_pPlayer->m_BonusScore = 0;
+	m_pPlayer->m_MultiScore = 0;
+	m_pPlayer->m_MultiScoreTick = Server()->Tick();
+}
+
+void CCharacter::BecameHero(bool AirStrike)
+{
+	m_pPlayer->m_Score += 3;
+	m_pPlayer->m_MutatorTeam = TEAM_HERO;
+	GiveWeapon(WEAPON_SHOTGUN, 10);
+	SetWeapon(WEAPON_SHOTGUN);
+	IncreaseHealth(10);
+	m_pPlayer->m_BonusScore = 0;
+	m_pPlayer->m_MultiScore = 0;
+	m_pPlayer->m_MultiScoreTick = Server()->Tick();
+	if(AirStrike && g_Config.m_SvHeroAirstrike)
+	{
+		char bBuf[512];
+		str_format(bBuf,sizeof(bBuf),"%s %s", Server()->ClientName(m_pPlayer->GetCID()),g_Config.m_SvInfoGotAirstrike);
+		GameServer()->SendChatTarget(-1, bBuf);
+		m_OwnAirstrike++;
+	}
+	m_pPlayer->m_ScienceExplored |= SCIENCE_SHOTGUN_FORCEX2;
+}		
+
+void CCharacter::BecameReaper()
+{
+	m_pPlayer->m_Score += 3;
+	m_pPlayer->m_MutatorTeam = TEAM_REAPER;
+	IncreaseHealth(10);
+	IncreaseArmor(10);
+	m_pPlayer->m_BonusScore = 0;
+	
+	GiveWeapon(WEAPON_RIFLE,1);
+	m_aWeapons[WEAPON_RIFLE].m_Ammo = g_Config.m_SvReaperAmmo;
+	m_aWeapons[WEAPON_GUN].m_Got = 0;
+	m_aWeapons[WEAPON_GUN].m_Ammo = 0;
+	m_aWeapons[WEAPON_SHOTGUN].m_Got = 0;
+	m_aWeapons[WEAPON_SHOTGUN].m_Ammo = 0;
+	m_aWeapons[WEAPON_GRENADE].m_Got = 0;
+	m_aWeapons[WEAPON_GRENADE].m_Ammo = 0;
+	SetWeapon(WEAPON_HAMMER);
+	m_pPlayer->m_MultiScore = 0;
+	m_pPlayer->m_MultiScoreTick = Server()->Tick();
+}
+
+void CCharacter::Metamorphose()
+{
+	int Lottery = rand()%8;
+	IncreaseHealth(5);
+	IncreaseArmor(5);
+
+	if(!(m_pPlayer->m_Score >= g_Config.m_SvReaperMinScore && Lottery == 5))
+	{
+		Lottery = m_pPlayer->m_ScienceCount;
+		m_pPlayer->m_ScienceCount++;
+		if(Lottery > 4)
+			return;
+	}
+	
+	char aBuf[512];
+	char bBuf[512];
+
+	m_pPlayer->m_MutaticLevels |= 1 << Lottery; 
+
+	switch(Lottery)
+	{
+		case 0:
+			{
+				str_format(bBuf,sizeof(bBuf),"%s metamorphosed and gained starting-shields", Server()->ClientName(m_pPlayer->GetCID()));
+				str_format(aBuf,sizeof(aBuf),"You gained starting-shields");
+			}
+			break;
+		case 1:
+			{
+				str_format(bBuf,sizeof(bBuf),"%s metamorphosed and gained biohazard-resistance", Server()->ClientName(m_pPlayer->GetCID()));
+				str_format(aBuf,sizeof(aBuf),"You gained biohazard-resistance");
+			}
+			break;
+		case 2:
+			{
+				str_format(bBuf,sizeof(bBuf),"%s metamorphosed and gained alien-multijump", Server()->ClientName(m_pPlayer->GetCID()));
+				str_format(aBuf,sizeof(aBuf),"You gained alien-multijump");
+			}
+			break;
+		case 3:
+			{
+				str_format(bBuf,sizeof(bBuf),"%s metamorphosed and gained alien-superhook", Server()->ClientName(m_pPlayer->GetCID()));
+				str_format(aBuf,sizeof(aBuf),"You gained alien-superhook");
+			}
+			break;
+		case 4:
+			{
+				str_format(bBuf,sizeof(bBuf),"%s metamorphosed and gained alien-selfheal", Server()->ClientName(m_pPlayer->GetCID()));
+				str_format(aBuf,sizeof(aBuf),"You gained alien-selfheal");
+			}
+			break;
+		case 5:
+			{
+				str_format(bBuf,sizeof(bBuf),"Alica-KI: WARNING: %s metamorphosed and became an alien-reaper!", Server()->ClientName(m_pPlayer->GetCID()));
+				str_format(aBuf,sizeof(aBuf),"You are now a Reaper!");
+				BecameReaper();
+			}
+			break;
+	}	
+
+	GameServer()->SendBroadcast(aBuf, m_pPlayer->GetCID());
+	if(Lottery == 5 || g_Config.m_SvBonusMsgOn)
+		GameServer()->SendChatTarget(-1, bBuf);
+}
+
+void CCharacter::ScienceResearch(bool AutoResearch)
+{
+	int Lottery = rand()%16;
+	int remember_me = 0;
+	char aBuf[512];
+	char bBuf[512];
+
+	m_pPlayer->m_ScienceCount = 0;
+
+
+	if(Lottery < 13)
+	{
+		if(m_pPlayer->m_ScienceExplored&(1 << Lottery) && Lottery < 9)
+		{
+			if(g_Config.m_SvSaveScienceScore && m_pPlayer->m_Score > g_Config.m_SvSaveScienceScore)
+			{
+				remember_me = 1; 
+				m_pPlayer->m_ScienceRemembered |= 1 << Lottery;
+				m_pPlayer->m_ScienceExplored |= 1 << Lottery;
+			}
+			else
+				Lottery = -1;
+		}
+		else
+			m_pPlayer->m_ScienceExplored |= 1 << Lottery;
+	}
+
+	if(Lottery > 12 || Lottery == -1 || (Lottery == 9 && m_pPlayer->m_MutatorTeam == TEAM_HERO))
+	{
+		if(!AutoResearch)
+		{
+			str_format(aBuf,sizeof(aBuf),"Scientific research: Failed!");
+			GameServer()->SendBroadcast(aBuf, m_pPlayer->GetCID());
+		}
+		return;
+	}
+
+	switch(Lottery)
+	{
+		case 0:
+			{
+				m_OwnLaserSubType[LASER_SUBTYPE_TELE] = true;
+				m_QueuedLaser = LASER_SUBTYPE_TELE;
+				m_aWeapons[WEAPON_RIFLE].m_SubType = LASER_SUBTYPE_TELE;
+				GiveWeapon(WEAPON_RIFLE,10);
+				if(!remember_me)
+				{
+					str_format(aBuf,sizeof(aBuf),"You gained Tele-Laserinator");
+					str_format(bBuf,sizeof(bBuf),"%s %s Tele-Laserinator", Server()->ClientName(m_pPlayer->GetCID()), AutoResearch == 1 ? g_Config.m_SvInfoGot : g_Config.m_SvInfoResearched);
+				}
+				else
+				{
+					str_format(aBuf,sizeof(aBuf),"Tele-Laserinator: Saved!");
+					str_format(bBuf,sizeof(bBuf),"%s saved: Tele-Laserinator", Server()->ClientName(m_pPlayer->GetCID()));
+				}
+			}
+			break;
+		case 1:
+			{
+				m_OwnLaserSubType[LASER_SUBTYPE_HEALING] = true;
+				m_QueuedLaser = LASER_SUBTYPE_HEALING;
+				if(m_ActiveWeapon != WEAPON_RIFLE)
+					m_aWeapons[WEAPON_RIFLE].m_SubType = LASER_SUBTYPE_HEALING;
+
+				GiveWeapon(WEAPON_RIFLE,g_Config.m_SvHealingAmmo,1);
+				if(!remember_me)
+				{
+					str_format(aBuf,sizeof(aBuf),"You gained Healing-Laser");
+					str_format(bBuf,sizeof(bBuf),"%s %s Healing-Laser", Server()->ClientName(m_pPlayer->GetCID()), AutoResearch == 1 ? g_Config.m_SvInfoGot : g_Config.m_SvInfoResearched);
+				}
+				else
+				{
+					str_format(aBuf,sizeof(aBuf),"Healing-Laser: Saved!");
+					str_format(bBuf,sizeof(bBuf),"%s saved: Healing-Laser", Server()->ClientName(m_pPlayer->GetCID()));
+				}
+			}
+			break;
+		case 2:
+			{
+				m_OwnLaserSubType[LASER_SUBTYPE_RIDDLE] = true;
+				m_QueuedLaser = LASER_SUBTYPE_RIDDLE;
+				m_aWeapons[WEAPON_RIFLE].m_SubType = LASER_SUBTYPE_RIDDLE;
+				GiveWeapon(WEAPON_RIFLE,10);
+				if(!remember_me)
+				{
+					str_format(aBuf,sizeof(aBuf),"You gained Riddle-Laser");
+					str_format(bBuf,sizeof(bBuf),"%s %s Riddle-Laser", Server()->ClientName(m_pPlayer->GetCID()), AutoResearch == 1 ? g_Config.m_SvInfoGot : g_Config.m_SvInfoResearched);
+				}
+				else
+				{
+					str_format(aBuf,sizeof(aBuf),"Riddle-Laser: Saved!");
+					str_format(bBuf,sizeof(bBuf),"%s saved: Riddle-Laser", Server()->ClientName(m_pPlayer->GetCID()));
+				}
+			}
+			break;
+		case 3:
+			{
+				GiveWeapon(WEAPON_SHOTGUN,10);
+				if(!remember_me)
+				{
+					str_format(aBuf,sizeof(aBuf),"You gained Shootgun MKII");
+					str_format(bBuf,sizeof(bBuf),"%s %s SG-MKII", Server()->ClientName(m_pPlayer->GetCID()), AutoResearch == 1 ? g_Config.m_SvInfoGot : g_Config.m_SvInfoResearched);
+				}
+				else
+				{
+					str_format(aBuf,sizeof(aBuf),"Shootgun MKII: Saved!");
+					str_format(bBuf,sizeof(bBuf),"%s saved: SG-MKII", Server()->ClientName(m_pPlayer->GetCID()));
+				}
+			}
+			break;
+		case 4:
+			{ 
+				if(!remember_me)
+				{
+					str_format(aBuf,sizeof(aBuf),"You gained SG-Ammo MKII");
+					str_format(bBuf,sizeof(bBuf),"%s %s SG-Ammo MKII", Server()->ClientName(m_pPlayer->GetCID()), AutoResearch == 1 ? g_Config.m_SvInfoGot : g_Config.m_SvInfoResearched);
+				}
+				else
+				{
+					str_format(aBuf,sizeof(aBuf),"SG-Ammo MKII: Saved!");
+					str_format(bBuf,sizeof(bBuf),"%s saved: SG-Ammo MKII", Server()->ClientName(m_pPlayer->GetCID()));
+				}
+			}
+			break;
+		case 5:
+			{
+				if(!remember_me)
+				{
+					str_format(aBuf,sizeof(aBuf),"You gained Cluster-Grenades");
+					str_format(bBuf,sizeof(bBuf),"%s %s Cluster-Grenades", Server()->ClientName(m_pPlayer->GetCID()), AutoResearch == 1 ? g_Config.m_SvInfoGot : g_Config.m_SvInfoResearched);
+				}
+				else
+				{
+					str_format(aBuf,sizeof(aBuf),"Cluster-Grenades: Saved!");
+					str_format(bBuf,sizeof(bBuf),"%s saved: Cluster-Grenades", Server()->ClientName(m_pPlayer->GetCID()));
+				}
+			}
+			break;
+		case 6:
+			{
+				if(!remember_me)
+				{
+					str_format(aBuf,sizeof(aBuf),"You gained Gun-Ammo MKII");
+					str_format(bBuf,sizeof(bBuf),"%s %s Gun-Ammo MKII", Server()->ClientName(m_pPlayer->GetCID()), AutoResearch == 1 ? g_Config.m_SvInfoGot : g_Config.m_SvInfoResearched);
+				}
+				else
+				{
+					str_format(aBuf,sizeof(aBuf),"Gun-Ammo MKII: Saved!");
+					str_format(bBuf,sizeof(bBuf),"%s saved: Gun-Ammo MKII", Server()->ClientName(m_pPlayer->GetCID()));
+				}
+			}
+			break;
+		case 7:
+			{
+				if(!remember_me)
+				{
+					str_format(aBuf,sizeof(aBuf),"You gained SG-Speed-kit");
+					str_format(bBuf,sizeof(bBuf),"%s %s SG-Speed-kit", Server()->ClientName(m_pPlayer->GetCID()), AutoResearch == 1 ? g_Config.m_SvInfoGot : g_Config.m_SvInfoResearched);
+				}
+				else
+				{
+					str_format(aBuf,sizeof(aBuf),"SG-Speed-kit: Saved!");
+					str_format(bBuf,sizeof(bBuf),"%s saved: SG-Speed-kit", Server()->ClientName(m_pPlayer->GetCID()));
+				}
+			}
+			break;
+		case 8:
+			{
+				if(!remember_me)
+				{
+					str_format(aBuf,sizeof(aBuf),"You gained Super-Battery");
+					str_format(bBuf,sizeof(bBuf),"%s %s Super-Battery", Server()->ClientName(m_pPlayer->GetCID()), AutoResearch == 1 ? g_Config.m_SvInfoGot : g_Config.m_SvInfoResearched);
+				}
+				else
+				{
+					str_format(aBuf,sizeof(aBuf),"Super-Battery: Saved!");
+					str_format(bBuf,sizeof(bBuf),"%s saved: Super-Battery", Server()->ClientName(m_pPlayer->GetCID()));
+				}
+			}
+			break;
+		case 9:
+			{
+				str_format(aBuf,sizeof(aBuf),"You became a hero");
+				str_format(bBuf,sizeof(bBuf),"%s gained: Hero-genetics", Server()->ClientName(m_pPlayer->GetCID()));
+				BecameHero(0);
+			}
+			break;
+		case 10:
+			{
+				str_format(aBuf,sizeof(aBuf),"You gained weapons refill.");
+				str_format(bBuf,sizeof(bBuf),"%s gained: Weapons refill", Server()->ClientName(m_pPlayer->GetCID()));
+				GiveWeapon(WEAPON_GUN,10);
+				GiveWeapon(WEAPON_SHOTGUN,10);
+				GiveWeapon(WEAPON_GRENADE,10);
+				GiveWeapon(WEAPON_RIFLE,10);
+				if(m_pPlayer->m_ScienceExplored&SCIENCE_LASER_HEALING)
+				{
+					if(m_ActiveWeapon != WEAPON_RIFLE)
+						m_aWeapons[WEAPON_RIFLE].m_SubType = LASER_SUBTYPE_HEALING;
+
+					GiveWeapon(WEAPON_RIFLE,g_Config.m_SvHealingAmmo,1);
+				}
+			}
+			break;
+		case 11:
+			{
+				str_format(aBuf,sizeof(aBuf),"You gained shields fillup");
+				str_format(bBuf,sizeof(bBuf),"%s gained: Shield fillup", Server()->ClientName(m_pPlayer->GetCID()));
+				IncreaseHealth(10);
+				IncreaseArmor(10);
+			}
+			break;
+		case 12:
+			{
+				if(!AutoResearch)
+					str_format(bBuf,sizeof(bBuf),"%s %s", Server()->ClientName(m_pPlayer->GetCID()), g_Config.m_SvInfoHackedAirstrike);
+				else
+					str_format(bBuf,sizeof(bBuf),"%s %s", Server()->ClientName(m_pPlayer->GetCID()), g_Config.m_SvInfoGotAirstrike);
+
+				str_format(aBuf,sizeof(aBuf),"You got an airstrike. (use /airstrike)");
+				m_OwnAirstrike++;
+			}
+			break;
+	}	
+	GameServer()->SendBroadcast(aBuf, m_pPlayer->GetCID());
+	if(g_Config.m_SvBonusMsgOn)
+		GameServer()->SendChatTarget(-1, bBuf);
+}
+
+vec2 CCharacter::GetVel()
+{
+	return m_Core.m_Vel;
+}
+                     
+void CCharacter::SetVel(vec2 Vel)
+{
+	m_Core.m_Vel = Vel;
+}
+
+void CCharacter::SetPos(vec2 Pos)
+{
+	m_Core.m_Pos = Pos;
+}
+
+void CCharacter::DestroyLaserWall()
+{
+	if(m_LaserWall)
+	{
+		GameServer()->m_World.DestroyEntity(m_LaserWall);
+		m_LaserWall = 0;
+	}
+}
+
+int CCharacter::GetActiveWeapon()
+{
+	return m_ActiveWeapon;
+}
+
+bool CCharacter::IsFiring()
+{
+	if((m_Input.m_Fire&1) != 0)
+		return 1;
+	else
+		return 0;
+}
+
+void CCharacter::SetOnScience(bool val)
+{
+	m_OnScience = val;
+	m_OnScienceOffTick = Server()->Tick() + 500 * Server()->TickSpeed() / 1000;
+}
+
+bool CCharacter::IsOnScience()
+{
+	return m_OnScience;
+}
+
+bool CCharacter::PrevOnScience()
+{
+	return m_PrevOnScience;
+}
+
+bool CCharacter::BreakCircuit()
+{
+	if(m_pPlayer->m_MutatorTeam <= TEAM_MUTANT)
+	{
+		GameServer()->m_pController->MutSetPowerSupply(0);
+		char aBuf[512];
+		str_format(aBuf,sizeof(aBuf),"\nAlica-AI: WARNING! Generator destroyed by %s!\n",Server()->ClientName(m_pPlayer->GetCID()));
+		GameServer()->SendChatTarget(-1, aBuf);
+		m_pPlayer->m_Score += 3;
+		SetEmote(EMOTE_FLASHING, Server()->Tick() + 2000 * Server()->TickSpeed() / 1000);
+		Metamorphose();
+		return true;
+	}
+	else
+		return false;
+}
+
+void CCharacter::SetShowInfoTick(int Tick)
+{
+	m_ShowInfoTick = Tick;
+}
+
+int CCharacter::GetShowInfoTick()
+{
+	return m_ShowInfoTick;
+}
+
+bool CCharacter::MutanticEyes()
+{
+	return m_MutanticEyeOn;
+}
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/entities/character.h alien-rc4/src//game/server/entities/character.h
--- teeworlds-b177-r50edfd37-source/src//game/server/entities/character.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/server/entities/character.h	2012-06-14 23:57:39.000000000 +0200
@@ -8,6 +8,7 @@
 #include <game/generated/protocol.h>
 
 #include <game/gamecore.h>
+#include <game/server/entities/laser.h>
 
 enum
 {
@@ -30,6 +31,7 @@ public:
 	virtual void Destroy();
 	virtual void Tick();
 	virtual void TickDefered();
+	virtual void TickPaused();
 	virtual void Snap(int SnappingClient);
 
 	bool IsGrounded();
@@ -48,6 +50,7 @@ public:
 
 	void Die(int Killer, int Weapon);
 	bool TakeDamage(vec2 Force, int Dmg, int From, int Weapon);
+	void TakeMinorDamage();
 
 	bool Spawn(class CPlayer *pPlayer, vec2 Pos);
 	bool Remove();
@@ -55,7 +58,7 @@ public:
 	bool IncreaseHealth(int Amount);
 	bool IncreaseArmor(int Amount);
 
-	bool GiveWeapon(int Weapon, int Ammo);
+	bool GiveWeapon(int Weapon, int Ammo, int Special=0);
 	void GiveNinja();
 
 	void SetEmote(int Emote, int Tick);
@@ -63,10 +66,71 @@ public:
 	bool IsAlive() const { return m_Alive; }
 	class CPlayer *GetPlayer() { return m_pPlayer; }
 
+	// Mutator
+	void SetPreStartGame();
+	void Mutate();
+	void ReMutate();
+	void Metamorphose();
+	void ScienceResearch(bool AutoResearch);
+	void BecameHero(bool AirStrike);
+	void BecameReaper();
+	void AirStrike();
+
+	vec2 GetVel();
+	void SetVel(vec2 Vel);
+	void SetPos(vec2 Pos);
+	bool DecreaseArmor(int Amount);
+	int GetActiveWeapon();
+	bool IsFiring();
+	void CycleLaserSubTypes();
+	void DestroyLaserWall();
+	void SetOnScience(bool val);
+	bool IsOnScience();
+	bool PrevOnScience();
+	bool BreakCircuit();
+	void ShowScanResults();
+	void SetShowInfoTick(int Tick);
+	int GetShowInfoTick();
+	bool MutanticEyes();
+
 private:
+	
 	// player controlling this character
 	class CPlayer *m_pPlayer;
 
+	// Mutator
+	class CLaserWall *m_LaserWall;
+	int m_MutanticEmoteTick;
+	int m_BioHazardDamageTick;
+	int m_AlienMetaTick;
+	int m_MutanticSpawnProtection;
+	int m_MutanticArmorDJCount;
+	bool m_OnScience;
+	int m_OnScienceOffTick;
+	bool m_PrevOnScience;
+	bool m_Invisible;
+	bool m_PrevOnReapinator;
+	bool m_OnReapinator;
+
+	bool m_OnTurret;
+	bool m_TurretActive;
+	int m_TurretAmmo;
+	int m_PrevTurretSwitchAmmo;
+	bool m_PrevTurretSwitchGot;
+	bool m_PrevOnTurret;
+	int m_OwnAirstrike;
+	
+	int m_EnergyUpTick;
+	int m_OnEnergyUp;
+	int m_PrevOnEnergyUp;
+
+	int m_ShowInfoTick;
+
+        int m_Col1;
+        int m_Col2;
+        int m_Col3;
+        int m_Col4;
+	
 	bool m_Alive;
 
 	// weapon info
@@ -79,12 +143,21 @@ private:
 		int m_Ammo;
 		int m_Ammocost;
 		bool m_Got;
+		int m_SubType;
+		int m_SpecialAmmo;
+		int m_NormalAmmo;
 
 	} m_aWeapons[NUM_WEAPONS];
 
 	int m_ActiveWeapon;
 	int m_LastWeapon;
+
+	// Mutator 
 	int m_QueuedWeapon;
+	int m_QueuedLaser;
+	int m_LaserCycleTick;
+	bool m_LaserCycleInfoSwitch;
+	bool m_OwnLaserSubType[LASER_MAX_SUBTYPE];
 
 	int m_ReloadTimer;
 	int m_AttackTick;
@@ -94,6 +167,11 @@ private:
 	int m_EmoteType;
 	int m_EmoteStop;
 
+	// Mutator
+	bool m_MutanticEyeOn;
+	bool m_MutanticEyeFlip;
+	int m_MutanticEyeFlipTick;
+
 	// last tick that the player took any action ie some input
 	int m_LastAction;
 
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/entities/flag.cpp alien-rc4/src//game/server/entities/flag.cpp
--- teeworlds-b177-r50edfd37-source/src//game/server/entities/flag.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/server/entities/flag.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -23,6 +23,13 @@ void CFlag::Reset()
 	m_GrabTick = 0;
 }
 
+void CFlag::TickPaused()
+{
+	++m_DropTick;
+	if(m_GrabTick)
+		++m_GrabTick;
+}
+
 void CFlag::Snap(int SnappingClient)
 {
 	if(NetworkClipped(SnappingClient))
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/entities/flag.h alien-rc4/src//game/server/entities/flag.h
--- teeworlds-b177-r50edfd37-source/src//game/server/entities/flag.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/server/entities/flag.h	2012-06-14 23:57:39.000000000 +0200
@@ -21,6 +21,7 @@ public:
 	CFlag(CGameWorld *pGameWorld, int Team);
 
 	virtual void Reset();
+	virtual void TickPaused();
 	virtual void Snap(int SnappingClient);
 };
 
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/entities/laser.cpp alien-rc4/src//game/server/entities/laser.cpp
--- teeworlds-b177-r50edfd37-source/src//game/server/entities/laser.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/server/entities/laser.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -3,10 +3,12 @@
 #include <game/generated/protocol.h>
 #include <game/server/gamecontext.h>
 #include "laser.h"
+#include <game/server/gamemodes/mod.h>
 
-CLaser::CLaser(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEnergy, int Owner)
+CLaser::CLaser(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEnergy, int Owner, int SubType)
 : CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER)
 {
+	m_SubType = SubType;
 	m_Pos = Pos;
 	m_Owner = Owner;
 	m_Energy = StartEnergy;
@@ -18,19 +20,76 @@ CLaser::CLaser(CGameWorld *pGameWorld, v
 }
 
 
+// Mutator 
+const char *CLaser::m_SubDescription[] =
+{
+	"* Laser *", "* Riddle-Laser *", "* Tele-Laserinator *", "* Healing-Laser *"
+};
+
 bool CLaser::HitCharacter(vec2 From, vec2 To)
 {
 	vec2 At;
-	CCharacter *OwnerChar = GameServer()->GetPlayerChar(m_Owner);
-	CCharacter *Hit = GameServer()->m_World.IntersectCharacter(m_Pos, To, 0.f, At, OwnerChar);
-	if(!Hit)
+	CCharacter *pOwnerChar = GameServer()->GetPlayerChar(m_Owner);
+	CCharacter *pHit = GameServer()->m_World.IntersectCharacter(m_Pos, To, 0.f, At, pOwnerChar);
+	if(!pHit)
 		return false;
 
-	m_From = From;
-	m_Pos = At;
-	m_Energy = -1;
-	Hit->TakeDamage(vec2(0.f, 0.f), GameServer()->Tuning()->m_LaserDamage, m_Owner, WEAPON_RIFLE);
-	return true;
+	// Tele-Laser
+	if(m_SubType == LASER_SUBTYPE_TELE && pOwnerChar)
+	{
+		if(pHit->IsAlive() && pOwnerChar->IsAlive())
+		{
+			vec2 TeleFrom = pOwnerChar->m_Pos;
+			vec2 TeleTo = pHit->m_Pos;
+			pOwnerChar->SetPos(TeleTo);
+			pHit->SetPos(TeleFrom);
+		}
+		else
+			return false;
+	}
+
+	// Healing-Laser	
+	if(m_SubType == LASER_SUBTYPE_HEALING)
+	{
+		if(pHit->GetPlayer()->m_MutatorTeam <= TEAM_MUTANT)
+		{
+			pHit->ReMutate();
+			if(pOwnerChar && pHit)
+			{
+				CPlayer *pKiller = pOwnerChar->GetPlayer();
+				CPlayer *pVictim = pHit->GetPlayer();
+				if(pKiller && pVictim)
+				{
+					int ModeSpecial = GameServer()->m_pController->OnCharacterDeath(pHit, GameServer()->m_apPlayers[pKiller->GetCID()], WEAPON_RIFLE);
+					CNetMsg_Sv_KillMsg Msg;
+					Msg.m_Killer = pKiller->GetCID();
+					Msg.m_Victim = pVictim->GetCID();
+					Msg.m_Weapon = WEAPON_RIFLE;
+					Msg.m_ModeSpecial = ModeSpecial;
+					Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, -1);
+					pKiller->m_Score++;
+				}
+			}
+		}
+		else
+			pHit->IncreaseHealth(10);
+	}
+	else
+		pHit->TakeDamage(vec2(0.f, 0.f), GameServer()->Tuning()->m_LaserDamage, m_Owner, WEAPON_RIFLE);
+
+	// Riddle-Laser
+	if(m_SubType == LASER_SUBTYPE_RIDDLE)
+	{
+		GameServer()->CreateSound(m_Pos, SOUND_RIFLE_BOUNCE);
+		return false;
+	}
+	else
+	{
+		m_From = From;
+		m_Pos = At;
+		m_Energy = -1;
+		return true;
+	}
 }
 
 void CLaser::DoBounce()
@@ -91,6 +150,11 @@ void CLaser::Tick()
 		DoBounce();
 }
 
+void CLaser::TickPaused()
+{
+	++m_EvalTick;
+}
+
 void CLaser::Snap(int SnappingClient)
 {
 	if(NetworkClipped(SnappingClient))
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/entities/laser.h alien-rc4/src//game/server/entities/laser.h
--- teeworlds-b177-r50edfd37-source/src//game/server/entities/laser.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/server/entities/laser.h	2012-06-14 23:57:39.000000000 +0200
@@ -5,14 +5,28 @@
 
 #include <game/server/entity.h>
 
+
+// Mutator
+enum
+{
+        LASER_SUBTYPE_NORMAL=0,
+        LASER_SUBTYPE_RIDDLE,
+        LASER_SUBTYPE_TELE,
+        LASER_SUBTYPE_HEALING,
+	LASER_MAX_SUBTYPE,
+};
+
+
 class CLaser : public CEntity
 {
 public:
-	CLaser(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEnergy, int Owner);
+	CLaser(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEnergy, int Owner, int SubType);
 
 	virtual void Reset();
 	virtual void Tick();
+	virtual void TickPaused();
 	virtual void Snap(int SnappingClient);
+	static const char * m_SubDescription[];
 
 protected:
 	bool HitCharacter(vec2 From, vec2 To);
@@ -25,6 +39,7 @@ private:
 	int m_Bounces;
 	int m_EvalTick;
 	int m_Owner;
+	int m_SubType;
 };
 
 #endif
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/entities/laserturret.cpp alien-rc4/src//game/server/entities/laserturret.cpp
--- teeworlds-b177-r50edfd37-source/src//game/server/entities/laserturret.cpp	1970-01-01 01:00:00.000000000 +0100
+++ alien-rc4/src//game/server/entities/laserturret.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -0,0 +1,78 @@
+/* (c) Martin Grasberger - See alien-license.txt and licence.txt in the root of the distribution for more information. */
+#include <game/generated/protocol.h>
+#include <game/server/gamecontext.h>
+#include "laser.h"
+#include "laserturret.h"
+#include <game/server/gamemodes/mod.h>
+#include <engine/shared/config.h>
+
+CLaserTurret::CLaserTurret(CGameWorld *pGameWorld, vec2 Pos)
+: CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER)
+{
+	m_Pos = Pos;
+	m_FireDelayTick = Server()->Tick();
+	GameWorld()->InsertEntity(this);
+}
+
+bool CLaserTurret::AimVictim()
+{
+	float ClosestRange = 9999; // just dummy maxval out of range to get some start-value for searching nearest
+	CCharacter *pClosest = 0;
+	vec2 CheckVel;
+
+	CCharacter *p = (CCharacter *)GameServer()->m_World.FindFirst(CGameWorld::ENTTYPE_CHARACTER);
+	for(; p; p = (CCharacter *)p->TypeNext())
+	{
+		// just aim what you see
+		if(!p || !p->IsAlive() || GameServer()->Collision()->IntersectLine(m_Pos, p->m_Pos, 0x0, 0x0))
+			continue;	
+		
+		// just aim if victim moved fast enough (slow movement = no detection)
+		if(length(p->GetVel()) < g_Config.m_SvMaxTurretAimVel)
+			continue;	
+
+		// just fire on mutants? 
+		if(g_Config.m_SvTurretAimNoHumans && p->GetPlayer()->m_MutatorTeam >= TEAM_HUMAN)
+			continue;
+		
+		float Len = distance(m_Pos, p->m_Pos);
+		if(Len < p->m_ProximityRadius+g_Config.m_SvTurretRange)
+		{
+			if(Len < ClosestRange)
+			{
+				ClosestRange = Len;
+				pClosest = p;
+			}
+		}
+	}
+	
+	if(pClosest)
+	{
+		GameServer()->CreateSound(m_Pos, SOUND_RIFLE_FIRE);
+		new CLaser(GameWorld(), m_Pos, normalize(pClosest->m_Pos - m_Pos), GameServer()->Tuning()->m_LaserReach, -1, LASER_SUBTYPE_NORMAL);
+		return true;
+	}
+	else
+		return false;
+}
+
+void CLaserTurret::Reset()
+{
+	return;
+}
+
+void CLaserTurret::Tick()
+{
+	if(Server()->Tick() - m_FireDelayTick > 0)
+	{
+		if(GameServer()->m_pController->MutPowerSupply() == 1 && AimVictim())
+			m_FireDelayTick = Server()->Tick() + 600 * Server()->TickSpeed() / 1000;
+		else
+			m_FireDelayTick = Server()->Tick() + 10 * Server()->TickSpeed() / 1000;
+	}
+}
+
+void CLaserTurret::Snap(int SnappingClient)
+{
+	return;
+}
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/entities/laserturret.h alien-rc4/src//game/server/entities/laserturret.h
--- teeworlds-b177-r50edfd37-source/src//game/server/entities/laserturret.h	1970-01-01 01:00:00.000000000 +0100
+++ alien-rc4/src//game/server/entities/laserturret.h	2012-06-14 23:57:39.000000000 +0200
@@ -0,0 +1,25 @@
+/* (c) Martin Grasberger - See alien-license.txt and licence.txt in the root of the distribution for more information. */
+#ifndef GAME_SERVER_ENTITIES_LASERTURRET_H
+#define GAME_SERVER_ENTITIES_LASERTURRET_H
+
+#include <game/server/entity.h>
+
+
+class CLaserTurret : public CEntity
+{
+public:
+	CLaserTurret(CGameWorld *pGameWorld, vec2 Pos);
+
+	virtual void Reset();
+	virtual void Tick();
+	virtual void Snap(int SnappingClient);
+	static const char * m_SubDescription[];
+
+protected:
+	bool AimVictim();
+
+private:
+	int m_FireDelayTick;
+};
+
+#endif
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/entities/laserwall.cpp alien-rc4/src//game/server/entities/laserwall.cpp
--- teeworlds-b177-r50edfd37-source/src//game/server/entities/laserwall.cpp	1970-01-01 01:00:00.000000000 +0100
+++ alien-rc4/src//game/server/entities/laserwall.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -0,0 +1,155 @@
+/* (c) Martin Grasberger - See alien-license.txt and licence.txt in the root of the distribution for more information. */
+#include <game/generated/protocol.h>
+#include <game/server/gamecontext.h>
+#include "laserwall.h"
+#include <game/server/gamemodes/mod.h>
+#include <engine/shared/config.h>
+
+CLaserWall::CLaserWall(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEnergy, int Owner)
+: CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER)
+{
+	m_Pos = Pos;
+	m_Owner = Owner;
+	m_Energy = StartEnergy;
+	m_Dir = Direction;
+	m_From = Pos; 
+	m_FromFinal = m_Pos + m_Dir * m_Energy;
+	m_EvalTick = 0;
+
+	CCharacter *pOwnerChar = GameServer()->GetPlayerChar(m_Owner);
+	if(!pOwnerChar)
+		return;
+	else if(pOwnerChar->GetPlayer()->m_ScienceExplored&SCIENCE_BATTERY)
+		m_ConsumePowerTick = Server()->Tick() + g_Config.m_SvLaserWallDelay * Server()->TickSpeed() + g_Config.m_SvSuperBattery * Server()->TickSpeed() / 1000;
+	else
+		m_ConsumePowerTick = Server()->Tick() + g_Config.m_SvLaserWallDelay * Server()->TickSpeed() + g_Config.m_SvNormalBattery * Server()->TickSpeed() / 1000;
+	
+	m_FirstTick = Server()->Tick();	
+	m_InitDelayTick = Server()->Tick() + Server()->TickSpeed();	
+	m_InitDelayCounter = 0;
+	GameWorld()->InsertEntity(this);
+}
+
+
+bool CLaserWall::HitCharacter(vec2 From, vec2 To)
+{
+	vec2 At;
+	CCharacter *pOwnerChar = GameServer()->GetPlayerChar(m_Owner);
+
+	// Check if owner is still alive and no Mutant
+	if(!pOwnerChar)
+	{
+		GameServer()->m_World.DestroyEntity(this);
+		return false;
+	} 
+	else if(pOwnerChar->GetPlayer()->m_MutatorTeam <= TEAM_MUTANT)
+	{
+		pOwnerChar->DestroyLaserWall();
+		return false;
+	}
+	
+	// Check absolute timelimit if required	
+	if((g_Config.m_SvLWLimitNonAlMap && !GameServer()->m_pController->FoundHammerPickups()) || g_Config.m_SvLWLimit)
+	{
+		if(pOwnerChar->GetPlayer()->m_ScienceExplored&SCIENCE_BATTERY)
+		{
+			if(Server()->Tick() - (m_FirstTick + g_Config.m_SvSuperBattery * Server()->TickSpeed() / 100) > 0)
+			{	
+				GameServer()->CreateSound(m_Pos, SOUND_GRENADE_EXPLODE);
+				GameServer()->CreateSound(m_Pos, SOUND_RIFLE_BOUNCE);
+				GameServer()->CreateExplosion(m_Pos, m_Owner, WEAPON_RIFLE, false);
+				pOwnerChar->DestroyLaserWall();
+				return false;
+			}
+		}
+		else
+		{
+			if(Server()->Tick() - (m_FirstTick + g_Config.m_SvNormalBattery * Server()->TickSpeed() / 100) > 0)
+			{
+				GameServer()->CreateSound(m_Pos, SOUND_GRENADE_EXPLODE);
+				GameServer()->CreateSound(m_Pos, SOUND_RIFLE_BOUNCE);
+				GameServer()->CreateExplosion(m_Pos, m_Owner, WEAPON_RIFLE, false);
+				pOwnerChar->DestroyLaserWall();
+				return false;
+			}
+		}
+	}
+	
+	// Consume Power 
+	if(m_InitDelayCounter == g_Config.m_SvLaserWallDelay && Server()->Tick() - m_ConsumePowerTick > 0)
+	{
+		if(!pOwnerChar->DecreaseArmor(1))
+		{
+			pOwnerChar->DestroyLaserWall();
+			return false;
+		}
+		else
+		{
+			if(pOwnerChar->GetPlayer()->m_ScienceExplored&SCIENCE_BATTERY)
+				m_ConsumePowerTick = Server()->Tick() + g_Config.m_SvSuperBattery * Server()->TickSpeed() / 1000;
+			else
+				m_ConsumePowerTick = Server()->Tick() + g_Config.m_SvNormalBattery * Server()->TickSpeed() / 1000;
+		}
+	}	
+		
+	// Check Collision
+	CCharacter *pHit = GameServer()->m_World.IntersectCharacter(m_Pos, To, 0.f, At, pOwnerChar);
+	if(!pHit)
+		return false;
+
+	pHit->TakeDamage(vec2(0.f, 0.f), GameServer()->Tuning()->m_LaserDamage, m_Owner, WEAPON_RIFLE);
+	return true;
+}
+
+void CLaserWall::Reset()
+{
+	GameServer()->m_World.DestroyEntity(this);
+}
+
+void CLaserWall::Tick()
+{
+	if(Server()->Tick() % (170 * Server()->TickSpeed() / 1000) == 0)
+		m_EvalTick = Server()->Tick();
+	if(m_InitDelayCounter < g_Config.m_SvLaserWallDelay && Server()->Tick() - m_InitDelayTick > 0)
+	{
+		m_InitDelayCounter++;
+		if(m_InitDelayCounter == g_Config.m_SvLaserWallDelay)
+		{
+			GameServer()->CreateSound(m_Pos, SOUND_RIFLE_BOUNCE);
+			// Test if Laser hit wall (if yes just cut no bounce).
+			vec2 TestFrom = m_FromFinal;
+			if(GameServer()->Collision()->IntersectLine(m_Pos, TestFrom, 0x0, &TestFrom))
+			{
+				m_Energy = distance(TestFrom, m_Pos)*1.1f;
+				m_From = m_Pos + m_Dir * m_Energy;
+			}
+			else	
+				m_From = m_FromFinal;
+			
+			HitCharacter(m_Pos, m_From);	
+		}
+		else
+		{
+			GameServer()->CreateSound(m_Pos, SOUND_RIFLE_BOUNCE);
+			m_InitDelayTick = Server()->Tick() + Server()->TickSpeed();
+		}
+	}
+	else
+		HitCharacter(m_Pos, m_From);	
+}
+
+void CLaserWall::Snap(int SnappingClient)
+{
+	if(NetworkClipped(SnappingClient))
+		return;
+
+	CNetObj_Laser *pObj = static_cast<CNetObj_Laser *>(Server()->SnapNewItem(NETOBJTYPE_LASER, m_ID, sizeof(CNetObj_Laser)));
+	if(!pObj)
+		return;
+
+	pObj->m_X = (int)m_Pos.x;
+	pObj->m_Y = (int)m_Pos.y;
+	pObj->m_FromX = (int)m_From.x;
+	pObj->m_FromY = (int)m_From.y;
+	pObj->m_StartTick = m_EvalTick;
+}
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/entities/laserwall.h alien-rc4/src//game/server/entities/laserwall.h
--- teeworlds-b177-r50edfd37-source/src//game/server/entities/laserwall.h	1970-01-01 01:00:00.000000000 +0100
+++ alien-rc4/src//game/server/entities/laserwall.h	2012-06-14 23:57:39.000000000 +0200
@@ -0,0 +1,33 @@
+/* (c) Martin Grasberger - See alien-license.txt and licence.txt in the root of the distribution for more information. */
+#ifndef GAME_SERVER_ENTITIES_LASERWALL_H
+#define GAME_SERVER_ENTITIES_LASERWALL_H
+
+#include <game/server/entity.h>
+
+class CLaserWall : public CEntity
+{
+public:
+	CLaserWall(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEnergy, int Owner);
+
+	virtual void Reset();
+	virtual void Tick();
+	virtual void Snap(int SnappingClient);
+
+protected:
+	bool HitCharacter(vec2 From, vec2 To);
+
+private:
+	vec2 m_From;
+	vec2 m_FromFinal;
+	vec2 m_Dir;
+	float m_Energy;
+	int m_EvalTick;
+	int m_FirstTick;
+	int m_Owner;
+	int m_ConsumePowerTick;
+	int m_InitDelayTick;
+        int m_InitDelayCounter;
+
+};
+
+#endif
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/entities/pickup.cpp alien-rc4/src//game/server/entities/pickup.cpp
--- teeworlds-b177-r50edfd37-source/src//game/server/entities/pickup.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/server/entities/pickup.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -3,6 +3,8 @@
 #include <game/generated/protocol.h>
 #include <game/server/gamecontext.h>
 #include "pickup.h"
+#include <game/server/gamemodes/mod.h>
+#include <engine/shared/config.h>
 
 CPickup::CPickup(CGameWorld *pGameWorld, int Type, int SubType)
 : CEntity(pGameWorld, CGameWorld::ENTTYPE_PICKUP)
@@ -44,6 +46,10 @@ void CPickup::Tick()
 	CCharacter *pChr = GameServer()->m_World.ClosestCharacter(m_Pos, 20.0f, 0);
 	if(pChr && pChr->IsAlive())
 	{
+		pChr->SetOnScience(0);
+		if(pChr->GetPlayer()->m_MutatorTeam <= TEAM_MUTANT)
+			return;
+
 		// player picked us up, is someone was hooking us, let them go
 		int RespawnTime = -1;
 		switch (m_Type)
@@ -67,7 +73,39 @@ void CPickup::Tick()
 			case POWERUP_WEAPON:
 				if(m_Subtype >= 0 && m_Subtype < NUM_WEAPONS)
 				{
-					if(pChr->GiveWeapon(m_Subtype, 10))
+					if(m_Subtype == WEAPON_HAMMER)					
+					{
+						pChr->SetOnScience(1);
+						if(pChr->GetActiveWeapon() == WEAPON_HAMMER && pChr->IsFiring())
+						{
+							if(GameServer()->m_pController->MutPowerSupply() && g_Config.m_SvScienceSuccessCount > 0)
+							{
+								if(pChr->DecreaseArmor(1))
+								{
+									pChr->SetShowInfoTick(Server()->Tick() + 2 * Server()->TickSpeed());
+									m_SpawnTick = Server()->Tick() + g_Config.m_SvScienceSpawn * Server()->TickSpeed() / 1000;	
+									GameServer()->CreateSound(m_Pos, SOUND_PICKUP_ARMOR);
+									pChr->GetPlayer()->m_ScienceCount++;
+									if(pChr->GetPlayer()->m_ScienceCount >= g_Config.m_SvScienceSuccessCount)
+									pChr->ScienceResearch(0);
+								}
+								else if(Server()->Tick() - pChr->GetShowInfoTick() > 0)
+								{
+									pChr->SetShowInfoTick(Server()->Tick() + 2 * Server()->TickSpeed());
+									GameServer()->SendChatTarget(pChr->GetPlayer()->GetCID(),"Shields required for research!");
+								}
+							}
+							else if(Server()->Tick() - pChr->GetShowInfoTick() > 0)
+							{
+								pChr->SetShowInfoTick(Server()->Tick() + 2 * Server()->TickSpeed());
+								if(g_Config.m_SvScienceSuccessCount > 0)
+									GameServer()->SendChatTarget(pChr->GetPlayer()->GetCID(),"Research failed! Generator is down!");
+								else
+									GameServer()->SendChatTarget(pChr->GetPlayer()->GetCID(),"Research failed! Station is disabled!");
+							}
+						}
+					}
+					else if(pChr->GiveWeapon(m_Subtype, 10))
 					{
 						RespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime;
 
@@ -117,6 +155,12 @@ void CPickup::Tick()
 	}
 }
 
+void CPickup::TickPaused()
+{
+	if(m_SpawnTick != -1)
+		++m_SpawnTick;
+}
+
 void CPickup::Snap(int SnappingClient)
 {
 	if(m_SpawnTick != -1 || NetworkClipped(SnappingClient))
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/entities/pickup.h alien-rc4/src//game/server/entities/pickup.h
--- teeworlds-b177-r50edfd37-source/src//game/server/entities/pickup.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/server/entities/pickup.h	2012-06-14 23:57:39.000000000 +0200
@@ -14,6 +14,7 @@ public:
 
 	virtual void Reset();
 	virtual void Tick();
+	virtual void TickPaused();
 	virtual void Snap(int SnappingClient);
 
 private:
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/entities/projectile.cpp alien-rc4/src//game/server/entities/projectile.cpp
--- teeworlds-b177-r50edfd37-source/src//game/server/entities/projectile.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/server/entities/projectile.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -5,7 +5,9 @@
 #include "projectile.h"
 
 CProjectile::CProjectile(CGameWorld *pGameWorld, int Type, int Owner, vec2 Pos, vec2 Dir, int Span,
-		int Damage, bool Explosive, float Force, int SoundImpact, int Weapon)
+		int Damage, bool Explosive, float Force, int SoundImpact, int Weapon, 
+		int Clusters, int ClusterType, int ClusterLifeSpan, int ClusterDamage, bool ClusterExplosive, float ClusterForce,
+                int ClusterSoundImpact)
 : CEntity(pGameWorld, CGameWorld::ENTTYPE_PROJECTILE)
 {
 	m_Type = Type;
@@ -20,6 +22,14 @@ CProjectile::CProjectile(CGameWorld *pGa
 	m_StartTick = Server()->Tick();
 	m_Explosive = Explosive;
 
+	m_Clusters = Clusters;
+	m_ClusterType = ClusterType;
+	m_ClusterLifeSpan = ClusterLifeSpan;
+	m_ClusterDamage = ClusterDamage;
+	m_ClusterExplosive = ClusterExplosive;
+	m_ClusterForce = ClusterForce;
+	m_ClusterSoundImpact = ClusterSoundImpact;
+
 	GameWorld()->InsertEntity(this);
 }
 
@@ -73,15 +83,67 @@ void CProjectile::Tick()
 			GameServer()->CreateSound(CurPos, m_SoundImpact);
 
 		if(m_Explosive)
-			GameServer()->CreateExplosion(CurPos, m_Owner, m_Weapon, false);
+		{
+			// Mutator
+			if(m_Weapon == WEAPON_SHOTGUN)
+			{
+				GameServer()->CreateSound(CurPos, m_SoundImpact);
+				GameServer()->CreateSound(CurPos, SOUND_RIFLE_BOUNCE);
+				GameServer()->CreateExplosion(CurPos, m_Owner, m_Weapon, false);
+			}
+			else
+				GameServer()->CreateExplosion(CurPos, m_Owner, m_Weapon, false);
+		}
 
 		else if(TargetChr)
 			TargetChr->TakeDamage(m_Direction * max(0.001f, m_Force), m_Damage, m_Owner, m_Weapon);
-
+		
+		if(m_Clusters > 0)
+		{
+			int pOwner;	
+			vec2 pSpread;
+			CCharacter *OwnerChar = GameServer()->GetPlayerChar(m_Owner);
+			if(OwnerChar)
+			{
+				pOwner = OwnerChar->GetPlayer()->GetCID();
+			
+				CProjectile * pCluster;
+				for(int i =0; i < m_Clusters; i++)
+				{
+					//float a = GetAngle(PrevPos);
+					float a = float(i*(360.f/float((m_Clusters+1))));
+					pSpread = CurPos;
+					pCluster = new CProjectile(GameWorld(), m_ClusterType,
+						pOwner,
+						PrevPos,
+						vec2(cosf(a), sinf(a))*1.1f,
+						m_ClusterLifeSpan,
+						m_ClusterDamage,
+						m_ClusterExplosive, 
+						m_ClusterForce,
+						m_ClusterSoundImpact, 
+						m_ClusterType);
+			
+					CNetObj_Projectile p;
+					pCluster->FillInfo(&p);
+
+					CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE);
+					Msg.AddInt(1);
+					for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++)
+						Msg.AddInt(((int *)&p)[i]);
+					Server()->SendMsg(&Msg, 0, pOwner);
+				}
+			}
+		}
 		GameServer()->m_World.DestroyEntity(this);
 	}
 }
 
+void CProjectile::TickPaused()
+{
+	++m_StartTick;
+}
+
 void CProjectile::FillInfo(CNetObj_Projectile *pProj)
 {
 	pProj->m_X = (int)m_Pos.x;
@@ -103,3 +165,13 @@ void CProjectile::Snap(int SnappingClien
 	if(pProj)
 		FillInfo(pProj);
 }
+
+vec2 CProjectile::GetVel()
+{
+	return m_Direction;
+}
+
+void CProjectile::SetVel(vec2 Vel)
+{
+	m_Direction = Vel;
+}
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/entities/projectile.h alien-rc4/src//game/server/entities/projectile.h
--- teeworlds-b177-r50edfd37-source/src//game/server/entities/projectile.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/server/entities/projectile.h	2012-06-14 23:57:39.000000000 +0200
@@ -7,13 +7,18 @@ class CProjectile : public CEntity
 {
 public:
 	CProjectile(CGameWorld *pGameWorld, int Type, int Owner, vec2 Pos, vec2 Dir, int Span,
-		int Damage, bool Explosive, float Force, int SoundImpact, int Weapon);
+		int Damage, bool Explosive, float Force, int SoundImpact, int Weapon, 
+		int Clusters=0, int ClusterType=0, int ClusterLifeSpan=0, int ClusterDamage=0, bool ClusterExplosive=0, float ClusterForce=0, 
+		int ClusterSoundImpact=0);
 
 	vec2 GetPos(float Time);
+	vec2 GetVel();
+	void SetVel(vec2 Vel);
 	void FillInfo(CNetObj_Projectile *pProj);
 
 	virtual void Reset();
 	virtual void Tick();
+	virtual void TickPaused();
 	virtual void Snap(int SnappingClient);
 
 private:
@@ -27,6 +32,14 @@ private:
 	float m_Force;
 	int m_StartTick;
 	bool m_Explosive;
+	
+	int m_Clusters;
+	int m_ClusterType;
+	int m_ClusterLifeSpan;
+	int m_ClusterDamage;
+	int m_ClusterExplosive;
+	int m_ClusterForce;
+	int m_ClusterSoundImpact;
 };
 
 #endif
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/entities/singularinator.cpp alien-rc4/src//game/server/entities/singularinator.cpp
--- teeworlds-b177-r50edfd37-source/src//game/server/entities/singularinator.cpp	1970-01-01 01:00:00.000000000 +0100
+++ alien-rc4/src//game/server/entities/singularinator.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -0,0 +1,112 @@
+/* (c) Martin Grasberger - See alien-license.txt and licence.txt in the root of the distribution for more information. */
+#include <game/generated/protocol.h>
+#include <game/server/gamecontext.h>
+#include "laser.h"
+#include <engine/shared/config.h>
+#include "singularinator.h"
+#include "singularity.h"
+#include <game/server/gamemodes/mod.h>
+
+CSingularinator::CSingularinator(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEnergy, int Owner, int LifeSpan)
+: CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER)
+{
+	m_LifeSpan = LifeSpan;
+	m_SparkTTL = Server()->Tick() + 3 * Server()->TickSpeed();
+	m_Pos = Pos;
+	m_Fake = Pos;
+	m_Owner = Owner;
+	m_Energy = StartEnergy;
+	m_Dir = Direction*4;
+	m_EvalTick = 0;
+	GameWorld()->InsertEntity(this);
+	Move();
+}
+
+bool CSingularinator::HitCharacter(vec2 From, vec2 To)
+{
+	vec2 At;
+	CCharacter *pOwnerChar = GameServer()->GetPlayerChar(m_Owner);
+	CCharacter *pHit = GameServer()->m_World.IntersectCharacter(m_Pos, To, 0.f, At, pOwnerChar);
+	if(!pHit)
+		return false;
+	else
+	{
+		new CSingularity(&GameServer()->m_World, m_Pos, g_Config.m_SvSingularityRangeW, g_Config.m_SvSingularityKillRange,m_Owner, m_LifeSpan);
+		GameServer()->m_World.DestroyEntity(this);
+		return true;
+	}
+}
+
+void CSingularinator::Move()
+{
+	if(Server()->Tick() - m_SparkTTL > 0)
+	{
+		new CSingularity(&GameServer()->m_World, m_Pos, g_Config.m_SvSingularityRangeW, g_Config.m_SvSingularityKillRange,m_Owner, m_LifeSpan);
+		GameServer()->m_World.DestroyEntity(this);
+		return;
+	}
+
+	vec2 To = m_Pos + m_Dir;
+	m_Dir = m_Dir * 1.05;
+
+	if(GameServer()->Collision()->IntersectLine(m_Pos, To, 0x0, &To))
+	{
+		if(!HitCharacter(m_Pos, To))
+		{
+			m_From = m_Pos;
+			m_Pos = To;
+
+			new CSingularity(&GameServer()->m_World, m_Pos, g_Config.m_SvSingularityRangeW, g_Config.m_SvSingularityKillRange,m_Owner, m_LifeSpan);
+			GameServer()->m_World.DestroyEntity(this);
+			GameServer()->CreateSound(m_Pos, SOUND_RIFLE_BOUNCE);
+			return;
+		}
+	}
+	else
+	{
+		if(!HitCharacter(m_Pos, To))
+		{
+			m_From = m_Pos;
+			m_Pos = To;
+		}
+	}
+}
+
+void CSingularinator::Reset()
+{
+	GameServer()->m_World.DestroyEntity(this);
+}
+
+void CSingularinator::Tick()
+{
+	Move();
+	m_EvalTick = Server()->Tick() - (5 + Server()->Tick()%5);
+	float a = float(Server()->Tick()%900)/2.5f;
+	m_Fake = m_Pos + vec2(cosf(a), sinf(a))*(80.f-Server()->Tick()%70);
+}
+
+void CSingularinator::TickPaused()
+{
+	m_EvalTick = Server()->Tick() - (5 + Server()->Tick()%5);
+	if(Server()->Tick() % 10 == 1)
+	{
+		float a = float(Server()->Tick()%900)/2.5f;
+		m_Fake = m_Pos + vec2(cosf(a), sinf(a))*(80.f-Server()->Tick()%70);
+	}
+}
+
+void CSingularinator::Snap(int SnappingClient)
+{
+	if(NetworkClipped(SnappingClient))
+		return;
+
+	CNetObj_Laser *pObj = static_cast<CNetObj_Laser *>(Server()->SnapNewItem(NETOBJTYPE_LASER, m_ID, sizeof(CNetObj_Laser)));
+	if(!pObj)
+		return;
+
+	pObj->m_X = (int)m_Pos.x;
+	pObj->m_Y = (int)m_Pos.y;
+	pObj->m_FromX = (int)m_Fake.x;
+	pObj->m_FromY = (int)m_Fake.y;
+	pObj->m_StartTick = m_EvalTick;
+}
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/entities/singularinator.h alien-rc4/src//game/server/entities/singularinator.h
--- teeworlds-b177-r50edfd37-source/src//game/server/entities/singularinator.h	1970-01-01 01:00:00.000000000 +0100
+++ alien-rc4/src//game/server/entities/singularinator.h	2012-06-14 23:57:39.000000000 +0200
@@ -0,0 +1,33 @@
+/* (c) Martin Grasberger - See alien-license.txt and licence.txt in the root of the distribution for more information. */
+#ifndef GAME_SERVER_ENTITIES_SINGULARINATOR_H
+#define GAME_SERVER_ENTITIES_SINGULARINATOR_H
+
+#include <game/server/entity.h>
+
+class CSingularinator : public CEntity
+{
+public:
+	CSingularinator(CGameWorld *pGameWorld, vec2 Pos, vec2 Direction, float StartEnergy, int Owner, int LifeSpan);
+
+	virtual void Reset();
+	virtual void Tick();
+	virtual void TickPaused();
+	virtual void Snap(int SnappingClient);
+	static const char * m_SubDescription[];
+
+protected:
+	bool HitCharacter(vec2 From, vec2 To);
+	void Move();
+
+private:
+	vec2 m_From;
+	vec2 m_Fake;
+	vec2 m_Dir;
+	float m_Energy;
+	int m_EvalTick;
+	int m_Owner;
+	int m_SparkTTL;
+	int m_LifeSpan;
+};
+
+#endif
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/entities/singularity.cpp alien-rc4/src//game/server/entities/singularity.cpp
--- teeworlds-b177-r50edfd37-source/src//game/server/entities/singularity.cpp	1970-01-01 01:00:00.000000000 +0100
+++ alien-rc4/src//game/server/entities/singularity.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -0,0 +1,111 @@
+/* (c) Martin Grasberger - See alien-license.txt and licence.txt in the root of the distribution for more information. */
+#include <game/generated/protocol.h>
+#include <game/server/gamecontext.h>
+#include "laser.h"
+#include "singularity.h"
+#include "projectile.h"
+#include <game/server/gamemodes/mod.h>
+
+CSingularity::CSingularity(CGameWorld *pGameWorld, vec2 Pos, float Range, float KillRange, int Owner, int LifeSpan)
+: CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER)
+{
+	m_Owner = Owner;
+	if(LifeSpan)
+		m_Temporary = 1;
+
+	m_LifeSpan = LifeSpan;
+	m_Range = Range;
+	m_KillRange = KillRange;
+	m_Pos = Pos;
+	m_From = Pos;
+	m_EvalTick = 0;
+	GameWorld()->InsertEntity(this);
+}
+
+void CSingularity::Suck()
+{
+	float Len;
+	
+	CCharacter *p = (CCharacter *)GameServer()->m_World.FindFirst(CGameWorld::ENTTYPE_CHARACTER);
+	for(; p; p = (CCharacter *)p->TypeNext())
+	{
+		if(!p || !p->IsAlive())
+			continue;	
+		
+		Len = distance(m_Pos, p->m_Pos);
+		if(Len < m_KillRange)
+		{
+			if(m_Owner > -1)
+				p->Die(m_Owner,WEAPON_RIFLE);
+			else
+				p->Die(p->GetPlayer()->GetCID(),WEAPON_WORLD);
+		}
+		else if(Len < m_Range)
+			p->SetVel(p->GetVel() + (normalize(m_Pos - p->m_Pos) * exp((m_Range - Len)/(m_Range/2.5f))));
+	}
+
+	// save CPU for projectiles
+	if(m_SkipTick)
+		return;
+	
+	CProjectile *s = (CProjectile *)GameServer()->m_World.FindFirst(CGameWorld::ENTTYPE_PROJECTILE);
+	for(; s; s = (CProjectile *)s->TypeNext())
+	{
+		if(!s)
+			continue;
+		
+		Len = distance(m_Pos, s->m_Pos);
+		if(Len < m_Range*1.5)
+			s->SetVel(s->GetVel() + ((normalize(m_Pos - s->m_Pos) * exp((m_Range*1.5 - Len)/(m_Range*0.6f)))*0.04f));
+	}
+}
+
+void CSingularity::Reset()
+{
+	if(m_Temporary)
+		GameServer()->m_World.DestroyEntity(this);
+	else
+		return;
+}
+
+void CSingularity::Tick()
+{
+	m_EvalTick = Server()->Tick() - (5 + Server()->Tick()%5);
+	m_SkipTick = 1 - m_SkipTick;
+
+	float a = float(Server()->Tick()%900)/2.5f;
+	m_From = m_Pos + vec2(cosf(a), sinf(a))*(300.f-Server()->Tick()%270);
+
+	if(m_Temporary && Server()->Tick() - m_LifeSpan > 0 )
+		GameServer()->m_World.DestroyEntity(this);
+	else
+		Suck();
+}
+
+void CSingularity::TickPaused()
+{
+        m_EvalTick = Server()->Tick() - (5 + Server()->Tick()%5);
+	if(Server()->Tick() % 10 == 1)
+	{
+        	float a = float(Server()->Tick()%900)/2.5f;
+        	m_From = m_Pos + vec2(cosf(a), sinf(a))*(300.f-Server()->Tick()%270);
+	}
+}
+
+void CSingularity::Snap(int SnappingClient)
+{
+        if(NetworkClipped(SnappingClient))
+		return;
+	
+        CNetObj_Laser *pObj; 
+	pObj = static_cast<CNetObj_Laser *>(Server()->SnapNewItem(NETOBJTYPE_LASER, m_ID, sizeof(CNetObj_Laser)));
+        if(!pObj)
+                return;
+
+        pObj->m_X = (int)m_Pos.x;
+        pObj->m_Y = (int)m_Pos.y;
+        pObj->m_FromX = (int)m_From.x;
+        pObj->m_FromY = (int)m_From.y;
+        pObj->m_StartTick = m_EvalTick;
+	return;
+}
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/entities/singularity.h alien-rc4/src//game/server/entities/singularity.h
--- teeworlds-b177-r50edfd37-source/src//game/server/entities/singularity.h	1970-01-01 01:00:00.000000000 +0100
+++ alien-rc4/src//game/server/entities/singularity.h	2012-06-14 23:57:39.000000000 +0200
@@ -0,0 +1,33 @@
+/* (c) Martin Grasberger - See alien-license.txt and licence.txt in the root of the distribution for more information. */
+#ifndef GAME_SERVER_ENTITIES_SINGULARITY_H
+#define GAME_SERVER_ENTITIES_SINGULARITY_H
+
+#include <game/server/entity.h>
+
+
+class CSingularity : public CEntity
+{
+public:
+	CSingularity(CGameWorld *pGameWorld, vec2 Pos, float Range, float KillRange, int Owner, int LifeSpan);
+
+	virtual void Reset();
+	virtual void Tick();
+	virtual void TickPaused();
+	virtual void Snap(int SnappingClient);
+	static const char * m_SubDescription[];
+
+protected:
+	void Suck();
+
+private:
+	vec2 m_From;
+	int m_Owner;
+	bool m_Temporary;
+	int m_LifeSpan;
+	float m_Range;
+	float m_KillRange;
+	bool m_SkipTick;
+	int m_EvalTick;
+};
+
+#endif
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/entities/spark.cpp alien-rc4/src//game/server/entities/spark.cpp
--- teeworlds-b177-r50edfd37-source/src//game/server/entities/spark.cpp	1970-01-01 01:00:00.000000000 +0100
+++ alien-rc4/src//game/server/entities/spark.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -0,0 +1,94 @@
+/* (c) Martin Grasberger - See alien-license.txt and licence.txt in the root of the distribution for more information. */
+#include <game/generated/protocol.h>
+#include <game/server/gamecontext.h>
+#include "spark.h"
+#include <game/server/gamemodes/mod.h>
+
+CSpark::CSpark(CGameWorld *pGameWorld, vec2 Pos)
+: CEntity(pGameWorld, CGameWorld::ENTTYPE_LASER)
+{
+	m_Pos = Pos;
+	m_EvalTick = 0;
+	m_DieTick = 0;
+	m_NextDetonationTick = 0;
+	m_InitDie = 0;
+	GameWorld()->InsertEntity(this);
+}
+
+bool CSpark::HitCharacter()
+{
+	vec2 At;
+		
+	// Check Collision
+	CCharacter *Hit = GameServer()->m_World.ClosestCharacter(m_Pos, 5.0f, 0);
+	if(!Hit)
+		return false;
+
+	if(GameServer()->m_pController->MutPowerSupply())
+		Hit->BreakCircuit();
+
+	Hit->TakeDamage(vec2(0.f, 0.f), GameServer()->Tuning()->m_LaserDamage, -1, WEAPON_RIFLE);
+	return true;
+}
+
+void CSpark::Reset()
+{
+	m_InitDie = 0;
+}
+
+void CSpark::Tick()
+{
+	if(Server()->Tick() % (100 * Server()->TickSpeed() / 1000) == 0)
+		m_EvalTick = Server()->Tick();
+	else
+	{
+
+		if(GameServer()->m_pController->MutPowerSupply() == 0)
+		{
+			if(!m_InitDie)
+			{
+				m_InitDie = 1;
+				m_DieTick = Server()->Tick() + 5 * Server()->TickSpeed();
+				m_NextDetonationTick = Server()->Tick();
+				GameServer()->CreateExplosion(m_Pos, -1, WEAPON_GRENADE, true);
+				GameServer()->CreateExplosion(m_Pos, -1, WEAPON_GRENADE, true);
+			}
+			else if(m_InitDie < 2)
+			{
+				if(Server()->Tick() - m_DieTick > 0)
+				{
+					GameServer()->CreateExplosion(m_Pos, -1, WEAPON_GRENADE, true);
+					GameServer()->CreateSound(m_Pos, SOUND_GRENADE_EXPLODE);
+					m_InitDie = 2;
+				}
+				else if(Server()->Tick() - m_NextDetonationTick > 0)
+				{
+					GameServer()->CreateExplosion(m_Pos, -1, WEAPON_GRENADE, true);
+					GameServer()->CreateSound(m_Pos, SOUND_GRENADE_EXPLODE);
+					m_NextDetonationTick = Server()->Tick() + (50 + rand()%500) * Server()->TickSpeed() / 1000;
+				}
+			}
+		}
+		else
+			HitCharacter();
+	}
+}
+
+void CSpark::Snap(int SnappingClient)
+{
+	if(GameServer()->m_pController->MutPowerSupply() == 0)
+		return;
+
+	if(NetworkClipped(SnappingClient))
+		return;
+
+	CNetObj_Laser *pObj = static_cast<CNetObj_Laser *>(Server()->SnapNewItem(NETOBJTYPE_LASER, m_ID, sizeof(CNetObj_Laser)));
+	if(!pObj)
+		return;
+
+	pObj->m_X = (int)m_Pos.x;
+	pObj->m_Y = (int)m_Pos.y;
+	pObj->m_FromX = (int)m_Pos.x;
+	pObj->m_FromY = (int)m_Pos.y;
+	pObj->m_StartTick = m_EvalTick;
+}
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/entities/spark.h alien-rc4/src//game/server/entities/spark.h
--- teeworlds-b177-r50edfd37-source/src//game/server/entities/spark.h	1970-01-01 01:00:00.000000000 +0100
+++ alien-rc4/src//game/server/entities/spark.h	2012-06-14 23:57:39.000000000 +0200
@@ -0,0 +1,26 @@
+/* (c) Martin Grasberger - See alien-license.txt and licence.txt in the root of the distribution for more information. */
+#ifndef GAME_SERVER_ENTITIES_SPARK_H
+#define GAME_SERVER_ENTITIES_SPARK_H
+
+#include <game/server/entity.h>
+
+class CSpark : public CEntity
+{
+public:
+	CSpark(CGameWorld *pGameWorld, vec2 Pos);
+
+	virtual void Reset();
+	virtual void Tick();
+	virtual void Snap(int SnappingClient);
+
+protected:
+	bool HitCharacter();
+
+private:
+	int m_EvalTick;
+	int m_DieTick;
+	int m_NextDetonationTick;
+	int m_InitDie;
+};
+
+#endif
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/entity.h alien-rc4/src//game/server/entity.h
--- teeworlds-b177-r50edfd37-source/src//game/server/entity.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/server/entity.h	2012-06-14 23:57:39.000000000 +0200
@@ -106,6 +106,12 @@ public:
 	virtual void TickDefered() {}
 
 	/*
+		Function: TickPaused
+			Called when the game is paused, to freeze the state and position of the entity.
+	*/
+	virtual void TickPaused() {}
+
+	/*
 		Function: snap
 			Called when a new snapshot is being generated for a specific
 			client.
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/gamecontext.cpp alien-rc4/src//game/server/gamecontext.cpp
--- teeworlds-b177-r50edfd37-source/src//game/server/gamecontext.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/server/gamecontext.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -33,6 +33,7 @@ void CGameContext::Construct(int Resetti
 	m_pVoteOptionFirst = 0;
 	m_pVoteOptionLast = 0;
 	m_NumVoteOptions = 0;
+	m_LockTeams = 0;
 
 	if(Resetting==NO_RESET)
 		m_pVoteOptionHeap = new CHeap();
@@ -141,8 +142,20 @@ void CGameContext::CreateExplosion(vec2
 				ForceDir = normalize(Diff);
 			l = 1-clamp((l-InnerRadius)/(Radius-InnerRadius), 0.0f, 1.0f);
 			float Dmg = 6 * l;
+
+			// Mutator
 			if((int)Dmg)
-				apEnts[i]->TakeDamage(ForceDir*Dmg*2, (int)Dmg, Owner, Weapon);
+			{
+				if(Weapon == WEAPON_SHOTGUN)
+				{
+					if(Dmg > 2.f)
+						Dmg = 2.0;
+		
+					apEnts[i]->TakeDamage(ForceDir*Dmg*2, int(Dmg), Owner, Weapon);
+				}
+				else
+					apEnts[i]->TakeDamage(ForceDir*Dmg*2, (int)Dmg, Owner, Weapon);
+			}
 		}
 	}
 }
@@ -204,7 +217,15 @@ void CGameContext::CreateSoundGlobal(int
 
 	CNetMsg_Sv_SoundGlobal Msg;
 	Msg.m_SoundID = Sound;
-	Server()->SendPackMsg(&Msg, MSGFLAG_VITAL, Target);
+	if(Target == -2)
+		Server()->SendPackMsg(&Msg, MSGFLAG_NOSEND, -1);
+	else
+	{
+		int Flag = MSGFLAG_VITAL;
+		if(Target != -1)
+			Flag |= MSGFLAG_NORECORD;
+		Server()->SendPackMsg(&Msg, Flag, Target);
+	}
 }
 
 
@@ -248,7 +269,12 @@ void CGameContext::SendChat(int ChatterC
 		// send to the clients
 		for(int i = 0; i < MAX_CLIENTS; i++)
 		{
-			if(m_apPlayers[i] && m_apPlayers[i]->GetTeam() == Team)
+			if(Team == TEAM_SPECTATORS)
+			{
+				if(m_apPlayers[i] && m_apPlayers[i]->GetTeam() == TEAM_SPECTATORS)
+					Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, i);
+			}
+			else if(m_apPlayers[i] && ((m_apPlayers[i]->m_MutatorTeam <= TEAM_MUTANT && Team <= TEAM_MUTANT) || (m_apPlayers[i]->m_MutatorTeam >= TEAM_HUMAN && Team >= TEAM_HUMAN)))
 				Server()->SendPackMsg(&Msg, MSGFLAG_VITAL|MSGFLAG_NORECORD, i);
 		}
 	}
@@ -379,6 +405,22 @@ void CGameContext::SendTuningParams(int
 	Server()->SendMsg(&Msg, MSGFLAG_VITAL, ClientID);
 }
 
+void CGameContext::SwapTeams()
+{
+	if(!m_pController->IsTeamplay())
+		return;
+	
+	SendChat(-1, CGameContext::CHAT_ALL, "Teams were swapped");
+
+	for(int i = 0; i < MAX_CLIENTS; ++i)
+	{
+		if(m_apPlayers[i] && m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS)
+			m_apPlayers[i]->SetTeam(m_apPlayers[i]->GetTeam()^1, false);
+	}
+
+	(void)m_pController->CheckTeamBalance();
+}
+
 void CGameContext::OnTick()
 {
 	// check tuning
@@ -457,7 +499,9 @@ void CGameContext::OnTick()
 
 			if(m_VoteEnforce == VOTE_ENFORCE_YES)
 			{
+				Server()->SetRconCID(IServer::RCON_CID_VOTE);
 				Console()->ExecuteLine(m_aVoteCommand);
+				Server()->SetRconCID(IServer::RCON_CID_SERV);
 				EndVote();
 				SendChat(-1, CGameContext::CHAT_ALL, "Vote passed");
 
@@ -583,7 +627,12 @@ void CGameContext::OnMessage(int MsgID,
 		CNetMsg_Cl_Say *pMsg = (CNetMsg_Cl_Say *)pRawMsg;
 		int Team = pMsg->m_Team;
 		if(Team)
-			Team = pPlayer->GetTeam();
+		{
+			if(pPlayer->GetTeam() > -1)
+				Team = pPlayer->m_MutatorTeam;
+			else
+				Team = TEAM_SPECTATORS;
+		}
 		else
 			Team = CGameContext::CHAT_ALL;
 
@@ -601,6 +650,37 @@ void CGameContext::OnMessage(int MsgID,
 			pMessage++;
 		}
 
+		// Mutator 
+		if(pMsg->m_pMessage[0] == '/' && m_pController && (str_comp(m_pController->m_pGameType,"Alien") == 0 || str_comp(m_pController->m_pGameType,"TEST") == 0))
+		{
+			if((!str_comp_nocase(pMsg->m_pMessage,"/info")) || (!str_comp_nocase(pMsg->m_pMessage, "/help")))
+			{
+				SendChatTarget(ClientID, "\n-------------------------------------\nAlien-TW RC3 by Mo(2)\n-------------------------------------\n/cyclelaser: Switch explored laser-subtypes.\n/airstrike: Use airstrike if you get one.\nResearch on 'hammer-pickup' with hammer (cost shields)\n\n");
+				return;
+			}
+			else if(str_comp_nocase(pMsg->m_pMessage,"/cyclelaser") == 0)
+			{
+				if(pPlayer->GetCharacter())
+					pPlayer->GetCharacter()->CycleLaserSubTypes();
+				else
+					SendChatTarget(ClientID,"No laser available.");
+				return;
+			}
+			else if(str_comp_nocase(pMsg->m_pMessage,"/airstrike") == 0)
+			{
+				if(pPlayer->GetCharacter())
+					pPlayer->GetCharacter()->AirStrike();
+				else
+					SendChatTarget(ClientID,"No airstrike available.");
+				return;
+			}
+			else
+			{
+				SendChatTarget(ClientID, "Unknown command.\nType /info to get help.");
+				return;
+			}
+		}
+
 		SendChat(ClientID, Team, pMsg->m_pMessage);
 	}
 	else if(MsgID == NETMSGTYPE_CL_CALLVOTE)
@@ -713,7 +793,6 @@ void CGameContext::OnMessage(int MsgID,
 				char aAddrStr[NETADDR_MAXSTRSIZE] = {0};
 				Server()->GetClientAddr(KickID, aAddrStr, sizeof(aAddrStr));
 				str_format(aCmd, sizeof(aCmd), "ban %s %d Banned by vote", aAddrStr, g_Config.m_SvVoteKickBantime);
-				Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aCmd);
 			}
 		}
 		else if(str_comp_nocase(pMsg->m_Type, "spectate") == 0)
@@ -774,6 +853,13 @@ void CGameContext::OnMessage(int MsgID,
 		if(pPlayer->GetTeam() == pMsg->m_Team || (g_Config.m_SvSpamprotection && pPlayer->m_LastSetTeam && pPlayer->m_LastSetTeam+Server()->TickSpeed()*3 > Server()->Tick()))
 			return;
 
+		if(pMsg->m_Team != TEAM_SPECTATORS && m_LockTeams)
+		{
+			pPlayer->m_LastSetTeam = Server()->Tick();
+			SendBroadcast("Teams are locked", ClientID);
+			return;
+		}
+
 		if(pPlayer->m_TeamChangeTick > Server()->Tick())
 		{
 			pPlayer->m_LastSetTeam = Server()->Tick();
@@ -802,7 +888,7 @@ void CGameContext::OnMessage(int MsgID,
 		else
 		{
 			char aBuf[128];
-			str_format(aBuf, sizeof(aBuf), "Only %d active players are allowed", g_Config.m_SvMaxClients-g_Config.m_SvSpectatorSlots);
+			str_format(aBuf, sizeof(aBuf), "Only %d active players are allowed", Server()->MaxClients()-g_Config.m_SvSpectatorSlots);
 			SendBroadcast(aBuf, ClientID);
 		}
 	}
@@ -954,6 +1040,43 @@ void CGameContext::OnMessage(int MsgID,
 		pPlayer->m_LastEmote = Server()->Tick();
 
 		SendEmoticon(ClientID, pMsg->m_Emoticon);
+
+		CCharacter* pChr = pPlayer->GetCharacter();
+		if(pChr && !pChr->MutanticEyes())
+		{
+			switch(pMsg->m_Emoticon)
+			{
+			case EMOTICON_EXCLAMATION:
+			case EMOTICON_GHOST:
+			case EMOTICON_QUESTION:
+			case EMOTICON_WTF:
+					pChr->SetEmote(EMOTE_SURPRISE, Server()->Tick() + 2 * Server()->TickSpeed());
+					break;
+			case EMOTICON_DOTDOT:
+			case EMOTICON_DROP:
+			case EMOTICON_ZZZ:
+					pChr->SetEmote(EMOTE_BLINK, Server()->Tick() + 2 * Server()->TickSpeed());
+					break;
+			case EMOTICON_EYES:
+			case EMOTICON_HEARTS:
+			case EMOTICON_MUSIC:
+					pChr->SetEmote(EMOTE_HAPPY, Server()->Tick() + 2 * Server()->TickSpeed());
+					break;
+			case EMOTICON_OOP:
+			case EMOTICON_SORRY:
+			case EMOTICON_SUSHI:
+					pChr->SetEmote(EMOTE_PAIN, Server()->Tick() + 2 * Server()->TickSpeed());
+					break;
+			case EMOTICON_DEVILTEE:
+			case EMOTICON_SPLATTEE:
+			case EMOTICON_ZOMG:
+					pChr->SetEmote(EMOTE_ANGRY, Server()->Tick() + 2 * Server()->TickSpeed());
+					break;
+			default:
+					pChr->SetEmote(EMOTE_NORMAL, Server()->Tick() + 2 * Server()->TickSpeed());
+					break;
+                        }
+                }
 	}
 	else if (MsgID == NETMSGTYPE_CL_KILL && !m_World.m_Paused)
 	{
@@ -1004,6 +1127,16 @@ void CGameContext::ConTuneDump(IConsole:
 	}
 }
 
+void CGameContext::ConPause(IConsole::IResult *pResult, void *pUserData)
+{
+	CGameContext *pSelf = (CGameContext *)pUserData;
+
+	if(pSelf->m_pController->IsGameOver())
+		return;
+
+	pSelf->m_World.m_Paused ^= 1;
+}
+
 void CGameContext::ConChangeMap(IConsole::IResult *pResult, void *pUserData)
 {
 	CGameContext *pSelf = (CGameContext *)pUserData;
@@ -1036,17 +1169,14 @@ void CGameContext::ConSetTeam(IConsole::
 	CGameContext *pSelf = (CGameContext *)pUserData;
 	int ClientID = clamp(pResult->GetInteger(0), 0, (int)MAX_CLIENTS-1);
 	int Team = clamp(pResult->GetInteger(1), -1, 1);
-	int Delay = 0;
-	if(pResult->NumArguments() > 2)
-		Delay = pResult->GetInteger(2);
+	int Delay = pResult->NumArguments()>2 ? pResult->GetInteger(2) : 0;
+	if(!pSelf->m_apPlayers[ClientID])
+		return;
 
 	char aBuf[256];
 	str_format(aBuf, sizeof(aBuf), "moved client %d to team %d", ClientID, Team);
 	pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf);
 
-	if(!pSelf->m_apPlayers[ClientID])
-		return;
-
 	pSelf->m_apPlayers[ClientID]->m_TeamChangeTick = pSelf->Server()->Tick()+pSelf->Server()->TickSpeed()*Delay*60;
 	pSelf->m_apPlayers[ClientID]->SetTeam(Team);
 	(void)pSelf->m_pController->CheckTeamBalance();
@@ -1058,16 +1188,75 @@ void CGameContext::ConSetTeamAll(IConsol
 	int Team = clamp(pResult->GetInteger(0), -1, 1);
 
 	char aBuf[256];
-	str_format(aBuf, sizeof(aBuf), "moved all clients to team %d", Team);
-	pSelf->Console()->Print(IConsole::OUTPUT_LEVEL_STANDARD, "server", aBuf);
+	str_format(aBuf, sizeof(aBuf), "All players were moved to the %s", pSelf->m_pController->GetTeamName(Team));
+	pSelf->SendChat(-1, CGameContext::CHAT_ALL, aBuf);
 
 	for(int i = 0; i < MAX_CLIENTS; ++i)
 		if(pSelf->m_apPlayers[i])
-			pSelf->m_apPlayers[i]->SetTeam(Team);
+			pSelf->m_apPlayers[i]->SetTeam(Team, false);
+
+	(void)pSelf->m_pController->CheckTeamBalance();
+}
+
+void CGameContext::ConSwapTeams(IConsole::IResult *pResult, void *pUserData)
+{
+	CGameContext *pSelf = (CGameContext *)pUserData;
+	pSelf->SwapTeams();
+}
+
+void CGameContext::ConShuffleTeams(IConsole::IResult *pResult, void *pUserData)
+{
+	CGameContext *pSelf = (CGameContext *)pUserData;
+	if(!pSelf->m_pController->IsTeamplay())
+		return;
+
+	int CounterRed = 0;
+	int CounterBlue = 0;
+	int PlayerTeam = 0;
+	for(int i = 0; i < MAX_CLIENTS; ++i)
+		if(pSelf->m_apPlayers[i] && pSelf->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS)
+			++PlayerTeam;
+	PlayerTeam = (PlayerTeam+1)/2;
+	
+	pSelf->SendChat(-1, CGameContext::CHAT_ALL, "Teams were shuffled");
+
+	for(int i = 0; i < MAX_CLIENTS; ++i)
+	{
+		if(pSelf->m_apPlayers[i] && pSelf->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS)
+		{
+			if(CounterRed == PlayerTeam)
+				pSelf->m_apPlayers[i]->SetTeam(TEAM_BLUE, false);
+			else if(CounterBlue == PlayerTeam)
+				pSelf->m_apPlayers[i]->SetTeam(TEAM_RED, false);
+			else
+			{	
+				if(rand() % 2)
+				{
+					pSelf->m_apPlayers[i]->SetTeam(TEAM_BLUE, false);
+					++CounterBlue;
+				}
+				else
+				{
+					pSelf->m_apPlayers[i]->SetTeam(TEAM_RED, false);
+					++CounterRed;
+				}
+			}
+		}
+	}
 
 	(void)pSelf->m_pController->CheckTeamBalance();
 }
 
+void CGameContext::ConLockTeams(IConsole::IResult *pResult, void *pUserData)
+{
+	CGameContext *pSelf = (CGameContext *)pUserData;
+	pSelf->m_LockTeams ^= 1;
+	if(pSelf->m_LockTeams)
+		pSelf->SendChat(-1, CGameContext::CHAT_ALL, "Teams were locked");
+	else
+		pSelf->SendChat(-1, CGameContext::CHAT_ALL, "Teams were unlocked");
+}
+
 void CGameContext::ConAddVote(IConsole::IResult *pResult, void *pUserData)
 {
 	CGameContext *pSelf = (CGameContext *)pUserData;
@@ -1287,6 +1476,11 @@ void CGameContext::ConClearVotes(IConsol
 void CGameContext::ConVote(IConsole::IResult *pResult, void *pUserData)
 {
 	CGameContext *pSelf = (CGameContext *)pUserData;
+
+	// check if there is a vote running
+	if(!pSelf->m_VoteCloseTime)
+		return;
+
 	if(str_comp_nocase(pResult->GetString(0), "yes") == 0)
 		pSelf->m_VoteEnforce = CGameContext::VOTE_ENFORCE_YES;
 	else if(str_comp_nocase(pResult->GetString(0), "no") == 0)
@@ -1321,12 +1515,16 @@ void CGameContext::OnConsoleInit()
 	Console()->Register("tune_reset", "", CFGFLAG_SERVER, ConTuneReset, this, "Reset tuning");
 	Console()->Register("tune_dump", "", CFGFLAG_SERVER, ConTuneDump, this, "Dump tuning");
 
+	Console()->Register("pause", "", CFGFLAG_SERVER, ConPause, this, "Pause/unpause game");
 	Console()->Register("change_map", "?r", CFGFLAG_SERVER|CFGFLAG_STORE, ConChangeMap, this, "Change map");
-	Console()->Register("restart", "?i", CFGFLAG_SERVER|CFGFLAG_STORE, ConRestart, this, "Restart in x seconds");
+	Console()->Register("restart", "?i", CFGFLAG_SERVER|CFGFLAG_STORE, ConRestart, this, "Restart in x seconds (0 = abort)");
 	Console()->Register("broadcast", "r", CFGFLAG_SERVER, ConBroadcast, this, "Broadcast message");
 	Console()->Register("say", "r", CFGFLAG_SERVER, ConSay, this, "Say in chat");
 	Console()->Register("set_team", "ii?i", CFGFLAG_SERVER, ConSetTeam, this, "Set team of player to team");
 	Console()->Register("set_team_all", "i", CFGFLAG_SERVER, ConSetTeamAll, this, "Set team of all players to team");
+	Console()->Register("swap_teams", "", CFGFLAG_SERVER, ConSwapTeams, this, "Swap the current teams");
+	Console()->Register("shuffle_teams", "", CFGFLAG_SERVER, ConShuffleTeams, this, "Shuffle the current teams");
+	Console()->Register("lock_teams", "", CFGFLAG_SERVER, ConLockTeams, this, "Lock/unlock teams");
 
 	Console()->Register("add_vote", "sr", CFGFLAG_SERVER, ConAddVote, this, "Add a voting option");
 	Console()->Register("remove_vote", "s", CFGFLAG_SERVER, ConRemoveVote, this, "remove a voting option");
@@ -1358,14 +1556,14 @@ void CGameContext::OnInit(/*class IKerne
 	//players = new CPlayer[MAX_CLIENTS];
 
 	// select gametype
-	if(str_comp(g_Config.m_SvGametype, "mod") == 0)
-		m_pController = new CGameControllerMOD(this);
-	else if(str_comp(g_Config.m_SvGametype, "ctf") == 0)
+//	if(str_comp(g_Config.m_SvGametype, "alien") == 0)
+	m_pController = new CGameControllerMOD(this);
+/*	else if(str_comp(g_Config.m_SvGametype, "ctf") == 0)
 		m_pController = new CGameControllerCTF(this);
 	else if(str_comp(g_Config.m_SvGametype, "tdm") == 0)
 		m_pController = new CGameControllerTDM(this);
 	else
-		m_pController = new CGameControllerDM(this);
+		m_pController = new CGameControllerDM(this);*/
 
 	// setup core world
 	//for(int i = 0; i < MAX_CLIENTS; i++)
@@ -1420,6 +1618,17 @@ void CGameContext::OnShutdown()
 
 void CGameContext::OnSnap(int ClientID)
 {
+	// add tuning to demo
+	CTuningParams StandardTuning;
+	if(ClientID == -1 && Server()->DemoRecorder_IsRecording() && mem_comp(&StandardTuning, &m_Tuning, sizeof(CTuningParams)) != 0)
+	{
+		CMsgPacker Msg(NETMSGTYPE_SV_TUNEPARAMS);
+		int *pParams = (int *)&m_Tuning;
+		for(unsigned i = 0; i < sizeof(m_Tuning)/sizeof(int); i++)
+			Msg.AddInt(pParams[i]);
+		Server()->SendMsg(&Msg, MSGFLAG_RECORD|MSGFLAG_NOSEND, ClientID);
+	}
+
 	m_World.Snap(ClientID);
 	m_pController->Snap(ClientID);
 	m_Events.Snap(ClientID);
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/gamecontext.h alien-rc4/src//game/server/gamecontext.h
--- teeworlds-b177-r50edfd37-source/src//game/server/gamecontext.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/server/gamecontext.h	2012-06-14 23:57:39.000000000 +0200
@@ -48,12 +48,16 @@ class CGameContext : public IGameServer
 	static void ConTuneParam(IConsole::IResult *pResult, void *pUserData);
 	static void ConTuneReset(IConsole::IResult *pResult, void *pUserData);
 	static void ConTuneDump(IConsole::IResult *pResult, void *pUserData);
+	static void ConPause(IConsole::IResult *pResult, void *pUserData);
 	static void ConChangeMap(IConsole::IResult *pResult, void *pUserData);
 	static void ConRestart(IConsole::IResult *pResult, void *pUserData);
 	static void ConBroadcast(IConsole::IResult *pResult, void *pUserData);
 	static void ConSay(IConsole::IResult *pResult, void *pUserData);
 	static void ConSetTeam(IConsole::IResult *pResult, void *pUserData);
 	static void ConSetTeamAll(IConsole::IResult *pResult, void *pUserData);
+	static void ConSwapTeams(IConsole::IResult *pResult, void *pUserData);
+	static void ConShuffleTeams(IConsole::IResult *pResult, void *pUserData);
+	static void ConLockTeams(IConsole::IResult *pResult, void *pUserData);
 	static void ConAddVote(IConsole::IResult *pResult, void *pUserData);
 	static void ConRemoveVote(IConsole::IResult *pResult, void *pUserData);
 	static void ConForceVote(IConsole::IResult *pResult, void *pUserData);
@@ -85,6 +89,8 @@ public:
 	// helper functions
 	class CCharacter *GetPlayerChar(int ClientID);
 
+	int m_LockTeams;
+
 	// voting
 	void StartVote(const char *pDesc, const char *pCommand, const char *pReason);
 	void EndVote();
@@ -141,6 +147,9 @@ public:
 	void CheckPureTuning();
 	void SendTuningParams(int ClientID);
 
+	//
+	void SwapTeams();
+
 	// engine events
 	virtual void OnInit();
 	virtual void OnConsoleInit();
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/gamecontroller.cpp alien-rc4/src//game/server/gamecontroller.cpp
--- teeworlds-b177-r50edfd37-source/src//game/server/gamecontroller.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/server/gamecontroller.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -9,6 +9,8 @@
 #include "gamecontroller.h"
 #include "gamecontext.h"
 
+#include <game/server/gamemodes/mod.h>
+
 
 IGameController::IGameController(class CGameContext *pGameServer)
 {
@@ -245,7 +247,11 @@ void IGameController::CycleMap()
 		return;
 
 	if(m_RoundCount < g_Config.m_SvRoundsPerMap-1)
+	{
+		if(g_Config.m_SvRoundSwap)
+			GameServer()->SwapTeams();
 		return;
+	}
 
 	// handle maprotation
 	const char *pMapRotation = g_Config.m_SvMaprotation;
@@ -418,7 +424,7 @@ void IGameController::Tick()
 	if(m_GameOverTick != -1)
 	{
 		// game over.. wait for restart
-		if(Server()->Tick() > m_GameOverTick+Server()->TickSpeed()*10)
+		if(Server()->Tick() > m_GameOverTick+Server()->TickSpeed()*5)
 		{
 			CycleMap();
 			StartRound();
@@ -426,8 +432,12 @@ void IGameController::Tick()
 		}
 	}
 
+	// game is Paused
+	if(GameServer()->m_World.m_Paused)
+		++m_RoundStartTick;
+
 	// do team-balancing
-	if (IsTeamplay() && m_UnbalancedTick != -1 && Server()->Tick() > m_UnbalancedTick+g_Config.m_SvTeambalanceTime*Server()->TickSpeed()*60)
+	if(IsTeamplay() && m_UnbalancedTick != -1 && Server()->Tick() > m_UnbalancedTick+g_Config.m_SvTeambalanceTime*Server()->TickSpeed()*60)
 	{
 		GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", "Balancing teams");
 
@@ -486,6 +496,13 @@ void IGameController::Tick()
 	{
 		for(int i = 0; i < MAX_CLIENTS; ++i)
 		{
+		#ifdef CONF_DEBUG
+			if(g_Config.m_DbgDummies)
+			{
+				if(i >= MAX_CLIENTS-g_Config.m_DbgDummies)
+					break;
+			}
+		#endif
 			if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != TEAM_SPECTATORS && !Server()->IsAuthed(i))
 			{
 				if(Server()->Tick() > GameServer()->m_apPlayers[i]->m_LastActionTick+g_Config.m_SvInactiveKickTime*Server()->TickSpeed()*60)
@@ -595,7 +612,7 @@ bool IGameController::CanJoinTeam(int Te
 		}
 	}
 
-	return (aNumplayers[0] + aNumplayers[1]) < g_Config.m_SvMaxClients-g_Config.m_SvSpectatorSlots;
+	return (aNumplayers[0] + aNumplayers[1]) < Server()->MaxClients()-g_Config.m_SvSpectatorSlots;
 }
 
 bool IGameController::CheckTeamBalance()
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/gamecontroller.h alien-rc4/src//game/server/gamecontroller.h
--- teeworlds-b177-r50edfd37-source/src//game/server/gamecontroller.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/server/gamecontroller.h	2012-06-14 23:57:39.000000000 +0200
@@ -64,6 +64,7 @@ public:
 	const char *m_pGameType;
 
 	bool IsTeamplay() const;
+	bool IsGameOver() const { return m_GameOverTick != -1; }
 
 	IGameController(class CGameContext *pGameServer);
 	virtual ~IGameController();
@@ -141,6 +142,11 @@ public:
 	int ClampTeam(int Team);
 
 	virtual void PostReset();
+	virtual int MutGameRunning() { return 0; }
+	virtual int MutPowerSupply() { return 0; }
+	virtual void MutSetPowerSupply(int State) { return; }
+	virtual bool ReapinatorOnline() { return 0; }
+	virtual bool FoundHammerPickups() { return 0; }
 };
 
 #endif
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/gamemodes/ctf.cpp alien-rc4/src//game/server/gamemodes/ctf.cpp
--- teeworlds-b177-r50edfd37-source/src//game/server/gamemodes/ctf.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/server/gamemodes/ctf.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -259,6 +259,8 @@ void CGameControllerCTF::Tick()
 						else
 							GameServer()->CreateSoundGlobal(SOUND_CTF_GRAB_PL, c);
 					}
+					// demo record entry
+					GameServer()->CreateSoundGlobal(SOUND_CTF_GRAB_EN, -2);
 					break;
 				}
 			}
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/gamemodes/mod.cpp alien-rc4/src//game/server/gamemodes/mod.cpp
--- teeworlds-b177-r50edfd37-source/src//game/server/gamemodes/mod.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/server/gamemodes/mod.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -1,20 +1,578 @@
 /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
 /* If you are missing that file, acquire a complete release at teeworlds.com.                */
 #include "mod.h"
+#include <engine/shared/config.h>
+
+#include <game/server/entities/character.h>
+#include <game/server/entities/pickup.h>
+#include <game/server/entities/spark.h>
+#include <game/server/entities/laserturret.h>
+#include <game/server/entities/singularity.h>
+#include <game/server/entities/projectile.h>
+
+#include <game/server/player.h>
+
+#include <game/generated/protocol.h>
+#include <fstream>
+#include <base/tl/threading.h>
+#include <string.h>
+
+static LOCK HiScoreMutex = 0;
 
 CGameControllerMOD::CGameControllerMOD(class CGameContext *pGameServer)
 : IGameController(pGameServer)
 {
-	// Exchange this to a string that identifies your game mode.
-	// DM, TDM and CTF are reserved for teeworlds original modes.
-	m_pGameType = "MOD";
+	m_pGameType = "Alien";
 
-	//m_GameFlags = GAMEFLAG_TEAMS; // GAMEFLAG_TEAMS makes it a two-team gamemode
+	m_GameRunning = 0;
+	m_GamePreStarting = 0;
+	m_GamePreStartingDelay = 0;
+	m_BroadcastTick = Server()->Tick();
+	m_GameInitDelayTick = Server()->Tick();
+	m_PreStartDelayTick = Server()->Tick();
+	mem_zero(m_GenBuf,sizeof(m_GenBuf));
+	m_PowerSupply = 1;
+	LoadHiScore();
+	m_ShowHighScore = 0;
+	m_ShowHighScoreTick = Server()->Tick();
+	m_FlipIdleBroadcast = 0;
+	if(HiScoreMutex == 0)
+		HiScoreMutex = lock_create();
+	m_ReapinatorInitTick = Server()->Tick();
+	m_ReapinatorStatus = 0;
+	m_FoundHammerPickups = 0;
+	
+	dbg_msg("server", "Mod constructor called.");
 }
 
-void CGameControllerMOD::Tick()
+int CGameControllerMOD::OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon)
+{
+        if(!pKiller || Weapon == WEAPON_GAME)
+                return 0;
+
+        if(pKiller == pVictim->GetPlayer())
+                pVictim->GetPlayer()->m_Score--; // suicide - all other scores in character.cpp
+
+        if(Weapon == WEAPON_SELF)
+                pVictim->GetPlayer()->m_RespawnTick = Server()->Tick()+Server()->TickSpeed()*3.0f;
+        return 0;
+}
+
+bool CGameControllerMOD::OnEntity(int Index, vec2 Pos)
+{
+	if(IGameController::OnEntity(Index, Pos))
+                return true;
+	
+	int Type = -1;
+	int SubType = 0;
+        
+	if(Index == ENTITY_POWERUP_HAMMER && !g_Config.m_SvSkipScienceStations)
+	{
+		Type = POWERUP_WEAPON;
+		SubType = WEAPON_HAMMER;
+		m_FoundHammerPickups = 1;
+	}
+	else if(Index == ENTITY_SPARK)
+	{
+		new CSpark(&GameServer()->m_World, Pos);
+	}
+	else if(Index == ENTITY_LASERTURRET)
+	{
+		new CLaserTurret(&GameServer()->m_World, Pos);
+	}
+	else if(Index == ENTITY_SINGULARITY)
+	{
+		new CSingularity(&GameServer()->m_World, Pos, g_Config.m_SvSingularityRangeS, g_Config.m_SvSingularityKillRange,-1, 0);
+	}
+
+	if(Type != -1)
+	{
+		CPickup *pPickup = new CPickup(&GameServer()->m_World, Type, SubType);
+		pPickup->m_Pos = Pos;
+		return true;
+	}
+
+	return false;
+}
+
+bool CGameControllerMOD::FoundHammerPickups()
+{
+	return m_FoundHammerPickups;
+}
+
+int CGameControllerMOD::MutGameRunning()
+{
+	return m_GameRunning;
+}
+
+int CGameControllerMOD::MutPowerSupply() 
+{ 
+	return m_PowerSupply;
+}
+
+void CGameControllerMOD::MutSetPowerSupply(int State)
+{
+	m_PowerSupply = State; 	
+}
+
+bool CGameControllerMOD::ReapinatorOnline()
+{
+	if(m_ReapinatorStatus > 0 && Server()->Tick() - m_ReapinatorInitTick > 0)
+		return 1;
+	else
+		return 0;
+}
+
+void CGameControllerMOD::DoAirstrike(int ClientID)
+{
+	CGameWorld *pWorld = &GameServer()->m_World;
+        for(int bomb = -320; bomb < (GameServer()->Collision()->GetWidth()+10)*32; bomb += g_Config.m_SvAlicaAirStrikeStep)
+        {
+                CProjectile *pProj = new CProjectile(pWorld, WEAPON_GRENADE,
+                        ClientID,
+                        vec2(bomb,0),
+                        vec2(0.8f,1.f),
+                        g_Config.m_SvAirStrikeTTL,
+                        1, true, 0, SOUND_GRENADE_EXPLODE, WEAPON_GRENADE);
+
+                CNetObj_Projectile p;
+                pProj->FillInfo(&p);
+
+                CMsgPacker Msg(NETMSGTYPE_SV_EXTRAPROJECTILE);
+                Msg.AddInt(1);
+                for(unsigned i = 0; i < sizeof(CNetObj_Projectile)/sizeof(int); i++)
+                        Msg.AddInt(((int *)&p)[i]);
+                Server()->SendMsg(&Msg, 0, ClientID);
+        }
+}
+
+void CGameControllerMOD::ShowHighScore()
+{
+	if(Server()->Tick() - m_ShowHighScoreTick > 0)
+	{
+		if(m_ShowHighScore == 1)
+		{
+			if(m_HighScoreHuman)
+			{
+				if(strlen(m_HighScoreClanHuman))
+					str_format(m_GenBuf, sizeof(m_GenBuf),"Highscore tees: %d - %s | %s",m_HighScoreHuman,m_HighScoreNameHuman,m_HighScoreClanHuman);
+				else
+					str_format(m_GenBuf, sizeof(m_GenBuf),"Highscore tees: %d - %s",m_HighScoreHuman,m_HighScoreNameHuman);
+        			
+				GameServer()->SendBroadcast(m_GenBuf,-1);
+			}			
+			else
+        			GameServer()->SendBroadcast("No hi-score for survivors yet!",-1);
+
+			m_ShowHighScoreTick = Server()->Tick() + 2 * Server()->TickSpeed();
+			m_ShowHighScore++;
+		}
+		else
+		{
+			if(m_HighScoreMutant)
+			{
+				if(strlen(m_HighScoreClanMutant))
+					str_format(m_GenBuf, sizeof(m_GenBuf),"Scariest mutant: %d - %s | %s",m_HighScoreMutant,m_HighScoreNameMutant,m_HighScoreClanMutant);
+				else
+					str_format(m_GenBuf, sizeof(m_GenBuf),"Scariest mutant: %d - %s",m_HighScoreMutant,m_HighScoreNameMutant);
+        			
+				GameServer()->SendBroadcast(m_GenBuf,-1);
+			}
+			else
+        			GameServer()->SendBroadcast("No hi-score for mutants yet!",-1);
+
+			m_ShowHighScore = 0;
+		}
+	}
+	return;
+}
+
+void CGameControllerMOD::PostReset()
+{
+	m_RoundStartTick = Server()->Tick();
+	mem_zero(m_GenBuf,sizeof(m_GenBuf));
+
+	m_GameRunning = 0;
+	m_GamePreStarting = 0;
+	m_GamePreStartingDelay = 1;
+	m_PowerSupply = 1;
+	m_ReapinatorStatus = 0;
+	m_ShowHighScore = 0;
+	m_ShowHighScoreTick = Server()->Tick();
+	for(int i=0; i < MAX_CLIENTS; i++)
+		if(GameServer()->m_apPlayers[i])
+			GameServer()->m_apPlayers[i]->m_ScienceExplored = GameServer()->m_apPlayers[i]->m_ScienceRemembered;
+
+	m_PreStartDelayTick = Server()->Tick() + 1000 * Server()->TickSpeed() / 1000;
+}
+
+void CGameControllerMOD::PreStartGame()
 {
-	// this is the main part of the gamemode, this function is run every tick
+	int pActivePlayers;
+	CCharacter* pChr;
+	m_PowerSupply = 1;
+	m_ReapinatorStatus = 0;
+	
+	pActivePlayers = 0;
+	for(int i=0; i < MAX_CLIENTS; i++)
+        {
+                if(GameServer()->m_apPlayers[i])
+                {
+			if(GameServer()->m_apPlayers[i]->GetTeam() != -1)
+				pActivePlayers++;
+
+			GameServer()->m_apPlayers[i]->m_ScienceExplored = GameServer()->m_apPlayers[i]->m_ScienceRemembered;
+		
+			GameServer()->m_apPlayers[i]->m_MutaticLevels = 0;
+			GameServer()->m_apPlayers[i]->m_ScienceCount = 0;
+			GameServer()->m_apPlayers[i]->m_Score = 0;
+			GameServer()->m_apPlayers[i]->m_MyHumanScore = 0;
+			GameServer()->m_apPlayers[i]->m_MyMutantScore = 0;
+			GameServer()->m_apPlayers[i]->m_BonusScore = 0;
+			GameServer()->m_apPlayers[i]->m_BonusScore2 = 0;
+			GameServer()->m_apPlayers[i]->m_MultiScore = 0;
+			GameServer()->m_apPlayers[i]->m_MultiScoreTick = Server()->Tick();
+				
+ 			pChr = GameServer()->m_apPlayers[i]->GetCharacter();
+			if(pChr)
+				pChr->SetPreStartGame();
+
+			GameServer()->m_apPlayers[i]->m_MutatorTeam = TEAM_HUMAN;
+                }
+        }
+	
+	if(pActivePlayers > 1)
+	{
+	        m_GameInitDelayTick = Server()->Tick() + 1000 * g_Config.m_SvPreStartDelay * Server()->TickSpeed() / 1000;
+		m_GameRunning = 0;
+        	m_GamePreStarting = 1;
+		m_GamePreStartingDelay = 0;
+	
+		GameServer()->SendChatTarget(-1, "Alica-AI: Possible intrusion. Starting scan...");
+		m_ShowHighScoreTick = Server()->Tick() + 5 * Server()->TickSpeed();
+		m_ShowHighScore = 1;
+	}
+}
+
+
+void CGameControllerMOD::StartGame(int PlayerCount)
+{
+	int iMutant;
+	int pActivePlayers;	
+	int pRandMsg = rand()%4;
+	CCharacter* pChr;
+
+	iMutant = rand()%PlayerCount;
+	pActivePlayers = 0;	
+	
+	for(int i=0; i < MAX_CLIENTS; i++)
+	{
+		if(!GameServer()->m_apPlayers[i])
+			continue;
+
+		if(GameServer()->m_apPlayers[i]->GetTeam() > -1)
+		{
+			if(pActivePlayers == iMutant)
+			{
+				if(GameServer()->m_apPlayers[i]->m_LastInitMutant)
+					return;
+
+				pChr = GameServer()->m_apPlayers[i]->GetCharacter();
+				if(pChr)
+				{
+					GameServer()->SendBroadcast("You are starting this round as Mutant!", GameServer()->m_apPlayers[i]->GetCID());
+					GameServer()->m_apPlayers[i]->m_ScienceCount = 0;
+					pChr->Mutate();
+					GameServer()->CreateSound(pChr->m_Pos,SOUND_PLAYER_SKID);
+				
+					if(g_Config.m_SvInitAirStrike && rand()%2 == 1)	
+					{
+						GameServer()->SendChatTarget(-1, "Alica-AI: WARNING: Alien mutagen detected! Starting countermeasures.");
+						DoAirstrike(-1);
+					}
+					else
+						GameServer()->SendChatTarget(-1, "Alica-AI: WARNING: Alien mutagen detected! Countermeasures not available.");
+						
+				
+					m_GameRunning = 1;
+					m_GamePreStarting = 0;
+					m_GamePreStartingDelay = 0;
+					m_PowerSupply = 1;
+					if(!g_Config.m_SvReapinatorDisabled)
+					{
+						m_ReapinatorInitTick = Server()->Tick() + g_Config.m_SvReapinatorDelay * Server()->TickSpeed();
+						m_ReapinatorStatus = 1;
+					}
 
+					GameServer()->m_apPlayers[i]->m_LastInitMutant = 1;
+					// Reset all non starting mutants
+					for(int y = 0; y < MAX_CLIENTS; y++)
+					{
+						if(y != i && GameServer()->m_apPlayers[y])
+						{
+							switch(pRandMsg)
+							{
+								case 0: GameServer()->SendBroadcast(g_Config.m_SvStartMsgA,GameServer()->m_apPlayers[y]->GetCID()); break; 
+								case 1: GameServer()->SendBroadcast(g_Config.m_SvStartMsgB,GameServer()->m_apPlayers[y]->GetCID()); break;
+								case 2: GameServer()->SendBroadcast(g_Config.m_SvStartMsgC,GameServer()->m_apPlayers[y]->GetCID()); break;
+								case 3: GameServer()->SendBroadcast(g_Config.m_SvStartMsgD,GameServer()->m_apPlayers[y]->GetCID()); break;
+							}
+							GameServer()->m_apPlayers[y]->m_LastInitMutant = 0;
+						}
+					}
+					return;
+				}
+			}
+			pActivePlayers++;
+		}
+	}
+}
+
+void CGameControllerMOD::Tick()
+{
 	IGameController::Tick();
+	if(m_ShowHighScore)
+		ShowHighScore();
+}
+
+void CGameControllerMOD::DoWincheck()
+{
+	if(m_GameOverTick != -1 || m_Warmup > 0)
+		return;
+
+	m_ActivePlayers = 0;
+	m_ActiveMutants = 0;
+	m_ActiveHumans = 0;
+	m_ActiveCharacters =0;
+
+        for(int i = 0; i < MAX_CLIENTS; i++)
+	{
+                if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->GetTeam() != -1)
+		{
+                       	m_ActivePlayers++;
+			if(GameServer()->m_apPlayers[i] && GameServer()->m_apPlayers[i]->m_MutatorTeam <= TEAM_MUTANT)
+				m_ActiveMutants++;
+			else
+				m_ActiveHumans++;
+			if(GameServer()->m_apPlayers[i]->GetCharacter())
+				m_ActiveCharacters++;
+		}
+	}
+
+	if(g_Config.m_SvTimelimit > 0 && (Server()->Tick()-m_RoundStartTick) >= g_Config.m_SvTimelimit*Server()->TickSpeed()*60)
+	{
+		for(int u = 0; u < MAX_CLIENTS; u++)
+		{
+			if(GameServer()->m_apPlayers[u] && GameServer()->m_apPlayers[u]->m_MutatorTeam >= TEAM_HUMAN)
+				GameServer()->m_apPlayers[u]->m_Score += g_Config.m_SurviveBonus;
+		}
+
+		if(m_ActivePlayers >= g_Config.m_SvMinScorePlayers)
+			UpdateHiScore();
+
+		EndRound();
+		m_GameRunning = 0;
+		m_GamePreStarting = 0;
+		m_GamePreStartingDelay = 0;
+		GameServer()->SendBroadcast("Brave tees survived alien invasion!", -1);
+	}
+
+	if(m_GameRunning == 0 && m_ActivePlayers > 1)
+	{
+		if(m_GamePreStarting == 0 && m_GamePreStartingDelay == 0 && m_ActiveCharacters > 1)
+			PostReset();
+		else if(m_GamePreStartingDelay == 1 && Server()->Tick() - m_PreStartDelayTick > 0)
+			PreStartGame();
+		else if(m_GamePreStarting == 1 && Server()->Tick() - m_GameInitDelayTick > 0)
+			StartGame(m_ActivePlayers);
+	}
+	else if(m_GameRunning == 1)
+	{
+		if(m_ActivePlayers < 2)
+		{
+			m_GameRunning = 0;
+			m_GamePreStarting = 0;
+			m_GamePreStartingDelay = 0;
+			EndRound();
+		}
+		else if(Server()->Tick() > m_GameInitDelayTick)
+		{	
+			if(m_ActiveMutants == m_ActivePlayers)
+			{
+				if(m_ActivePlayers >= g_Config.m_SvMinScorePlayers)
+					UpdateHiScore();
+
+				EndRound();
+				m_GameRunning = 0;
+				m_GamePreStarting = 0;
+				m_GamePreStartingDelay = 0;
+				GameServer()->SendBroadcast("Mutants took over the world!", -1);
+			}
+			else if(m_ActiveHumans == m_ActivePlayers)
+			{	
+				for(int u = 0; u < MAX_CLIENTS; u++)
+				{
+					if(GameServer()->m_apPlayers[u] && GameServer()->m_apPlayers[u]->m_MutatorTeam >= TEAM_HUMAN)
+						GameServer()->m_apPlayers[u]->m_Score += g_Config.m_SurviveBonus;
+				}
+
+				if(m_ActivePlayers >= g_Config.m_SvMinScorePlayers)
+					UpdateHiScore();
+				
+				EndRound();
+				m_GameRunning = 0;
+				m_GamePreStarting = 0;
+				m_GamePreStartingDelay = 0;
+				GameServer()->SendBroadcast("Brave tees survived alien invasion!", -1);
+				m_BroadcastTick = Server()->Tick() + 5000 * Server()->TickSpeed() / 1000;
+			}
+		}
+	}
+	else
+	{
+		m_GamePreStarting = 0;
+		m_GamePreStartingDelay = 0;
+		if(Server()->Tick() - m_BroadcastTick > 0)
+		{
+			m_FlipIdleBroadcast = 1 - m_FlipIdleBroadcast; 
+			m_BroadcastTick = Server()->Tick() + 4 * Server()->TickSpeed();
+			if(m_FlipIdleBroadcast == 1)
+				GameServer()->SendBroadcast("2 players required. Please wait!", -1);
+			else
+				m_ShowHighScore = 1;
+		}
+	}
+		
+}
+
+void CGameControllerMOD::UpdateHiScore()
+{
+	bool newscore = 0; 
+
+	for(int i=0; i < MAX_CLIENTS; i++)
+	{
+		if(!GameServer()->m_apPlayers[i])
+			continue;
+		
+		if(GameServer()->m_apPlayers[i]->m_MutatorTeam >= TEAM_HUMAN && GameServer()->m_apPlayers[i]->m_Score > m_HighScoreHuman)
+		{
+			newscore = 1;
+			m_HighScoreHuman = GameServer()->m_apPlayers[i]->m_Score;
+			strcpy(m_HighScoreNameHuman,Server()->ClientName(GameServer()->m_apPlayers[i]->GetCID()));	
+			strcpy(m_HighScoreClanHuman,Server()->ClientClan(GameServer()->m_apPlayers[i]->GetCID()));
+			char aBuf[512];
+			str_format(aBuf, sizeof(aBuf), "%s set new hi-score for brave survivors!",m_HighScoreNameHuman);
+			GameServer()->SendChatTarget(-1,aBuf);
+		}	
+
+		if(GameServer()->m_apPlayers[i]->m_MutatorTeam <= TEAM_MUTANT && GameServer()->m_apPlayers[i]->m_Score > m_HighScoreMutant)
+		{
+			newscore = 1;
+			m_HighScoreMutant = GameServer()->m_apPlayers[i]->m_Score;
+			strcpy(m_HighScoreNameMutant,Server()->ClientName(GameServer()->m_apPlayers[i]->GetCID()));	
+			strcpy(m_HighScoreClanMutant,Server()->ClientClan(GameServer()->m_apPlayers[i]->GetCID()));
+			char bBuf[512];
+			str_format(bBuf, sizeof(bBuf), "%s set new hi-score for most scary mutant!",m_HighScoreNameMutant);
+			GameServer()->SendChatTarget(-1,bBuf);
+		}	
+	}
+	
+	if(!newscore)
+		return;
+
+	// Probably a bit ugly but first time I use threads in C++ so...
+	ScoreData * score = new ScoreData;
+	score->m_HighScoreHuman = m_HighScoreHuman;
+	strcpy(score->m_HighScoreNameHuman,m_HighScoreNameHuman);
+	strcpy(score->m_HighScoreClanHuman,m_HighScoreClanHuman);
+	score->m_HighScoreMutant = m_HighScoreMutant;
+	strcpy(score->m_HighScoreNameMutant,m_HighScoreNameMutant);
+	strcpy(score->m_HighScoreClanMutant,m_HighScoreClanMutant);
+	void *pSaveHiScoreThread = thread_create(SaveHiScoreThread, score);
+#if defined(CONF_FAMILY_UNIX)
+	pthread_detach((pthread_t)pSaveHiScoreThread);
+#endif
+	GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", "SaveHiScoreThread created.");
+}
+
+void CGameControllerMOD::SaveHiScoreThread(void *data)
+{
+	ScoreData * score = (ScoreData *) data;
+	lock_wait(HiScoreMutex);
+
+	char fName[4096];
+	str_format(fName,sizeof(fName),"%s/%s-score.txt",g_Config.m_SvHighScorePath,g_Config.m_SvMap);
+
+	std::fstream f;
+	f.open(fName, std::ios::out | std::ios::trunc);
+	if(!f.fail() && score)
+	{
+		f << score->m_HighScoreHuman << std::endl;
+		f << score->m_HighScoreNameHuman << std::endl;
+		f << score->m_HighScoreClanHuman << std::endl;
+		f << score->m_HighScoreMutant << std::endl;
+		f << score->m_HighScoreNameMutant << std::endl;
+		f << score->m_HighScoreClanMutant << std::endl;
+		delete score;
+	}
+	f.close();
+	lock_release(HiScoreMutex);
+}
+
+bool CGameControllerMOD::LoadHiScore()
+{
+	char Score[16];
+	m_HighScoreHuman = 0;
+        m_HighScoreMutant = 0;
+        mem_zero(m_HighScoreNameHuman,sizeof(m_HighScoreNameHuman));
+        mem_zero(m_HighScoreClanHuman,sizeof(m_HighScoreClanHuman));
+        mem_zero(m_HighScoreNameMutant,sizeof(m_HighScoreNameMutant));
+        mem_zero(m_HighScoreClanMutant,sizeof(m_HighScoreClanMutant));
+
+	char fName[4096];
+	str_format(fName,sizeof(fName),"%s/%s-score.txt",g_Config.m_SvHighScorePath,g_Config.m_SvMap);
+
+	std::fstream f;
+	f.open(fName, std::ios::in);
+	if(!f.fail() && !f.eof())
+	{
+		f.getline(Score,16);
+		m_HighScoreHuman = atoi(Score);
+		if(f.eof())
+		{
+			f.close();
+			return 0;
+		}
+		f.getline(m_HighScoreNameHuman,MAX_NAME_LENGTH);
+		if(f.eof())
+		{
+			f.close();
+			return 0;
+		}
+		f.getline(m_HighScoreClanHuman,MAX_NAME_LENGTH);
+		if(f.eof())
+		{
+			f.close();
+			return 0;
+		}
+		f.getline(Score,16);
+		m_HighScoreMutant = atoi(Score);
+		if(f.eof())
+		{
+			f.close();
+			return 0;
+		}
+		f.getline(m_HighScoreNameMutant,MAX_NAME_LENGTH);
+		if(f.eof())
+		{
+			f.close();
+			return 0;
+		}
+		f.getline(m_HighScoreClanMutant,MAX_NAME_LENGTH);
+	
+		f.close();
+		return 1;
+	}
+	f.close();
+	return 0;
 }
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/gamemodes/mod.h alien-rc4/src//game/server/gamemodes/mod.h
--- teeworlds-b177-r50edfd37-source/src//game/server/gamemodes/mod.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/server/gamemodes/mod.h	2012-06-14 23:57:39.000000000 +0200
@@ -3,14 +3,118 @@
 #ifndef GAME_SERVER_GAMEMODES_MOD_H
 #define GAME_SERVER_GAMEMODES_MOD_H
 #include <game/server/gamecontroller.h>
+#include <engine/shared/protocol.h>
 
-// you can subclass GAMECONTROLLER_CTF, GAMECONTROLLER_TDM etc if you want
-// todo a modification with their base as well.
+enum
+{
+	EMOTE_FLASHING=6,
+};
+
+enum
+{
+	TEAM_REAPER=1,
+ 	TEAM_MUTANT,
+	TEAM_HUMAN, 
+	TEAM_HERO,
+};
+
+enum
+{
+        POWERUP_HAMMER=5,
+        POWERUP_GUN=6,	// currently unused
+};
+
+
+enum
+{
+	SCIENCE_LASER_TELE=1,		// 0
+	SCIENCE_LASER_HEALING=2,	// 1
+	SCIENCE_LASER_RIDDLE=4,		// 2
+	SCIENCE_SHOTGUN_FORCEX2=8,	// 3
+	SCIENCE_SHOTGUN_EXPL=16,	// 4
+	SCIENCE_GRENADE_CLUSTER=32,	// 5
+	SCIENCE_GUN_MK2=64,		// 6
+	SCIENCE_SHOTGUN_FASTRELOAD=128,	// 7
+	SCIENCE_BATTERY=256,		// 8
+	SCIENCE_GAIN_WEAPONS=512,	// 9 
+	SCIENCE_GAIN_HEALTH=1024,	// 10
+	SCIENCE_AIRSTRIKE=2048,		// 11
+	SCIENCE_GAIN_HERO=4096,		// 12
+	MUTATOR_START_SHIELDS=1,	// 0
+	MUTATOR_NOBIOHAZARD=2,		// 1
+	MUTATOR_JUMP=4,			// 2
+	MUTATOR_ENDLESSHOOK=8,		// 3
+	MUTATOR_SELFHEAL=16,		// 4
+	MUTATOR_GAIN_REAPER=32,		// 5
+};
+
+struct ScoreData
+{
+	int m_HighScoreHuman;
+	char m_HighScoreNameHuman[MAX_NAME_LENGTH];
+	char m_HighScoreClanHuman[MAX_CLAN_LENGTH];
+	int m_HighScoreMutant;
+	char m_HighScoreNameMutant[MAX_NAME_LENGTH];
+	char m_HighScoreClanMutant[MAX_CLAN_LENGTH];
+};
+	
 class CGameControllerMOD : public IGameController
 {
 public:
 	CGameControllerMOD(class CGameContext *pGameServer);
+	
+	void UpdateHiScore();
+	bool LoadHiScore();
+	static void SaveHiScoreThread(void *data);
+	
+	void PreStartGame();
+	void StartGame(int PlayerCount);
+
+	void DoAirstrike(int ClientID);
+	void ShowHighScore();
 	virtual void Tick();
-	// add more virtual functions here if you wish
+	virtual void PostReset();
+	virtual int MutGameRunning();
+	virtual int MutPowerSupply();
+	virtual void MutSetPowerSupply(int State);
+	virtual bool ReapinatorOnline();
+	virtual void DoWincheck();
+	virtual int OnCharacterDeath(class CCharacter *pVictim, class CPlayer *pKiller, int Weapon);
+	virtual bool OnEntity(int Index, vec2 Pos);
+	virtual bool FoundHammerPickups();
+
+private:
+	bool m_PowerSupply;
+	int m_ShowCountDownTick;
+	
+	int m_HighScoreHuman;
+	char m_HighScoreNameHuman[MAX_NAME_LENGTH];
+	char m_HighScoreClanHuman[MAX_CLAN_LENGTH];
+	int m_HighScoreMutant;
+	char m_HighScoreNameMutant[MAX_NAME_LENGTH];
+	char m_HighScoreClanMutant[MAX_CLAN_LENGTH];
+	
+	int m_ShowHighScore;
+	int m_ShowHighScoreTick;
+	bool m_FlipIdleBroadcast;
+	
+	bool m_GameRunning;
+	bool m_GamePreStarting;
+	bool m_GamePreStartingDelay;
+	int m_PreStartDelayTick;
+	
+	int m_ActivePlayers;
+	int m_ActiveCharacters;
+	int m_ActiveMutants;
+	int m_ActiveHumans;
+	int m_BroadcastTick;
+	int m_GameInitDelayTick;
+	
+	int m_ReapinatorInitTick;
+	int m_ReapinatorStatus;
+
+	bool m_FoundHammerPickups;
+	
+	char m_GenBuf[512];
 };
 #endif
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/gameworld.cpp alien-rc4/src//game/server/gameworld.cpp
--- teeworlds-b177-r50edfd37-source/src//game/server/gameworld.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/server/gameworld.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -173,6 +173,17 @@ void CGameWorld::Tick()
 				pEnt = m_pNextTraverseEntity;
 			}
 	}
+	else
+	{
+		// update all objects
+		for(int i = 0; i < NUM_ENTTYPES; i++)
+			for(CEntity *pEnt = m_apFirstEntityTypes[i]; pEnt; )
+			{
+				m_pNextTraverseEntity = pEnt->m_pNextTypeEntity;
+				pEnt->TickPaused();
+				pEnt = m_pNextTraverseEntity;
+			}
+	}
 
 	RemoveEntities();
 }
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/player.cpp alien-rc4/src//game/server/player.cpp
--- teeworlds-b177-r50edfd37-source/src//game/server/player.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/server/player.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -4,6 +4,8 @@
 #include <engine/shared/config.h>
 #include "player.h"
 
+#include <game/server/gamemodes/mod.h>
+
 
 MACRO_ALLOC_POOL_ID_IMPL(CPlayer, MAX_CLIENTS)
 
@@ -21,6 +23,20 @@ CPlayer::CPlayer(CGameContext *pGameServ
 	m_SpectatorID = SPEC_FREEVIEW;
 	m_LastActionTick = Server()->Tick();
 	m_TeamChangeTick = Server()->Tick();
+
+	// Mutator
+	m_MutatorTeam = TEAM_MUTANT;
+	m_ScienceCount = 0;
+	m_ScienceExplored = 0;
+	m_MutaticLevels = 0;
+	m_ScienceRemembered = 0;
+	m_MyHumanScore = 0;
+	m_MyMutantScore = 0;
+	m_BonusScore = 0;
+	m_BonusScore2 = 0;
+	m_MultiScore = 0;
+	m_MultiScoreTick = Server()->Tick();
+	m_LastInitMutant = 0;
 }
 
 CPlayer::~CPlayer()
@@ -60,26 +76,37 @@ void CPlayer::Tick()
 		}
 	}
 
-	if(!m_pCharacter && m_Team == TEAM_SPECTATORS && m_SpectatorID == SPEC_FREEVIEW)
-		m_ViewPos -= vec2(clamp(m_ViewPos.x-m_LatestActivity.m_TargetX, -500.0f, 500.0f), clamp(m_ViewPos.y-m_LatestActivity.m_TargetY, -400.0f, 400.0f));
+	if(!GameServer()->m_World.m_Paused)
+	{
+		if(!m_pCharacter && m_Team == TEAM_SPECTATORS && m_SpectatorID == SPEC_FREEVIEW)
+			m_ViewPos -= vec2(clamp(m_ViewPos.x-m_LatestActivity.m_TargetX, -500.0f, 500.0f), clamp(m_ViewPos.y-m_LatestActivity.m_TargetY, -400.0f, 400.0f));
 
-	if(!m_pCharacter && m_DieTick+Server()->TickSpeed()*3 <= Server()->Tick())
-		m_Spawning = true;
+		if(!m_pCharacter && m_DieTick+Server()->TickSpeed()*3 <= Server()->Tick())
+			m_Spawning = true;
 
-	if(m_pCharacter)
-	{
-		if(m_pCharacter->IsAlive())
-		{
-			m_ViewPos = m_pCharacter->m_Pos;
-		}
-		else
+		if(m_pCharacter)
 		{
-			delete m_pCharacter;
-			m_pCharacter = 0;
+			if(m_pCharacter->IsAlive())
+			{
+				m_ViewPos = m_pCharacter->m_Pos;
+			}
+			else
+			{
+				delete m_pCharacter;
+				m_pCharacter = 0;
+			}
 		}
+		else if(m_Spawning && m_RespawnTick <= Server()->Tick())
+			TryRespawn();
 	}
-	else if(m_Spawning && m_RespawnTick <= Server()->Tick())
-		TryRespawn();
+	else
+	{
+		++m_RespawnTick;
+		++m_DieTick;
+		++m_ScoreStartTick;
+		++m_LastActionTick;
+		++m_TeamChangeTick;
+ 	}
 }
 
 void CPlayer::PostTick()
@@ -115,9 +142,41 @@ void CPlayer::Snap(int SnappingClient)
 	StrToInts(&pClientInfo->m_Clan0, 3, Server()->ClientClan(m_ClientID));
 	pClientInfo->m_Country = Server()->ClientCountry(m_ClientID);
 	StrToInts(&pClientInfo->m_Skin0, 6, m_TeeInfos.m_SkinName);
-	pClientInfo->m_UseCustomColor = m_TeeInfos.m_UseCustomColor;
-	pClientInfo->m_ColorBody = m_TeeInfos.m_ColorBody;
-	pClientInfo->m_ColorFeet = m_TeeInfos.m_ColorFeet;
+	pClientInfo->m_UseCustomColor = 1;
+	/*pClientInfo->m_ColorBody = m_TeeInfos.m_ColorBody;
+	pClientInfo->m_ColorFeet = m_TeeInfos.m_ColorFeet;*/
+
+	switch(m_MutatorTeam)
+	{
+		case TEAM_HERO:
+			/*pClientInfo->m_ColorBody = 25 * 0x100000 + 0xff00;
+			pClientInfo->m_ColorFeet = 25 * 0x100000 + 0xff00;*/
+			pClientInfo->m_ColorBody = 26279680;
+			pClientInfo->m_ColorFeet = 26279680;
+			StrToInts(&pClientInfo->m_Clan0, 3, "- Hero -");
+			break;
+                case TEAM_HUMAN:
+			/*pClientInfo->m_ColorBody = 25 * 0x100000 + 0xff72;
+			pClientInfo->m_ColorFeet = 25 * 0x100000 + 0xcc66;*/
+			pClientInfo->m_ColorBody = 26279794;
+			pClientInfo->m_ColorFeet = 26266726;
+			break;
+		case TEAM_MUTANT:
+			/*pClientInfo->m_ColorBody = 128 * 0x100000 + 0xff72;
+			pClientInfo->m_ColorFeet = 128 * 0x100000 + 0xcc66;*/
+			pClientInfo->m_ColorBody = 134283122;
+			pClientInfo->m_ColorFeet = 134270054;
+			StrToInts(&pClientInfo->m_Clan0, 3, "- Mutant-");
+			break;
+		case TEAM_REAPER:
+			/*pClientInfo->m_ColorBody = 128 * 0x100000 + 0xff11;
+			pClientInfo->m_ColorFeet = 128 * 0x100000 + 0xff11;*/
+			pClientInfo->m_ColorBody = 134283025;
+			pClientInfo->m_ColorFeet = 134283025;
+			StrToInts(&pClientInfo->m_Clan0, 3, "- Reaper -");
+			break;
+	}
+
 
 	CNetObj_PlayerInfo *pPlayerInfo = static_cast<CNetObj_PlayerInfo *>(Server()->SnapNewItem(NETOBJTYPE_PLAYERINFO, m_ClientID, sizeof(CNetObj_PlayerInfo)));
 	if(!pPlayerInfo)
@@ -230,7 +289,7 @@ void CPlayer::Respawn()
 		m_Spawning = true;
 }
 
-void CPlayer::SetTeam(int Team)
+void CPlayer::SetTeam(int Team, bool DoChatMsg)
 {
 	// clamp the team
 	Team = GameServer()->m_pController->ClampTeam(Team);
@@ -238,8 +297,11 @@ void CPlayer::SetTeam(int Team)
 		return;
 
 	char aBuf[512];
-	str_format(aBuf, sizeof(aBuf), "'%s' joined the %s", Server()->ClientName(m_ClientID), GameServer()->m_pController->GetTeamName(Team));
-	GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf);
+	if(DoChatMsg)
+	{
+		str_format(aBuf, sizeof(aBuf), "'%s' joined the %s", Server()->ClientName(m_ClientID), GameServer()->m_pController->GetTeamName(Team));
+		GameServer()->SendChat(-1, CGameContext::CHAT_ALL, aBuf);
+	}
 
 	KillCharacter();
 
diff -rupN teeworlds-b177-r50edfd37-source/src//game/server/player.h alien-rc4/src//game/server/player.h
--- teeworlds-b177-r50edfd37-source/src//game/server/player.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/server/player.h	2012-06-14 23:57:39.000000000 +0200
@@ -20,7 +20,7 @@ public:
 
 	void TryRespawn();
 	void Respawn();
-	void SetTeam(int Team);
+	void SetTeam(int Team, bool DoChatMsg=true);
 	int GetTeam() const { return m_Team; };
 	int GetCID() const { return m_ClientID; };
 
@@ -96,6 +96,21 @@ public:
 		int m_Max;
 	} m_Latency;
 
+	// Mutator
+	int m_MutatorTeam;
+	int m_ScienceCount;
+	int m_ScienceExplored;
+	int m_MutaticLevels;
+	int m_ScienceRemembered;
+
+	int m_MyHumanScore;
+	int m_MyMutantScore;
+	int m_BonusScore;
+	int m_BonusScore2;
+	int m_MultiScore;
+	int m_MultiScoreTick;
+	int m_LastInitMutant;
+
 private:
 	CCharacter *m_pCharacter;
 	CGameContext *m_pGameServer;
Binary files teeworlds-b177-r50edfd37-source/src//game/server/.singularynator.cpp.swp and alien-rc4/src//game/server/.singularynator.cpp.swp differ
diff -rupN teeworlds-b177-r50edfd37-source/src//game/variables.h alien-rc4/src//game/variables.h
--- teeworlds-b177-r50edfd37-source/src//game/variables.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/variables.h	2012-06-14 23:57:39.000000000 +0200
@@ -14,6 +14,7 @@ MACRO_CONFIG_INT(ClNameplatesSize, cl_na
 MACRO_CONFIG_INT(ClAutoswitchWeapons, cl_autoswitch_weapons, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Auto switch weapon on pickup")
 
 MACRO_CONFIG_INT(ClShowhud, cl_showhud, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show ingame HUD")
+MACRO_CONFIG_INT(ClShowChatFriends, cl_show_chat_friends, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show only chat messages from friends")
 MACRO_CONFIG_INT(ClShowfps, cl_showfps, 0, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Show ingame FPS counter")
 
 MACRO_CONFIG_INT(ClAirjumpindicator, cl_airjumpindicator, 1, 0, 1, CFGFLAG_CLIENT|CFGFLAG_SAVE, "")
@@ -41,7 +42,7 @@ MACRO_CONFIG_INT(PlayerColorBody, player
 MACRO_CONFIG_INT(PlayerColorFeet, player_color_feet, 65408, 0, 0xFFFFFF, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player feet color")
 MACRO_CONFIG_STR(PlayerSkin, player_skin, 24, "default", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Player skin")
 
-MACRO_CONFIG_INT(UiPage, ui_page, 5, 0, 10, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface page")
+MACRO_CONFIG_INT(UiPage, ui_page, 6, 0, 10, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface page")
 MACRO_CONFIG_INT(UiToolboxPage, ui_toolbox_page, 0, 0, 2, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Toolbox page")
 MACRO_CONFIG_STR(UiServerAddress, ui_server_address, 64, "localhost:8303", CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface server address")
 MACRO_CONFIG_INT(UiScale, ui_scale, 100, 50, 150, CFGFLAG_CLIENT|CFGFLAG_SAVE, "Interface scale")
@@ -60,10 +61,11 @@ MACRO_CONFIG_STR(SvMotd, sv_motd, 900, "
 MACRO_CONFIG_INT(SvTeamdamage, sv_teamdamage, 0, 0, 1, CFGFLAG_SERVER, "Team damage")
 MACRO_CONFIG_STR(SvMaprotation, sv_maprotation, 768, "", CFGFLAG_SERVER, "Maps to rotate between")
 MACRO_CONFIG_INT(SvRoundsPerMap, sv_rounds_per_map, 1, 1, 100, CFGFLAG_SERVER, "Number of rounds on each map before rotating")
+MACRO_CONFIG_INT(SvRoundSwap, sv_round_swap, 1, 0, 1, CFGFLAG_SERVER, "Swap teams between rounds")
 MACRO_CONFIG_INT(SvPowerups, sv_powerups, 1, 0, 1, CFGFLAG_SERVER, "Allow powerups like ninja")
-MACRO_CONFIG_INT(SvScorelimit, sv_scorelimit, 20, 0, 1000, CFGFLAG_SERVER, "Score limit (0 disables)")
-MACRO_CONFIG_INT(SvTimelimit, sv_timelimit, 0, 0, 1000, CFGFLAG_SERVER, "Time limit in minutes (0 disables)")
-MACRO_CONFIG_STR(SvGametype, sv_gametype, 32, "dm", CFGFLAG_SERVER, "Game type (dm, tdm, ctf)")
+MACRO_CONFIG_INT(SvScorelimit, sv_scorelimit, 0, 0, 1000, CFGFLAG_SERVER, "Score limit (0 disables)")
+MACRO_CONFIG_INT(SvTimelimit, sv_timelimit, 4, 0, 1000, CFGFLAG_SERVER, "Time limit in minutes (0 disables)")
+MACRO_CONFIG_STR(SvGametype, sv_gametype, 32, "alien", CFGFLAG_SERVER, "Game type (dm, tdm, ctf)")
 MACRO_CONFIG_INT(SvTournamentMode, sv_tournament_mode, 0, 0, 1, CFGFLAG_SERVER, "Tournament mode. When enabled, players joins the server as spectator")
 MACRO_CONFIG_INT(SvSpamprotection, sv_spamprotection, 1, 0, 1, CFGFLAG_SERVER, "Spam protection")
 
@@ -80,6 +82,73 @@ MACRO_CONFIG_INT(SvVoteSpectateRejoindel
 MACRO_CONFIG_INT(SvVoteKick, sv_vote_kick, 1, 0, 1, CFGFLAG_SERVER, "Allow voting to kick players")
 MACRO_CONFIG_INT(SvVoteKickMin, sv_vote_kick_min, 0, 0, MAX_CLIENTS, CFGFLAG_SERVER, "Minimum number of players required to start a kick vote")
 MACRO_CONFIG_INT(SvVoteKickBantime, sv_vote_kick_bantime, 5, 0, 1440, CFGFLAG_SERVER, "The time to ban a player if kicked by vote. 0 makes it just use kick")
+MACRO_CONFIG_INT(SvPreStartDelay, sv_prestartdelay, 10,1,10000, CFGFLAG_SERVER, "Warmup-phase at start")
+MACRO_CONFIG_INT(SvSingularityRangeW, sv_singularityrange_w, 800, 1, 9999, CFGFLAG_SERVER, "Weapon singularity range")
+MACRO_CONFIG_INT(SvSingularityRangeS, sv_singularityrange_s, 1600, 1, 9999, CFGFLAG_SERVER, "Mapentity singularity range")
+MACRO_CONFIG_INT(SvSingularityKillRange, sv_singularitykillrange, 40, 1, 1000, CFGFLAG_SERVER, "Deathzone of singularity")
+MACRO_CONFIG_INT(SvSingularinatorTTL, sv_singularinatorttl,10,1,9999,CFGFLAG_SERVER, "Singularity TTL of Singularinator")
+MACRO_CONFIG_INT(SvMinScorePlayers, sv_minscoreplayers,1,1,16,CFGFLAG_SERVER, "Minimum of players before high-score would be written.")
+MACRO_CONFIG_STR(SvHighScorePath, sv_highscorepath, 2048, "./", CFGFLAG_SERVER, "Pathname for high-score files.")
+MACRO_CONFIG_STR(SvStartMsgA, sv_startmsg_a, 128, "And so it began...", CFGFLAG_SERVER, "Startmsg 1 for humans")
+MACRO_CONFIG_STR(SvStartMsgB, sv_startmsg_b, 128, "A storm is brewing...", CFGFLAG_SERVER, "Startmsg 2 for humans")
+MACRO_CONFIG_STR(SvStartMsgC, sv_startmsg_c, 128, "Is there still hope?", CFGFLAG_SERVER, "Startmsg 3 for humans")
+MACRO_CONFIG_STR(SvStartMsgD, sv_startmsg_d, 128, "Please insert coin!", CFGFLAG_SERVER, "Startmsg 4 for humans")
+MACRO_CONFIG_INT(SvMutEmoteDelay, sv_mutemotedelay,20,5,9999,CFGFLAG_SERVER, "Base-delay of random protecting mutantic eye flashing (+10 secs rand)")
+MACRO_CONFIG_INT(SvSGTurretNonExpDmg, sv_sgturret_nonexpdmg,2,0,4,CFGFLAG_SERVER, "Damage of stationary shotgun-turret (final_sum = +1 for exploding_dmg)")
+MACRO_CONFIG_INT(SvAirStrikeTTL, sv_airstrikettl,1500,1,9999,CFGFLAG_SERVER, "TTL for airstrike grenades")
+MACRO_CONFIG_INT(SvInitAirStrike, sv_initairstrike,1,0,1,CFGFLAG_SERVER, "Do random airstrike at start")
+MACRO_CONFIG_INT(SvClusters, sv_clusters,6,0,64,CFGFLAG_SERVER, "How many clusters per grenade")
+MACRO_CONFIG_INT(SvAirStrikeClusters, sv_airstrikeclusters,6,0,24,CFGFLAG_SERVER, "How many clusters per human airstrike-grenade")
+MACRO_CONFIG_INT(SvAlicaAirStrikeStep, sv_alica_airstrikestep,128,32,9999,CFGFLAG_SERVER, "Size of space between bomb-carpet of alica")
+MACRO_CONFIG_INT(SvHumAirStrikeStep, sv_hum_airstrikestep,128,32,9999,CFGFLAG_SERVER, "Size of space between bomb-carpet of humans")
+MACRO_CONFIG_INT(SvReaperAmmo, sv_reaperammo,2,0,10,CFGFLAG_SERVER, "How many singularities at reaper start")
+MACRO_CONFIG_INT(SvHealingAmmo, sv_healingammo,3,0,10,CFGFLAG_SERVER, "How many healing laser ammo")
+MACRO_CONFIG_INT(SvGunMK2Force, sv_gunmk2force,20,0,9999,CFGFLAG_SERVER, "How many force for gun mk2")
+MACRO_CONFIG_INT(SvShotMK2Force, sv_shotmk2force,10,0,9999,CFGFLAG_SERVER, "How many force for shotgun mk2")
+MACRO_CONFIG_INT(SvShotSpeedkit, sv_shotspeedkit,700,250,2000,CFGFLAG_SERVER, "Shotgun-Speedkit reload delay")
+MACRO_CONFIG_INT(SvScienceSuccessCount, sv_sciencesuccesscount,10,0,9999,CFGFLAG_SERVER, "How many shields for research (0 to disable)")
+MACRO_CONFIG_INT(SvSaveScienceScore, sv_savesciencescore,0,0,9999,CFGFLAG_SERVER, "Save double researches after round at min score (0 to disable)")
+MACRO_CONFIG_INT(SvScienceSpawn, sv_sciencespawn,400,0,2000,CFGFLAG_SERVER, "Time in msecs until hammer respawns at research")
+MACRO_CONFIG_INT(SvSkipScienceStations, sv_skipsciencestations,0,0,1,CFGFLAG_SERVER, "Remove science stations when map is loaded")
+MACRO_CONFIG_INT(SvMaxTurretAimVel, sv_maxturretaimvel,10,0,9999,CFGFLAG_SERVER, "Max movement speed before turret will fire on tee")
+MACRO_CONFIG_INT(SvTurretAimNoHumans, sv_turretaimnohumans,0,0,1,CFGFLAG_SERVER, "Laserturrets should just aim mutants")
+MACRO_CONFIG_INT(SvTurretRange, sv_turretrange,500,0,1000,CFGFLAG_SERVER, "Range of laserturrets")
+MACRO_CONFIG_INT(SvLaserWallDelay, sv_laserwalldelay, 1, 0, 5, CFGFLAG_SERVER, "Delay before laserwall would be activated")
+MACRO_CONFIG_INT(SvLaserWallLength, sv_laserwalllength, 266, 0, 9999, CFGFLAG_SERVER, "Length for one hit laserwall")
+MACRO_CONFIG_INT(SvNormalBattery, sv_normalbattery,3000,1,9999,CFGFLAG_SERVER, "Time that one shield keep laserwall on power")
+MACRO_CONFIG_INT(SvSuperBattery, sv_superbattery,4500,1,9999,CFGFLAG_SERVER, "Time that one shield keep laserwall on power")
+MACRO_CONFIG_INT(SvLWLimit, sv_lw_limit,0,0,1,CFGFLAG_SERVER, "Limit TTL of laserwall to 10 x batterypower")
+MACRO_CONFIG_INT(SvLWLimitNonAlMap, sv_lw_limit_non_al_map,1,0,1,CFGFLAG_SERVER, "Limit TTL of laserwall to 10 x batterypower in non-alien maps")
+MACRO_CONFIG_INT(SvHeroAirstrike, sv_heroairstrike,0,0,1,CFGFLAG_SERVER, "Give airstrike when player get hero")
+MACRO_CONFIG_INT(SvReapinatorDisabled, sv_reapinator_disabled,0,0,1,CFGFLAG_SERVER, "Disable reapinator")
+MACRO_CONFIG_INT(SvReapinatorDelay, sv_reapinator_delay,120,1,9999,CFGFLAG_SERVER, "Init delay of reapinator (in secs)")
+MACRO_CONFIG_INT(SvReapinatorMinScore, sv_reapinator_minscore,5,0,9999,CFGFLAG_SERVER, "Min player score for reapinator")
+MACRO_CONFIG_INT(SvReaperMinScore, sv_reaper_minscore,6,0,9999,CFGFLAG_SERVER, "Min player score for reaper (without reapinator)")
+MACRO_CONFIG_INT(SvMetamorphoseCount, sv_metamorphosecount,1,0,9999,CFGFLAG_SERVER, "How many kills until metamorphose")
+MACRO_CONFIG_INT(SvHeroBecameScore, sv_becamehero_score,15,0,9999,CFGFLAG_SERVER, "Score to became hero")
+MACRO_CONFIG_INT(SvAutoResearchScore, sv_autoresearchscore, 3,0,9999,CFGFLAG_SERVER, "BonusScore to init research lottery - (0 to disable)")
+MACRO_CONFIG_INT(SvEmptyResearch, sv_emptyresearch, 1,0,1,CFGFLAG_SERVER, "Auto research only on maps without hammer pickup")
+MACRO_CONFIG_STR(SvInfoGot, sv_infogot, 64, "got:", CFGFLAG_SERVER, "Autoresearch text success text")
+MACRO_CONFIG_STR(SvInfoResearched, sv_inforesearched, 64, "researched:", CFGFLAG_SERVER, "Manual hammer research success text")
+MACRO_CONFIG_STR(SvInfoHackedAirstrike, sv_hackedairstrike, 64, "hacked Alica-AI and got an airstrike!", CFGFLAG_SERVER, "Became airstrike text at research")
+MACRO_CONFIG_STR(SvInfoGotAirstrike, sv_gotairstrike, 64, "got an airstrike!", CFGFLAG_SERVER, "Became airstrike text no-research")
+MACRO_CONFIG_INT(SvScepticMsgOn, sv_scepticmsg_on, 1,0,1,CFGFLAG_SERVER, "Enable energynator sceptic msg.")
+MACRO_CONFIG_INT(SvHappyMsgOn, sv_happymsg_on, 1,0,1,CFGFLAG_SERVER, "Enable energynator sceptic msg.")
+MACRO_CONFIG_INT(SvBonusMsgOn, sv_bonusmsg_on, 1,0,1,CFGFLAG_SERVER, "Enable generic research and metamorph-messages.")
+MACRO_CONFIG_STR(SvScepticEnergynatorA, sv_scepticenergynator_a, 128, "Energynator: You are a mutant, aren't you?", CFGFLAG_SERVER, "Sceptic energynator text 1")
+MACRO_CONFIG_STR(SvScepticEnergynatorB, sv_scepticenergynator_b, 128, "Energynator: Starting fillup... Hey wait a minute!", CFGFLAG_SERVER, "Sceptic energynator text 2")
+MACRO_CONFIG_STR(SvScepticEnergynatorC, sv_scepticenergynator_c, 128, "Energynator: Go away scary mutant!", CFGFLAG_SERVER, "Sceptic energynator text 3")
+MACRO_CONFIG_STR(SvScepticEnergynatorD, sv_scepticenergynator_d, 128, "Energynator: :P", CFGFLAG_SERVER, "Sceptic energynator text 4")
+MACRO_CONFIG_STR(SvScepticEnergynatorE, sv_scepticenergynator_e, 128, "Energynator: Help!!! I'm getting raped by mutants!", CFGFLAG_SERVER, "Sceptic energynator text 5")
+MACRO_CONFIG_STR(SvHappyReapinatorA, sv_happyreapinator_a, 128, "Reapinator: Hello alien-reaper. I'm your personal fan (but don't tell this energynator)", CFGFLAG_SERVER, "Happy reapinator text 1")
+MACRO_CONFIG_STR(SvHappyReapinatorB, sv_happyreapinator_b, 128, "Reapinator: Hint: If your eyes are flashing you are almost undestructable!", CFGFLAG_SERVER, "Happy reapinator text 2")
+MACRO_CONFIG_STR(SvHappyReapinatorC, sv_happyreapinator_c, 128, "Reapinator: I love you!", CFGFLAG_SERVER, "Happy reapinator text 3")
+MACRO_CONFIG_STR(SvHappyReapinatorD, sv_happyreapinator_d, 128, "Reapinator: You are sooo cool!", CFGFLAG_SERVER, "Happy reapinator text 4")
+MACRO_CONFIG_STR(SvHappyReapinatorE, sv_happyreapinator_e, 128, "Reapinator: A real reaper!", CFGFLAG_SERVER, "Happy reapinator test 5")
+MACRO_CONFIG_INT(SurviveBonus, sv_survivebonus, 3,0,9999,CFGFLAG_SERVER, "Score bonus for survive at game-end.")
+MACRO_CONFIG_INT(SvDummy, sv_dummy, 1,0,1,CFGFLAG_SERVER, "Useless empty dummy for vote")
+
+
 
 // debug
 #ifdef CONF_DEBUG // this one can crash the server if not used correctly
diff -rupN teeworlds-b177-r50edfd37-source/src//game/version.h alien-rc4/src//game/version.h
--- teeworlds-b177-r50edfd37-source/src//game/version.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//game/version.h	2012-06-14 23:57:39.000000000 +0200
@@ -3,6 +3,7 @@
 #ifndef GAME_VERSION_H
 #define GAME_VERSION_H
 #include "generated/nethash.cpp"
-#define GAME_VERSION "0.6.1"
+#define GAME_VERSION "0.6 trunk"
 #define GAME_NETVERSION "0.6 " GAME_NETVERSION_HASH
+static const char GAME_RELEASE_VERSION[8] = {'0', '.', '6', '1', 0};
 #endif
diff -rupN teeworlds-b177-r50edfd37-source/src//mastersrv/mastersrv.cpp alien-rc4/src//mastersrv/mastersrv.cpp
--- teeworlds-b177-r50edfd37-source/src//mastersrv/mastersrv.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//mastersrv/mastersrv.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -1,20 +1,24 @@
 /* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
 /* If you are missing that file, acquire a complete release at teeworlds.com.                */
 #include <base/system.h>
-#include <engine/shared/network.h>
-#include <engine/shared/config.h>
+
+#include <engine/config.h>
 #include <engine/console.h>
-#include <engine/storage.h>
 #include <engine/kernel.h>
+#include <engine/storage.h>
+
+#include <engine/shared/config.h>
+#include <engine/shared/netban.h>
+#include <engine/shared/network.h>
 
 #include "mastersrv.h"
 
+
 enum {
 	MTU = 1400,
 	MAX_SERVERS_PER_PACKET=75,
 	MAX_PACKETS=16,
 	MAX_SERVERS=MAX_SERVERS_PER_PACKET*MAX_PACKETS,
-	MAX_BANS=128,
 	EXPIRE_TIME = 90
 };
 
@@ -77,14 +81,7 @@ static CCountPacketData m_CountData;
 static CCountPacketData m_CountDataLegacy;
 
 
-struct CBanEntry
-{
-	NETADDR m_Address;
-	int64 m_Expire;
-};
-
-static CBanEntry m_aBans[MAX_BANS];
-static int m_NumBans = 0;
+CNetBan m_NetBan;
 
 static CNetClient m_NetChecker; // NAT/FW checker
 static CNetClient m_NetOp; // main
@@ -217,9 +214,9 @@ void AddCheckserver(NETADDR *pInfo, NETA
 	}
 
 	char aAddrStr[NETADDR_MAXSTRSIZE];
-	net_addr_str(pInfo, aAddrStr, sizeof(aAddrStr));
+	net_addr_str(pInfo, aAddrStr, sizeof(aAddrStr), true);
 	char aAltAddrStr[NETADDR_MAXSTRSIZE];
-	net_addr_str(pAlt, aAltAddrStr, sizeof(aAltAddrStr));
+	net_addr_str(pAlt, aAltAddrStr, sizeof(aAltAddrStr), true);
 	dbg_msg("mastersrv", "checking: %s (%s)", aAddrStr, aAltAddrStr);
 	m_aCheckServers[m_NumCheckServers].m_Address = *pInfo;
 	m_aCheckServers[m_NumCheckServers].m_AltAddress = *pAlt;
@@ -237,7 +234,7 @@ void AddServer(NETADDR *pInfo, ServerTyp
 		if(net_addr_comp(&m_aServers[i].m_Address, pInfo) == 0)
 		{
 			char aAddrStr[NETADDR_MAXSTRSIZE];
-			net_addr_str(pInfo, aAddrStr, sizeof(aAddrStr));
+			net_addr_str(pInfo, aAddrStr, sizeof(aAddrStr), true);
 			dbg_msg("mastersrv", "updated: %s", aAddrStr);
 			m_aServers[i].m_Expire = time_get()+time_freq()*EXPIRE_TIME;
 			return;
@@ -252,7 +249,7 @@ void AddServer(NETADDR *pInfo, ServerTyp
 	}
 
 	char aAddrStr[NETADDR_MAXSTRSIZE];
-	net_addr_str(pInfo, aAddrStr, sizeof(aAddrStr));
+	net_addr_str(pInfo, aAddrStr, sizeof(aAddrStr), true);
 	dbg_msg("mastersrv", "added: %s", aAddrStr);
 	m_aServers[m_NumServers].m_Address = *pInfo;
 	m_aServers[m_NumServers].m_Expire = time_get()+time_freq()*EXPIRE_TIME;
@@ -271,9 +268,9 @@ void UpdateServers()
 			if(m_aCheckServers[i].m_TryCount == 10)
 			{
 				char aAddrStr[NETADDR_MAXSTRSIZE];
-				net_addr_str(&m_aCheckServers[i].m_Address, aAddrStr, sizeof(aAddrStr));
+				net_addr_str(&m_aCheckServers[i].m_Address, aAddrStr, sizeof(aAddrStr), true);
 				char aAltAddrStr[NETADDR_MAXSTRSIZE];
-				net_addr_str(&m_aCheckServers[i].m_AltAddress, aAltAddrStr, sizeof(aAltAddrStr));
+				net_addr_str(&m_aCheckServers[i].m_AltAddress, aAltAddrStr, sizeof(aAltAddrStr), true);
 				dbg_msg("mastersrv", "check failed: %s (%s)", aAddrStr, aAltAddrStr);
 
 				// FAIL!!
@@ -305,7 +302,7 @@ void PurgeServers()
 		{
 			// remove server
 			char aAddrStr[NETADDR_MAXSTRSIZE];
-			net_addr_str(&m_aServers[i].m_Address, aAddrStr, sizeof(aAddrStr));
+			net_addr_str(&m_aServers[i].m_Address, aAddrStr, sizeof(aAddrStr), true);
 			dbg_msg("mastersrv", "expired: %s", aAddrStr);
 			m_aServers[i] = m_aServers[m_NumServers-1];
 			m_NumServers--;
@@ -315,53 +312,9 @@ void PurgeServers()
 	}
 }
 
-bool CheckBan(NETADDR Addr)
-{
-	for(int i = 0; i < m_NumBans; i++)
-	{
-		if(net_addr_comp(&m_aBans[i].m_Address, &Addr) == 0)
-		{
-			return true;
-		}
-	}
-	Addr.port = 0;
-	for(int i = 0; i < m_NumBans; i++)
-	{
-		if(net_addr_comp(&m_aBans[i].m_Address, &Addr) == 0)
-		{
-			return true;
-		}
-	}
-	return false;
-}
-
-void ConAddBan(IConsole::IResult *pResult, void *pUser)
-{
-	if(m_NumBans == MAX_BANS)
-	{
-		dbg_msg("mastersrv", "error: banlist is full");
-		return;
-	}
-
-	if(net_addr_from_str(&m_aBans[m_NumBans].m_Address, pResult->GetString(0)) != 0)
-	{
-		dbg_msg("mastersrv", "error: invalid address");
-		return;
-	}
-
-	if(CheckBan(m_aBans[m_NumBans].m_Address))
-	{
-		dbg_msg("mastersrv", "duplicate ban: %s", pResult->GetString(0));
-		return;
-	}
-
-	dbg_msg("mastersrv", "ban added: %s", pResult->GetString(0));
-	m_NumBans++;
-}
-
 void ReloadBans()
 {
-	m_NumBans = 0;
+	m_NetBan.UnbanAll();
 	m_pConsole->ExecuteFile("master.cfg");
 }
 
@@ -374,16 +327,40 @@ int main(int argc, const char **argv) //
 	dbg_logger_stdout();
 	net_init();
 
-	mem_zero(&BindAddr, sizeof(BindAddr));
-	BindAddr.type = NETTYPE_ALL;
-	BindAddr.port = MASTERSERVER_PORT;
+	mem_copy(m_CountData.m_Header, SERVERBROWSE_COUNT, sizeof(SERVERBROWSE_COUNT));
+	mem_copy(m_CountDataLegacy.m_Header, SERVERBROWSE_COUNT_LEGACY, sizeof(SERVERBROWSE_COUNT_LEGACY));
+
+	IKernel *pKernel = IKernel::Create();
+	IStorage *pStorage = CreateStorage("Teeworlds", IStorage::STORAGETYPE_BASIC, argc, argv);
+	IConfig *pConfig = CreateConfig();
+	m_pConsole = CreateConsole(CFGFLAG_MASTER);
+	
+	bool RegisterFail = !pKernel->RegisterInterface(pStorage);
+	RegisterFail |= !pKernel->RegisterInterface(m_pConsole);
+	RegisterFail |= !pKernel->RegisterInterface(pConfig);
+
+	if(RegisterFail)
+		return -1;
+
+	pConfig->Init();
+	m_NetBan.Init(m_pConsole, pStorage);
+	if(argc > 1) // ignore_convention
+		m_pConsole->ParseArguments(argc-1, &argv[1]); // ignore_convention
+
+	if(g_Config.m_Bindaddr[0] && net_host_lookup(g_Config.m_Bindaddr, &BindAddr, NETTYPE_ALL) == 0)
+		BindAddr.port = MASTERSERVER_PORT;
+	else
+	{
+		mem_zero(&BindAddr, sizeof(BindAddr));
+		BindAddr.type = NETTYPE_ALL;
+		BindAddr.port = MASTERSERVER_PORT;
+	}
 
 	if(!m_NetOp.Open(BindAddr, 0))
 	{
 		dbg_msg("mastersrv", "couldn't start network (op)");
 		return -1;
 	}
-
 	BindAddr.port = MASTERSERVER_PORT+1;
 	if(!m_NetChecker.Open(BindAddr, 0))
 	{
@@ -391,21 +368,6 @@ int main(int argc, const char **argv) //
 		return -1;
 	}
 
-	mem_copy(m_CountData.m_Header, SERVERBROWSE_COUNT, sizeof(SERVERBROWSE_COUNT));
-	mem_copy(m_CountDataLegacy.m_Header, SERVERBROWSE_COUNT_LEGACY, sizeof(SERVERBROWSE_COUNT_LEGACY));
-
-	IKernel *pKernel = IKernel::Create();
-	IStorage *pStorage = CreateStorage("Teeworlds", argc, argv);
-
-	m_pConsole = CreateConsole(CFGFLAG_MASTER);
-	m_pConsole->Register("ban", "s", CFGFLAG_MASTER, ConAddBan, 0, "Ban IP from mastersrv");
-
-	bool RegisterFail = !pKernel->RegisterInterface(pStorage);
-	RegisterFail |= !pKernel->RegisterInterface(m_pConsole);
-
-	if(RegisterFail)
-		return -1;
-
 	dbg_msg("mastersrv", "started");
 
 	while(1)
@@ -418,7 +380,8 @@ int main(int argc, const char **argv) //
 		while(m_NetOp.Recv(&Packet))
 		{
 			// check if the server is banned
-			if(CheckBan(Packet.m_Address)) continue;
+			if(m_NetBan.IsBanned(&Packet.m_Address, 0, 0))
+				continue;
 
 			if(Packet.m_DataSize == sizeof(SERVERBROWSE_HEARTBEAT)+2 &&
 				mem_comp(Packet.m_pData, SERVERBROWSE_HEARTBEAT, sizeof(SERVERBROWSE_HEARTBEAT)) == 0)
@@ -519,7 +482,8 @@ int main(int argc, const char **argv) //
 		while(m_NetChecker.Recv(&Packet))
 		{
 			// check if the server is banned
-			if(CheckBan(Packet.m_Address)) continue;
+			if(m_NetBan.IsBanned(&Packet.m_Address, 0, 0))
+				continue;
 
 			if(Packet.m_DataSize == sizeof(SERVERBROWSE_FWRESPONSE) &&
 				mem_comp(Packet.m_pData, SERVERBROWSE_FWRESPONSE, sizeof(SERVERBROWSE_FWRESPONSE)) == 0)
diff -rupN teeworlds-b177-r50edfd37-source/src//tools/crapnet.cpp alien-rc4/src//tools/crapnet.cpp
--- teeworlds-b177-r50edfd37-source/src//tools/crapnet.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//tools/crapnet.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -129,7 +129,7 @@ void Run(int Port, NETADDR Dest)
 			if(m_ConfigLog)
 			{
 				char aAddrStr[NETADDR_MAXSTRSIZE];
-				net_addr_str(&From, aAddrStr, sizeof(aAddrStr));
+				net_addr_str(&From, aAddrStr, sizeof(aAddrStr), true);
 				dbg_msg("crapnet", "<< %08d %s (%d)", p->m_ID, aAddrStr, p->m_DataSize);
 			}
 		}
@@ -193,7 +193,7 @@ void Run(int Port, NETADDR Dest)
 				if(m_ConfigLog)
 				{
 					char aAddrStr[NETADDR_MAXSTRSIZE];
-					net_addr_str(&p->m_SendTo, aAddrStr, sizeof(aAddrStr));
+					net_addr_str(&p->m_SendTo, aAddrStr, sizeof(aAddrStr), true);
 					dbg_msg("crapnet", ">> %08d %s (%d) %s", p->m_ID, aAddrStr, p->m_DataSize, aFlags);
 				}
 
diff -rupN teeworlds-b177-r50edfd37-source/src//tools/dilate.cpp alien-rc4/src//tools/dilate.cpp
--- teeworlds-b177-r50edfd37-source/src//tools/dilate.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//tools/dilate.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -96,7 +96,7 @@ int main(int argc, const char **argv)
 		dbg_msg("Usage", "%s FILE1 [ FILE2... ]", argv[0]);
 		return -1;
 	}
-	
+
 	for(int i = 1; i < argc; i++)
 		DilateFile(argv[i]);
 	return 0;
diff -rupN teeworlds-b177-r50edfd37-source/src//tools/fake_server.cpp alien-rc4/src//tools/fake_server.cpp
--- teeworlds-b177-r50edfd37-source/src//tools/fake_server.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//tools/fake_server.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -113,7 +113,7 @@ static int Run()
 	int64 NextHeartBeat = 0;
 	NETADDR BindAddr = {NETTYPE_IPV4, {0},0};
 
-	if(!pNet->Open(BindAddr, 0, 0, 0))
+	if(!pNet->Open(BindAddr, 0, 0, 0, 0))
 		return 0;
 
 	while(1)
diff -rupN teeworlds-b177-r50edfd37-source/src//tools/map_resave.cpp alien-rc4/src//tools/map_resave.cpp
--- teeworlds-b177-r50edfd37-source/src//tools/map_resave.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//tools/map_resave.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -6,7 +6,7 @@
 
 int main(int argc, const char **argv)
 {
-	IStorage *pStorage = CreateStorage("Teeworlds", argc, argv);
+	IStorage *pStorage = CreateStorage("Teeworlds", IStorage::STORAGETYPE_BASIC, argc, argv);
 	int Index, ID = 0, Type = 0, Size;
 	void *pPtr;
 	char aFileName[1024];
@@ -16,7 +16,7 @@ int main(int argc, const char **argv)
 	if(!pStorage || argc != 3)
 		return -1;
 
-	str_format(aFileName, sizeof(aFileName), "maps/%s", argv[2]);
+	str_format(aFileName, sizeof(aFileName), "%s", argv[2]);
 
 	if(!DataFile.Open(pStorage, argv[1], IStorage::TYPE_ALL))
 		return -1;
diff -rupN teeworlds-b177-r50edfd37-source/src//tools/map_version.cpp alien-rc4/src//tools/map_version.cpp
--- teeworlds-b177-r50edfd37-source/src//tools/map_version.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//tools/map_version.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -44,7 +44,7 @@ int MaplistCallback(const char *pName, i
 int main(int argc, const char **argv) // ignore_convention
 {
 	IKernel *pKernel = IKernel::Create();
-	s_pStorage = CreateStorage("Teeworlds", argc, argv);
+	s_pStorage = CreateStorage("Teeworlds", IStorage::STORAGETYPE_BASIC, argc, argv);
 	s_pEngineMap = CreateEngineMap();
 
 	bool RegisterFail = !pKernel->RegisterInterface(s_pStorage);
diff -rupN teeworlds-b177-r50edfd37-source/src//tools/tileset_borderadd.cpp alien-rc4/src//tools/tileset_borderadd.cpp
--- teeworlds-b177-r50edfd37-source/src//tools/tileset_borderadd.cpp	1970-01-01 01:00:00.000000000 +0100
+++ alien-rc4/src//tools/tileset_borderadd.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -0,0 +1,86 @@
+/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
+/* If you are missing that file, acquire a complete release at teeworlds.com.                */
+#include <base/math.h>
+#include <base/system.h>
+#include <engine/external/pnglite/pnglite.h>
+
+typedef struct
+{
+	unsigned char r, g, b, a;
+} CPixel;
+
+static void TilesetBorderadd(int w, int h, CPixel *pSrc, CPixel *pDest)
+{
+	int TileW = w/16;
+	int TileH = h/16;
+
+	for(int tx = 0; tx < 16; tx++)
+	{
+		for(int ty = 0; ty < 16; ty++)
+		{
+			for(int x = 0; x < TileW + 4; x++)
+			{
+				for(int y = 0; y < TileH + 4; y++)
+				{
+					int SourceX = tx * TileW + clamp(x - 2, 0, TileW - 1);
+					int SourceY = ty * TileH + clamp(y - 2, 0, TileH - 1);
+					int DestX = tx * (TileW + 4) + x;
+					int DestY = ty * (TileH + 4) + y;
+
+					int SourceI = SourceY * w + SourceX;
+					int DestI = DestY * (w + 16 * 4) + DestX;
+
+					pDest[DestI] = pSrc[SourceI];
+
+				}
+			}
+		}
+	}
+}
+
+
+int FixFile(const char *pFileName)
+{
+	png_t Png;
+	CPixel *pBuffer[2] = {0,0};
+
+	png_init(0, 0);
+	png_open_file(&Png, pFileName);
+
+	if(Png.color_type != PNG_TRUECOLOR_ALPHA)
+	{
+		dbg_msg("tileset_borderadd", "%s: not an RGBA image", pFileName);
+		return 1;
+	}
+
+	int w = Png.width;
+	int h = Png.height;
+
+	pBuffer[0] = (CPixel*)mem_alloc(w*h*sizeof(CPixel), 1);
+	pBuffer[1] = (CPixel*)mem_alloc((w+16*4)*(h+16*4)*sizeof(CPixel), 1);
+	png_get_data(&Png, (unsigned char *)pBuffer[0]);
+	png_close_file(&Png);
+
+	TilesetBorderadd(w, h, pBuffer[0], pBuffer[1]);
+
+	// save here
+	png_open_file_write(&Png, pFileName);
+	png_set_data(&Png, w + 16 * 4, h + 16 * 4, 8, PNG_TRUECOLOR_ALPHA, (unsigned char *)pBuffer[1]);
+	png_close_file(&Png);
+
+	return 0;
+}
+
+int main(int argc, const char **argv)
+{
+	dbg_logger_stdout();
+	if(argc == 1)
+	{
+		dbg_msg("Usage", "%s FILE1 [ FILE2... ]", argv[0]);
+		return -1;
+	}
+
+	for(int i = 1; i < argc; i++)
+		FixFile(argv[i]);
+	return 0;
+}
diff -rupN teeworlds-b177-r50edfd37-source/src//tools/tileset_borderrem.cpp alien-rc4/src//tools/tileset_borderrem.cpp
--- teeworlds-b177-r50edfd37-source/src//tools/tileset_borderrem.cpp	1970-01-01 01:00:00.000000000 +0100
+++ alien-rc4/src//tools/tileset_borderrem.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -0,0 +1,86 @@
+/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
+/* If you are missing that file, acquire a complete release at teeworlds.com.                */
+#include <base/math.h>
+#include <base/system.h>
+#include <engine/external/pnglite/pnglite.h>
+
+typedef struct
+{
+	unsigned char r, g, b, a;
+} CPixel;
+
+static void TilesetBorderrem(int w, int h, CPixel *pSrc, CPixel *pDest)
+{
+	int TileW = w/16;
+	int TileH = h/16;
+
+	for(int tx = 0; tx < 16; tx++)
+	{
+		for(int ty = 0; ty < 16; ty++)
+		{
+			for(int x = 0; x < TileW - 4; x++)
+			{
+				for(int y = 0; y < TileH - 4; y++)
+				{
+					int SourceX = tx * TileW + x + 2;
+					int SourceY = ty * TileH + y + 2;
+					int DestX = tx * (TileW - 4) + x;
+					int DestY = ty * (TileH - 4) + y;
+
+					int SourceI = SourceY * w + SourceX;
+					int DestI = DestY * (w - 16 * 4) + DestX;
+
+					pDest[DestI] = pSrc[SourceI];
+
+				}
+			}
+		}
+	}
+}
+
+
+int FixFile(const char *pFileName)
+{
+	png_t Png;
+	CPixel *pBuffer[2] = {0,0};
+
+	png_init(0, 0);
+	png_open_file(&Png, pFileName);
+
+	if(Png.color_type != PNG_TRUECOLOR_ALPHA)
+	{
+		dbg_msg("tileset_borderrem", "%s: not an RGBA image", pFileName);
+		return 1;
+	}
+
+	int w = Png.width;
+	int h = Png.height;
+
+	pBuffer[0] = (CPixel*)mem_alloc(w*h*sizeof(CPixel), 1);
+	pBuffer[1] = (CPixel*)mem_alloc((w-16*4)*(h-16*4)*sizeof(CPixel), 1);
+	png_get_data(&Png, (unsigned char *)pBuffer[0]);
+	png_close_file(&Png);
+
+	TilesetBorderrem(w, h, pBuffer[0], pBuffer[1]);
+
+	// save here
+	png_open_file_write(&Png, pFileName);
+	png_set_data(&Png, w - 16 * 4, h - 16 * 4, 8, PNG_TRUECOLOR_ALPHA, (unsigned char *)pBuffer[1]);
+	png_close_file(&Png);
+
+	return 0;
+}
+
+int main(int argc, const char **argv)
+{
+	dbg_logger_stdout();
+	if(argc == 1)
+	{
+		dbg_msg("Usage", "%s FILE1 [ FILE2... ]", argv[0]);
+		return -1;
+	}
+
+	for(int i = 1; i < argc; i++)
+		FixFile(argv[i]);
+	return 0;
+}
diff -rupN teeworlds-b177-r50edfd37-source/src//tools/tileset_borderset.cpp alien-rc4/src//tools/tileset_borderset.cpp
--- teeworlds-b177-r50edfd37-source/src//tools/tileset_borderset.cpp	1970-01-01 01:00:00.000000000 +0100
+++ alien-rc4/src//tools/tileset_borderset.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -0,0 +1,78 @@
+/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
+/* If you are missing that file, acquire a complete release at teeworlds.com.                */
+#include <base/math.h>
+#include <base/system.h>
+#include <engine/external/pnglite/pnglite.h>
+
+typedef struct
+{
+	unsigned char r, g, b, a;
+} CPixel;
+
+static void TilesetBorderset(int w, int h, CPixel *pSrc, CPixel *pDest)
+{
+	int TileW = w/16;
+	int TileH = h/16;
+
+	for(int tx = 0; tx < 16; tx++)
+	{
+		for(int ty = 0; ty < 16; ty++)
+		{
+			for(int x = 0; x < TileW; x++)
+			{
+				for(int y = 0; y < TileH; y++)
+				{
+					#define TILE_INDEX(tx_, ty_, x_, y_) (((ty_) * TileH + (y_)) * w + (tx_) * TileW + (x_))
+					pDest[TILE_INDEX(tx, ty, x, y)] = pSrc[TILE_INDEX(tx, ty, clamp(x, 2, TileW - 3), clamp(y, 2, TileH - 3))];
+				}
+			}
+		}
+	}
+}
+
+
+int FixFile(const char *pFileName)
+{
+	png_t Png;
+	CPixel *pBuffer[2] = {0,0};
+
+	png_init(0, 0);
+	png_open_file(&Png, pFileName);
+
+	if(Png.color_type != PNG_TRUECOLOR_ALPHA)
+	{
+		dbg_msg("tileset_borderset", "%s: not an RGBA image", pFileName);
+		return 1;
+	}
+
+	int w = Png.width;
+	int h = Png.height;
+
+	pBuffer[0] = (CPixel*)mem_alloc(w*h*sizeof(CPixel), 1);
+	pBuffer[1] = (CPixel*)mem_alloc(w*h*sizeof(CPixel), 1);
+	png_get_data(&Png, (unsigned char *)pBuffer[0]);
+	png_close_file(&Png);
+
+	TilesetBorderset(w, h, pBuffer[0], pBuffer[1]);
+
+	// save here
+	png_open_file_write(&Png, pFileName);
+	png_set_data(&Png, w, h, 8, PNG_TRUECOLOR_ALPHA, (unsigned char *)pBuffer[1]);
+	png_close_file(&Png);
+
+	return 0;
+}
+
+int main(int argc, const char **argv)
+{
+	dbg_logger_stdout();
+	if(argc == 1)
+	{
+		dbg_msg("Usage", "%s FILE1 [ FILE2... ]", argv[0]);
+		return -1;
+	}
+
+	for(int i = 1; i < argc; i++)
+		FixFile(argv[i]);
+	return 0;
+}
diff -rupN teeworlds-b177-r50edfd37-source/src//versionsrv/versionsrv.cpp alien-rc4/src//versionsrv/versionsrv.cpp
--- teeworlds-b177-r50edfd37-source/src//versionsrv/versionsrv.cpp	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//versionsrv/versionsrv.cpp	2012-06-14 23:57:39.000000000 +0200
@@ -4,6 +4,8 @@
 
 #include <engine/shared/network.h>
 
+#include <game/version.h>
+
 #include "versionsrv.h"
 
 enum {
@@ -57,10 +59,10 @@ void BuildPackets()
 void SendVer(NETADDR *pAddr)
 {
 	CNetChunk p;
-	unsigned char aData[sizeof(VERSIONSRV_VERSION) + sizeof(VERSION_DATA)];
+	unsigned char aData[sizeof(VERSIONSRV_VERSION) + sizeof(GAME_RELEASE_VERSION)];
 
 	mem_copy(aData, VERSIONSRV_VERSION, sizeof(VERSIONSRV_VERSION));
-	mem_copy(aData + sizeof(VERSIONSRV_VERSION), VERSION_DATA, sizeof(VERSION_DATA));
+	mem_copy(aData + sizeof(VERSIONSRV_VERSION), GAME_RELEASE_VERSION, sizeof(GAME_RELEASE_VERSION));
 
 	p.m_ClientID = -1;
 	p.m_Address = *pAddr;
diff -rupN teeworlds-b177-r50edfd37-source/src//versionsrv/versionsrv.h alien-rc4/src//versionsrv/versionsrv.h
--- teeworlds-b177-r50edfd37-source/src//versionsrv/versionsrv.h	2011-07-31 23:17:00.000000000 +0200
+++ alien-rc4/src//versionsrv/versionsrv.h	2012-06-14 23:57:39.000000000 +0200
@@ -28,8 +28,6 @@ static CMapVersion s_aMapVersionList[] =
 };
 static const int s_NumMapVersionItems = sizeof(s_aMapVersionList)/sizeof(CMapVersion);
 
-static const unsigned char VERSION_DATA[] = {0x00, 0, 6, 0};
-
 static const unsigned char VERSIONSRV_GETVERSION[] = {255, 255, 255, 255, 'v', 'e', 'r', 'g'};
 static const unsigned char VERSIONSRV_VERSION[] = {255, 255, 255, 255, 'v', 'e', 'r', 's'};
 
