Radix cross Linux

Radix Linux distribution for embedded systems.

637 Commits   4 Branches   3 Tags
author: Andrey V.Kosteltsev <kx@radix.pro> 2016-10-15 00:19:33 +0000 committer: Andrey V.Kosteltsev <kx@radix.pro> 2016-10-15 00:19:33 +0000 commit: 97caf2550daab6f0cba57170a10f5f2d4fd8b89e parent: 06edf95a4b548ff0d09d7302a27c15e36489a6b5
Commit Summary:
Simple DirectMedia Layer library
Diffstat:
37 files changed, 8313 insertions, 0 deletions
diff --git a/X11/libs/sdl/sdl/1.2.15-x86_32/Makefile b/X11/libs/sdl/sdl/1.2.15-x86_32/Makefile
new file mode 100644
index 000000000..c049f7bb4
--- /dev/null
+++ b/X11/libs/sdl/sdl/1.2.15-x86_32/Makefile
@@ -0,0 +1,200 @@
+
+COMPONENT_TARGETS  = $(HARDWARE_PC64)
+
+NEED_ABS_PATH      = true
+COMPONENT_IS_3PP   = true
+
+CREATE_X86_32_PACKAGE = true
+
+
+include ../../../../../build-system/constants.mk
+
+
+SOURCE_REQUIRES    = sources/packages/l/sdl/sdl
+
+REQUIRES           = X11/libs/sdl/sdl/1.2.15
+REQUIRES          += libs/alsa-lib/1.1.1-x86_32
+REQUIRES          += libs/pulseaudio/9.0-x86_32
+REQUIRES          += app/esound/0.2.41-x86_32
+REQUIRES          += X11/X.org/lib/libXrandr/1.5.0-x86_32
+REQUIRES          += libs/aalib/1.4.0-x86_32
+
+REQUIRES          += X11/libs/opengl-collection
+
+# ======= __END_OF_REQUIRES__ =======
+
+
+version            = 1.2.15
+tar_gz_archive     = $(SRC_PACKAGE_PATH)/packages/l/sdl/sdl/SDL-$(version).tar.gz
+SRC_ARCHIVE        = $(tar_gz_archive)
+SRC_DIR            = $(TARGET_BUILD_DIR)/SDL-$(version)
+src_dir_name       = SDL-$(version)
+doc_dir_name       = sdl-$(version)
+src_done           = $(TARGET_BUILD_DIR)/.source_done
+
+PATCHES = PATCHES
+
+build_dir          = $(TARGET_BUILD_DIR)/build
+build_target       = $(TARGET_BUILD_DIR)/.build_done
+install_target     = $(TARGET_BUILD_DIR)/.install_done
+
+
+####### Targets
+
+PKG_GROUP = xlibs
+
+#
+# *PKG_NAME & *PKG_VERSION shouldn't be a reference to value.
+#
+SDL_32_PKG_NAME                = sdl-x32
+SDL_32_PKG_VERSION             = 1.2.15
+SDL_32_PKG_ARCH                = $(TOOLCHAIN)
+SDL_32_PKG_DISTRO_NAME         = $(DISTRO_NAME)
+SDL_32_PKG_DISTRO_VERSION      = $(DISTRO_VERSION)
+SDL_32_PKG_GROUP               = $(PKG_GROUP)
+###                             |---handy-ruler-------------------------------|
+SDL_32_PKG_SHORT_DESCRIPTION   = Simple DirectMedia Layer library
+SDL_32_PKG_URL                 = $(BUG_URL)
+SDL_32_PKG_LICENSE             = LGPLv2.1
+SDL_32_PKG_DESCRIPTION_FILE    = $(TARGET_BUILD_DIR)/$(SDL_32_PKG_NAME)-pkg-description
+SDL_32_PKG_DESCRIPTION_FILE_IN = $(SDL_32_PKG_NAME)-pkg-description.in
+SDL_32_PKG_INSTALL_SCRIPT      = $(SDL_32_PKG_NAME)-pkg-install.sh
+
+SDL_32_PKG       = $(CURDIR)/$(TARGET_BUILD_DIR)/$(SDL_32_PKG_NAME)-package
+
+pkg_basename     = $(SDL_32_PKG_NAME)-$(SDL_32_PKG_VERSION)-$(SDL_32_PKG_ARCH)-$(SDL_32_PKG_DISTRO_NAME)-$(SDL_32_PKG_DISTRO_VERSION)
+
+pkg_archive      = $(TARGET_BUILD_DIR)/$(PKG_GROUP)/$(pkg_basename).$(pkg_arch_suffix)
+pkg_signature    = $(call sign-name,$(pkg_archive))
+pkg_description  = $(call desc-name,$(pkg_archive))
+products         = $(call pkg-files,$(pkg_archive))
+
+BUILD_TARGETS    = $(build_target)
+BUILD_TARGETS   += $(install_target)
+
+PRODUCT_TARGETS  = $(products)
+
+ROOTFS_TARGETS   = $(pkg_archive)
+
+
+include ../../../../../build-system/core.mk
+
+
+env_sysroot  = DESTDIR=$(SDL_32_PKG)
+
+
+extra_configure_switches  = --libdir=/usr/lib$(MULTILIB_X86_32_SUFFIX)
+extra_configure_switches += --docdir=/usr/share/doc/$(src_dir_name)
+extra_configure_switches += --infodir=/usr/share/info
+extra_configure_switches += --mandir=/usr/share/man
+
+extra_configure_switches += --bindir=/usr/bin/32
+
+extra_configure_switches += --with-x
+extra_configure_switches += --disable-arts
+extra_configure_switches += --disable-nasm
+extra_configure_switches += --enable-alsa
+extra_configure_switches += --enable-esd
+extra_configure_switches += --enable-video-aalib
+
+extra_configure_switches += --disable-rpath
+extra_configure_switches += --disable-x11-shared
+
+extra_configure_switches += --enable-static=yes
+extra_configure_switches += --enable-shared=yes
+
+
+TARGET_LIB_RPATH = /lib$(MULTILIB_X86_32_SUFFIX):/usr/lib$(MULTILIB_X86_32_SUFFIX):/usr/lib/../lib$(MULTILIB_X86_32_SUFFIX)
+
+LDFLAGS += -Wl,-rpath,$(TARGET_LIB_RPATH)
+
+
+####### Dependencies
+
+$(src_done): $(SRC_ARCHIVE) $(PATCHES_DEP)
+	$(UNPACK_SRC_ARCHIVE)
+	$(APPLY_PATCHES)
+	@touch $@
+
+$(build_target): $(src_done)
+	@mkdir -p $(build_dir)
+	@cd $(build_dir) && $(BUILD_ENVIRONMENT) ../$(src_dir_name)/configure \
+	  --prefix=/usr               \
+	  --build=$(BUILD)            \
+	  --host=$(TARGET32)          \
+	  $(extra_configure_switches)
+	@( cd $(build_dir) ; \
+	   sed -i "s, -L/usr/lib64,,g" Makefile   ; \
+	   sed -i "s, -L/usr/lib64,,g" sdl-config ; \
+	   sed -i "s, -L/usr/lib64,,g" sdl.pc     ; \
+	 )
+	@cd $(build_dir) && $(BUILD_ENVIRONMENT) $(MAKE)
+	@touch $@
+
+$(install_target): $(build_target)
+	@mkdir -p $(SDL_32_PKG)
+	@cd $(build_dir) && $(BUILD_ENVIRONMENT) $(MAKE) -j1 install $(env_sysroot)
+	@rm -rf $(SDL_32_PKG)/usr/include
+	@rm -rf $(SDL_32_PKG)/usr/share
+	# ======= tune library path in the sdl-config script =======
+	@( cd $(SDL_32_PKG)/usr/bin/32 ; \
+	   sed -i 's,-L/usr,-L$${prefix},g' sdl-config ; \
+	 )
+	# ======= remove toolchain path from target libtool *.la files =======
+	@( cd $(SDL_32_PKG)/usr/lib$(MULTILIB_X86_32_SUFFIX) ; \
+	   sed -i "s,$(TARGET_DEST_DIR),,g" libSDL.la libSDLmain.la ; \
+	 )
+	# ======= Install the same to $(TARGET_DEST_DIR) =======
+	$(call install-into-devenv, $(SDL_32_PKG))
+	# ======= tune libtool *.la search path to the target destination for development =======
+	@( cd $(TARGET_DEST_DIR)/usr/lib$(MULTILIB_X86_32_SUFFIX) ; \
+	   sed -i "s,/usr,$(TARGET_DEST_DIR)/usr,g" libSDL.la libSDLmain.la ; \
+	   sed -i "s,L/lib,L$(TARGET_DEST_DIR)/lib,g" libSDL.la libSDLmain.la ; \
+	 )
+	# ======= tune pkg-config *.pc search path to the target destination for development =======
+	@( cd $(TARGET_DEST_DIR)/usr/lib$(MULTILIB_X86_32_SUFFIX)/pkgconfig ; \
+	   sed -i "s,/usr,$(TARGET_DEST_DIR)/usr,g" sdl.pc ; \
+	 )
+	# ======= tune prefix for development in the sdl-config script =======
+	@( cd $(TARGET_DEST_DIR)/usr/bin/32 ; \
+	   sed -i "s,=/usr,=$(TARGET_DEST_DIR)/usr,g" sdl-config ; \
+	 )
+	# ======= Strip binaries =======
+	@( cd $(SDL_32_PKG); \
+	   find . | xargs file | grep "executable" | grep ELF | cut -f 1 -d : | xargs $(STRIP) --strip-unneeded 2> /dev/null ; \
+	   find . | xargs file | grep "shared object" | grep ELF | cut -f 1 -d : | xargs $(STRIP) --strip-unneeded 2> /dev/null ; \
+	   find . | xargs file | grep "current ar archive" | cut -f 1 -d : | xargs $(STRIP) -g 2> /dev/null \
+	 )
+ifneq ($(CHRPATH),)
+	# ======= Set RPATH/RUNPATH for target shared objects =======
+	@( cd $(SDL_32_PKG)/usr/lib$(MULTILIB_X86_32_SUFFIX) ; \
+	   for file in `find . | xargs file | grep "shared object" | grep ELF | cut -f 1 -d : | xargs echo` ; do \
+	     rpath=`$(CHRPATH) -l $$file 2> /dev/null | grep "R*PATH"` ; \
+	     if echo "$$rpath" | grep -q "$(TARGET_DEST_DIR)" ; then \
+	       $(CHRPATH) -r $(TARGET_LIB_RPATH) $$file 1> /dev/null 2> /dev/null ; \
+	     fi ; \
+	   done ; \
+	 )
+endif
+	@touch $@
+
+$(SDL_32_PKG_DESCRIPTION_FILE): $(SDL_32_PKG_DESCRIPTION_FILE_IN)
+	@cat $< | $(SED) -e "s/@VERSION@/$(version)/g" > $@
+
+$(pkg_signature)   : $(pkg_archive) ;
+$(pkg_description) : $(pkg_archive) ;
+
+$(pkg_archive): $(install_target) $(SDL_32_PKG_DESCRIPTION_FILE) $(SDL_32_PKG_INSTALL_SCRIPT)
+	@cp $(SDL_32_PKG_DESCRIPTION_FILE) $(SDL_32_PKG)/.DESCRIPTION
+	@cp $(SDL_32_PKG_INSTALL_SCRIPT) $(SDL_32_PKG)/.INSTALL
+	@$(BUILD_PKG_REQUIRES) $(SDL_32_PKG)/.REQUIRES
+	@echo "pkgname=$(SDL_32_PKG_NAME)"                            >  $(SDL_32_PKG)/.PKGINFO ; \
+	 echo "pkgver=$(SDL_32_PKG_VERSION)"                          >> $(SDL_32_PKG)/.PKGINFO ; \
+	 echo "arch=$(SDL_32_PKG_ARCH)"                               >> $(SDL_32_PKG)/.PKGINFO ; \
+	 echo "distroname=$(SDL_32_PKG_DISTRO_NAME)"                  >> $(SDL_32_PKG)/.PKGINFO ; \
+	 echo "distrover=$(SDL_32_PKG_DISTRO_VERSION)"                >> $(SDL_32_PKG)/.PKGINFO ; \
+	 echo "group=$(SDL_32_PKG_GROUP)"                             >> $(SDL_32_PKG)/.PKGINFO ; \
+	 echo "short_description=\"$(SDL_32_PKG_SHORT_DESCRIPTION)\"" >> $(SDL_32_PKG)/.PKGINFO ; \
+	 echo "url=$(SDL_32_PKG_URL)"                                 >> $(SDL_32_PKG)/.PKGINFO ; \
+	 echo "license=$(SDL_32_PKG_LICENSE)"                         >> $(SDL_32_PKG)/.PKGINFO
+	@$(FAKEROOT) sh -c "cd $(SDL_32_PKG) && chown -R root:root . && $(MAKE_PACKAGE) --linkadd yes .."
diff --git a/X11/libs/sdl/sdl/1.2.15-x86_32/PATCHES b/X11/libs/sdl/sdl/1.2.15-x86_32/PATCHES
new file mode 100644
index 000000000..9a84e2cfe
--- /dev/null
+++ b/X11/libs/sdl/sdl/1.2.15-x86_32/PATCHES
@@ -0,0 +1,7 @@
+
+../../../../../sources/packages/l/sdl/sdl/patches/SDL-1.2.15-bypass-gamma.patch  -p0
+../../../../../sources/packages/l/sdl/sdl/patches/SDL-1.2.15-disable-mmx.patch   -p0
+../../../../../sources/packages/l/sdl/sdl/patches/SDL-1.2.15-joystick-axis.patch -p0
+../../../../../sources/packages/l/sdl/sdl/patches/SDL-1.2.15-x11-XData32.patch   -p0
+../../../../../sources/packages/l/sdl/sdl/patches/SDL-1.2.15-x11-events.patch    -p0
+../../../../../sources/packages/l/sdl/sdl/patches/SDL-1.2.15-x11-grab.patch      -p0
diff --git a/X11/libs/sdl/sdl/1.2.15-x86_32/sdl-x32-pkg-description.in b/X11/libs/sdl/sdl/1.2.15-x86_32/sdl-x32-pkg-description.in
new file mode 100644
index 000000000..52408c26f
--- /dev/null
+++ b/X11/libs/sdl/sdl/1.2.15-x86_32/sdl-x32-pkg-description.in
@@ -0,0 +1,19 @@
+# HOW TO EDIT THIS FILE:
+# The "handy ruler" below makes it easier to edit a package description.  Line
+# up the first '|' above the ':' following the base package name, and the '|'
+# on the right side marks the last column you can put a character in.  You must
+# make exactly 11 lines for the formatting to be correct.  It's also
+# customary to leave one space after the ':'.
+
+       |-----handy-ruler------------------------------------------------------|
+sdl-x32: sdl-x32 @VERSION@ (x86_32 Simple DirectMedia Layer library)
+sdl-x32:
+sdl-x32: This is the Simple DirectMedia Layer, a generic API that provides
+sdl-x32: low level access to audio, keyboard, mouse, joystick, 3D hardware
+sdl-x32: via OpenGL, and 2D framebuffer across multiple platforms.
+sdl-x32:
+sdl-x32:
+sdl-x32: Homepage: http://www.libsdl.org
+sdl-x32:
+sdl-x32:
+sdl-x32:
diff --git a/X11/libs/sdl/sdl/1.2.15-x86_32/sdl-x32-pkg-install.sh b/X11/libs/sdl/sdl/1.2.15-x86_32/sdl-x32-pkg-install.sh
new file mode 100755
index 000000000..8e8683cd6
--- /dev/null
+++ b/X11/libs/sdl/sdl/1.2.15-x86_32/sdl-x32-pkg-install.sh
@@ -0,0 +1,39 @@
+#!/bin/sh
+
+# arg 1:  the new package version
+pre_install() {
+  /bin/true
+}
+
+# arg 1:  the new package version
+post_install() {
+  /bin/true
+}
+
+# arg 1:  the new package version
+# arg 2:  the old package version
+pre_update() {
+  /bin/true
+}
+
+# arg 1:  the new package version
+# arg 2:  the old package version
+post_update() {
+  post_install
+}
+
+# arg 1:  the old package version
+pre_remove() {
+  /bin/true
+}
+
+# arg 1:  the old package version
+post_remove() {
+  /bin/true
+}
+
+
+operation=$1
+shift
+
+$operation $*
diff --git a/X11/libs/sdl/sdl/1.2.15/Makefile b/X11/libs/sdl/sdl/1.2.15/Makefile
new file mode 100644
index 000000000..d11d71b03
--- /dev/null
+++ b/X11/libs/sdl/sdl/1.2.15/Makefile
@@ -0,0 +1,233 @@
+
+COMPONENT_TARGETS  = $(HARDWARE_PC32)
+COMPONENT_TARGETS += $(HARDWARE_PC64)
+COMPONENT_TARGETS += $(HARDWARE_CB1X)
+COMPONENT_TARGETS += $(HARDWARE_CB2X)
+COMPONENT_TARGETS += $(HARDWARE_CB3X)
+COMPONENT_TARGETS += $(HARDWARE_FFRK3288)
+COMPONENT_TARGETS += $(HARDWARE_M201)
+COMPONENT_TARGETS += $(HARDWARE_MXQ)
+COMPONENT_TARGETS += $(HARDWARE_NIT6Q)
+COMPONENT_TARGETS += $(HARDWARE_OMAP5UEVM)
+COMPONENT_TARGETS += $(HARDWARE_DRA7XXEVM)
+COMPONENT_TARGETS += $(HARDWARE_CI20)
+COMPONENT_TARGETS += $(HARDWARE_BT1)
+
+
+NEED_ABS_PATH      = true
+COMPONENT_IS_3PP   = true
+
+
+include ../../../../../build-system/constants.mk
+
+
+SOURCE_REQUIRES    = sources/packages/l/sdl/sdl
+
+REQUIRES           = libs/alsa-lib/1.1.1
+REQUIRES          += libs/pulseaudio/9.0
+REQUIRES          += app/esound/0.2.41
+REQUIRES          += X11/X.org/lib/libXrandr/1.5.0
+REQUIRES          += libs/aalib/1.4.0
+
+REQUIRES          += X11/libs/opengl-collection
+
+# ======= __END_OF_REQUIRES__ =======
+
+
+version            = 1.2.15
+tar_gz_archive     = $(SRC_PACKAGE_PATH)/packages/l/sdl/sdl/SDL-$(version).tar.gz
+SRC_ARCHIVE        = $(tar_gz_archive)
+SRC_DIR            = $(TARGET_BUILD_DIR)/SDL-$(version)
+src_dir_name       = SDL-$(version)
+doc_dir_name       = sdl-$(version)
+src_done           = $(TARGET_BUILD_DIR)/.source_done
+
+
+PATCHES = PATCHES
+
+build_dir          = $(TARGET_BUILD_DIR)/build
+build_target       = $(TARGET_BUILD_DIR)/.build_done
+install_target     = $(TARGET_BUILD_DIR)/.install_done
+
+
+####### Targets
+
+PKG_GROUP = xlibs
+
+#
+# *PKG_NAME & *PKG_VERSION shouldn't be a reference to value.
+#
+SDL_PKG_NAME                = sdl
+SDL_PKG_VERSION             = 1.2.15
+SDL_PKG_ARCH                = $(TOOLCHAIN)
+SDL_PKG_DISTRO_NAME         = $(DISTRO_NAME)
+SDL_PKG_DISTRO_VERSION      = $(DISTRO_VERSION)
+SDL_PKG_GROUP               = $(PKG_GROUP)
+###                          |---handy-ruler-------------------------------|
+SDL_PKG_SHORT_DESCRIPTION   = Simple DirectMedia Layer library
+SDL_PKG_URL                 = $(BUG_URL)
+SDL_PKG_LICENSE             = LGPLv2.1
+SDL_PKG_DESCRIPTION_FILE    = $(TARGET_BUILD_DIR)/$(SDL_PKG_NAME)-pkg-description
+SDL_PKG_DESCRIPTION_FILE_IN = $(SDL_PKG_NAME)-pkg-description.in
+SDL_PKG_INSTALL_SCRIPT      = $(SDL_PKG_NAME)-pkg-install.sh
+
+SDL_PKG          = $(CURDIR)/$(TARGET_BUILD_DIR)/$(SDL_PKG_NAME)-package
+
+pkg_basename     = $(SDL_PKG_NAME)-$(SDL_PKG_VERSION)-$(SDL_PKG_ARCH)-$(SDL_PKG_DISTRO_NAME)-$(SDL_PKG_DISTRO_VERSION)
+
+pkg_archive      = $(TARGET_BUILD_DIR)/$(PKG_GROUP)/$(pkg_basename).$(pkg_arch_suffix)
+pkg_signature    = $(call sign-name,$(pkg_archive))
+pkg_description  = $(call desc-name,$(pkg_archive))
+products         = $(call pkg-files,$(pkg_archive))
+
+BUILD_TARGETS    = $(build_target)
+BUILD_TARGETS   += $(install_target)
+
+PRODUCT_TARGETS  = $(products)
+
+ROOTFS_TARGETS   = $(pkg_archive)
+
+
+include ../../../../../build-system/core.mk
+
+
+env_sysroot = DESTDIR=$(SDL_PKG)
+
+
+extra_configure_switches  = --libdir=/usr/lib$(LIBSUFFIX)
+extra_configure_switches += --docdir=/usr/share/doc/$(doc_dir_name)
+extra_configure_switches += --infodir=/usr/share/info
+extra_configure_switches += --mandir=/usr/share/man
+
+extra_configure_switches += --with-x
+extra_configure_switches += --disable-arts
+extra_configure_switches += --disable-nasm
+extra_configure_switches += --enable-alsa
+extra_configure_switches += --enable-esd
+extra_configure_switches += --enable-video-aalib
+
+extra_configure_switches += --disable-rpath
+extra_configure_switches += --disable-x11-shared
+
+extra_configure_switches += --enable-shared=yes
+extra_configure_switches += --enable-static=yes
+
+
+TARGET_LIB_RPATH = /lib$(LIBSUFFIX):/usr/lib$(LIBSUFFIX):/usr/lib/../lib$(LIBSUFFIX)
+
+LDFLAGS += -Wl,-rpath,$(TARGET_LIB_RPATH)
+
+
+####### Dependencies
+
+$(src_done): $(SRC_ARCHIVE) $(PATCHES_DEP)
+	$(UNPACK_SRC_ARCHIVE)
+	$(APPLY_PATCHES)
+	@touch $@
+
+$(build_target): $(src_done)
+	@mkdir -p $(build_dir)
+	@cd $(build_dir) && \
+	  $(BUILD_ENVIRONMENT) ../$(src_dir_name)/configure \
+	  --prefix=/usr               \
+	  --build=$(BUILD)            \
+	  --host=$(TARGET)            \
+	  $(extra_configure_switches)
+	@cd $(build_dir) && $(BUILD_ENVIRONMENT) $(MAKE)
+	@touch $@
+
+$(install_target): $(build_target)
+	@mkdir -p $(SDL_PKG)
+	@cd $(build_dir) && $(BUILD_ENVIRONMENT) $(MAKE) -j1 install $(env_sysroot)
+	# ======= Install Documentation =======
+	@if [ -d $(SDL_PKG)/usr/share/man ]; then \
+	  ( cd $(SDL_PKG)/usr/share/man ; \
+	    for manpagedir in `find . -type d -name "man*"` ; do \
+	      ( cd $$manpagedir ; \
+	        for eachpage in `find . -type l -maxdepth 1` ; do \
+	          ln -s `readlink $$eachpage`.gz $$eachpage.gz ; \
+	          rm $$eachpage ; \
+	        done ; \
+	        gzip -9 *.?  ; \
+	      ) \
+	    done \
+	  ) \
+	 fi
+	@mkdir -p $(SDL_PKG)/usr/doc/$(doc_dir_name)
+	@cp -a $(SRC_DIR)/COPYING $(SRC_DIR)/CREDITS \
+	       $(SDL_PKG)/usr/doc/$(doc_dir_name)
+	@mkdir -p $(SDL_PKG)/usr/share/doc/$(doc_dir_name)
+	@( cd $(SRC_DIR) ; \
+	   cp -a COPYING CREDITS INSTALL README TODO \
+	         docs/html docs/images docs/index.html \
+	         $(SDL_PKG)/usr/share/doc/$(doc_dir_name) ; \
+	 )
+	@( cd $(SRC_DIR) ; \
+	   if [ -r ChangeLog ]; then \
+	     DOCSDIR=`echo $(SDL_PKG)/usr/share/doc/$(doc_dir_name)` ; \
+	     cat ChangeLog | head -n 1000 > $$DOCSDIR/ChangeLog ; \
+	     touch -r ChangeLog $$DOCSDIR/ChangeLog ; \
+	   fi \
+	 )
+	# ======= tune library path in the sdl-config script =======
+	@( cd $(SDL_PKG)/usr/bin ; \
+	   sed -i 's,-L/usr,-L$${prefix},g' sdl-config ; \
+	 )
+	# ======= remove toolchain path from target libtool *.la files =======
+	@( cd $(SDL_PKG)/usr/lib$(LIBSUFFIX) ; \
+	   sed -i "s,$(TARGET_DEST_DIR),,g" libSDL.la libSDLmain.la ; \
+	 )
+	# ======= Install the same to $(TARGET_DEST_DIR) =======
+	$(call install-into-devenv, $(SDL_PKG))
+	# ======= tune libtool *.la search path to the target destination for development =======
+	@( cd $(TARGET_DEST_DIR)/usr/lib$(LIBSUFFIX) ; \
+	   sed -i "s,/usr,$(TARGET_DEST_DIR)/usr,g" libSDL.la libSDLmain.la ; \
+	   sed -i "s,L/lib,L$(TARGET_DEST_DIR)/lib,g" libSDL.la libSDLmain.la ; \
+	 )
+	# ======= tune pkg-config *.pc search path to the target destination for development =======
+	@( cd $(TARGET_DEST_DIR)/usr/lib$(LIBSUFFIX)/pkgconfig ; \
+	   sed -i "s,/usr,$(TARGET_DEST_DIR)/usr,g" sdl.pc ; \
+	 )
+	# ======= tune prefix for development in the sdl-config script =======
+	@( cd $(TARGET_DEST_DIR)/usr/bin ; \
+	   sed -i "s,=/usr,=$(TARGET_DEST_DIR)/usr,g" sdl-config ; \
+	 )
+	# ======= Strip binaries =======
+	@( cd $(SDL_PKG); \
+	   find . | xargs file | grep "executable" | grep ELF | cut -f 1 -d : | xargs $(STRIP) --strip-unneeded 2> /dev/null ; \
+	   find . | xargs file | grep "shared object" | grep ELF | cut -f 1 -d : | xargs $(STRIP) --strip-unneeded 2> /dev/null ; \
+	   find . | xargs file | grep "current ar archive" | cut -f 1 -d : | xargs $(STRIP) -g 2> /dev/null \
+	 )
+ifneq ($(CHRPATH),)
+	# ======= Set RPATH/RUNPATH for target shared objects =======
+	@( cd $(SDL_PKG)/usr/lib$(LIBSUFFIX) ; \
+	   for file in `find . | xargs file | grep "shared object" | grep ELF | cut -f 1 -d : | xargs echo` ; do \
+	     rpath=`$(CHRPATH) -l $$file 2> /dev/null | grep "R*PATH"` ; \
+	     if echo "$$rpath" | grep -q "$(TARGET_DEST_DIR)" ; then \
+	       $(CHRPATH) -r $(TARGET_LIB_RPATH) $$file 1> /dev/null 2> /dev/null ; \
+	     fi ; \
+	   done ; \
+	 )
+endif
+	@touch $@
+
+$(SDL_PKG_DESCRIPTION_FILE): $(SDL_PKG_DESCRIPTION_FILE_IN)
+	@cat $< | $(SED) -e "s/@VERSION@/$(version)/g" > $@
+
+$(pkg_signature)   : $(pkg_archive) ;
+$(pkg_description) : $(pkg_archive) ;
+
+$(pkg_archive): $(install_target) $(SDL_PKG_DESCRIPTION_FILE) $(SDL_PKG_INSTALL_SCRIPT)
+	@cp $(SDL_PKG_DESCRIPTION_FILE) $(SDL_PKG)/.DESCRIPTION
+	@cp $(SDL_PKG_INSTALL_SCRIPT) $(SDL_PKG)/.INSTALL
+	@$(BUILD_PKG_REQUIRES) $(SDL_PKG)/.REQUIRES
+	@echo "pkgname=$(SDL_PKG_NAME)"                            >  $(SDL_PKG)/.PKGINFO ; \
+	 echo "pkgver=$(SDL_PKG_VERSION)"                          >> $(SDL_PKG)/.PKGINFO ; \
+	 echo "arch=$(SDL_PKG_ARCH)"                               >> $(SDL_PKG)/.PKGINFO ; \
+	 echo "distroname=$(SDL_PKG_DISTRO_NAME)"                  >> $(SDL_PKG)/.PKGINFO ; \
+	 echo "distrover=$(SDL_PKG_DISTRO_VERSION)"                >> $(SDL_PKG)/.PKGINFO ; \
+	 echo "group=$(SDL_PKG_GROUP)"                             >> $(SDL_PKG)/.PKGINFO ; \
+	 echo "short_description=\"$(SDL_PKG_SHORT_DESCRIPTION)\"" >> $(SDL_PKG)/.PKGINFO ; \
+	 echo "url=$(SDL_PKG_URL)"                                 >> $(SDL_PKG)/.PKGINFO ; \
+	 echo "license=$(SDL_PKG_LICENSE)"                         >> $(SDL_PKG)/.PKGINFO
+	@$(FAKEROOT) sh -c "cd $(SDL_PKG) && chown -R root:root . && $(MAKE_PACKAGE) --linkadd yes .."
diff --git a/X11/libs/sdl/sdl/1.2.15/PATCHES b/X11/libs/sdl/sdl/1.2.15/PATCHES
new file mode 100644
index 000000000..9a84e2cfe
--- /dev/null
+++ b/X11/libs/sdl/sdl/1.2.15/PATCHES
@@ -0,0 +1,7 @@
+
+../../../../../sources/packages/l/sdl/sdl/patches/SDL-1.2.15-bypass-gamma.patch  -p0
+../../../../../sources/packages/l/sdl/sdl/patches/SDL-1.2.15-disable-mmx.patch   -p0
+../../../../../sources/packages/l/sdl/sdl/patches/SDL-1.2.15-joystick-axis.patch -p0
+../../../../../sources/packages/l/sdl/sdl/patches/SDL-1.2.15-x11-XData32.patch   -p0
+../../../../../sources/packages/l/sdl/sdl/patches/SDL-1.2.15-x11-events.patch    -p0
+../../../../../sources/packages/l/sdl/sdl/patches/SDL-1.2.15-x11-grab.patch      -p0
diff --git a/X11/libs/sdl/sdl/1.2.15/sdl-pkg-description.in b/X11/libs/sdl/sdl/1.2.15/sdl-pkg-description.in
new file mode 100644
index 000000000..1b11f77bc
--- /dev/null
+++ b/X11/libs/sdl/sdl/1.2.15/sdl-pkg-description.in
@@ -0,0 +1,19 @@
+# HOW TO EDIT THIS FILE:
+# The "handy ruler" below makes it easier to edit a package description.  Line
+# up the first '|' above the ':' following the base package name, and the '|'
+# on the right side marks the last column you can put a character in.  You must
+# make exactly 11 lines for the formatting to be correct.  It's also
+# customary to leave one space after the ':'.
+
+   |-----handy-ruler------------------------------------------------------|
+sdl: sdl @VERSION@ (Simple DirectMedia Layer library)
+sdl:
+sdl: This is the Simple DirectMedia Layer, a generic API that provides
+sdl: low level access to audio, keyboard, mouse, joystick, 3D hardware
+sdl: via OpenGL, and 2D framebuffer across multiple platforms.
+sdl:
+sdl:
+sdl: Homepage: http://www.libsdl.org
+sdl:
+sdl:
+sdl:
diff --git a/X11/libs/sdl/sdl/1.2.15/sdl-pkg-install.sh b/X11/libs/sdl/sdl/1.2.15/sdl-pkg-install.sh
new file mode 100755
index 000000000..b44c4e648
--- /dev/null
+++ b/X11/libs/sdl/sdl/1.2.15/sdl-pkg-install.sh
@@ -0,0 +1,53 @@
+#!/bin/sh
+
+# Preserve new files
+install_file() {
+  NEW="$1"
+  OLD="`dirname $NEW`/`basename $NEW .new`"
+  # If there's no file by that name, mv it over:
+  if [ ! -r $OLD ]; then
+    mv $NEW $OLD
+  elif [ "`cat $OLD | md5sum`" = "`cat $NEW | md5sum`" ]; then # toss the redundant copy
+    rm $NEW
+  fi
+  # Otherwise, we leave the .new copy for the admin to consider...
+}
+
+
+# arg 1:  the new package version
+pre_install() {
+  /bin/true
+}
+
+# arg 1:  the new package version
+post_install() {
+  /bin/true
+}
+
+# arg 1:  the new package version
+# arg 2:  the old package version
+pre_update() {
+  /bin/true
+}
+
+# arg 1:  the new package version
+# arg 2:  the old package version
+post_update() {
+  post_install
+}
+
+# arg 1:  the old package version
+pre_remove() {
+  /bin/true
+}
+
+# arg 1:  the old package version
+post_remove() {
+  /bin/true
+}
+
+
+operation=$1
+shift
+
+$operation $*
diff --git a/sources/packages/l/sdl/Makefile b/sources/packages/l/sdl/Makefile
new file mode 100644
index 000000000..78f51bc23
--- /dev/null
+++ b/sources/packages/l/sdl/Makefile
@@ -0,0 +1,13 @@
+
+COMPONENT_TARGETS = $(HARDWARE_NOARCH)
+
+SOURCE_REQUIRES += ALL_DIRS
+
+
+include ../../../../build-system/core.mk
+
+
+download_clean:
+	@true
+
+.PHONY: download_clean
diff --git a/sources/packages/l/sdl/sdl-image/Makefile b/sources/packages/l/sdl/sdl-image/Makefile
new file mode 100644
index 000000000..51baaab0f
--- /dev/null
+++ b/sources/packages/l/sdl/sdl-image/Makefile
@@ -0,0 +1,47 @@
+
+COMPONENT_TARGETS = $(HARDWARE_NOARCH)
+
+
+include ../../../../../build-system/constants.mk
+
+
+url         = $(DOWNLOAD_SERVER)/sources/packages/l/sdl/sdl-image
+
+versions    = 1.2.12
+pkgname     = SDL_image
+suffix      = tar.gz
+
+tarballs    = $(addsuffix .$(suffix), $(addprefix $(pkgname)-, $(versions)))
+sha1s       = $(addsuffix .sha1sum, $(tarballs))
+
+
+BUILD_TARGETS = $(tarballs) $(sha1s)
+
+
+include ../../../../../build-system/core.mk
+
+
+.PHONY: download_clean
+
+
+$(tarballs):
+	@echo -e "\n======= Downloading source tarballs =======" ; \
+	 for tarball in $(tarballs) ; do \
+	   echo "$(url)/$$tarball" | xargs -n 1 -P 100 wget $(WGET_OPTIONS) -i & \
+	 done ; wait
+
+$(sha1s): $(tarballs)
+	@for sha in $@ ; do \
+	   echo -e "\n======= Downloading '$$sha' signature =======\n" ; \
+	   echo "$(url)/$$sha" | xargs -n 1 -P 100 wget $(WGET_OPTIONS) -i & wait %1 ; \
+	   touch $$sha ; \
+	   echo -e "\n======= Check the '$$sha' sha1sum =======\n" ; \
+	   sha1sum --check $$sha ; ret="$$?" ; \
+	   if [ "$$ret" == "1" ]; then \
+	     echo -e "\n======= ERROR: Bad '$$sha' sha1sum =======\n" ; \
+	     exit 1 ; \
+	   fi ; \
+	 done
+
+download_clean:
+	@rm -f $(tarballs) $(sha1s)
diff --git a/sources/packages/l/sdl/sdl-mixer/Makefile b/sources/packages/l/sdl/sdl-mixer/Makefile
new file mode 100644
index 000000000..e490b8c9e
--- /dev/null
+++ b/sources/packages/l/sdl/sdl-mixer/Makefile
@@ -0,0 +1,47 @@
+
+COMPONENT_TARGETS = $(HARDWARE_NOARCH)
+
+
+include ../../../../../build-system/constants.mk
+
+
+url         = $(DOWNLOAD_SERVER)/sources/packages/l/sdl/sdl-mixer
+
+versions    = 1.2.12
+pkgname     = SDL_mixer
+suffix      = tar.gz
+
+tarballs    = $(addsuffix .$(suffix), $(addprefix $(pkgname)-, $(versions)))
+sha1s       = $(addsuffix .sha1sum, $(tarballs))
+
+
+BUILD_TARGETS = $(tarballs) $(sha1s)
+
+
+include ../../../../../build-system/core.mk
+
+
+.PHONY: download_clean
+
+
+$(tarballs):
+	@echo -e "\n======= Downloading source tarballs =======" ; \
+	 for tarball in $(tarballs) ; do \
+	   echo "$(url)/$$tarball" | xargs -n 1 -P 100 wget $(WGET_OPTIONS) -i & \
+	 done ; wait
+
+$(sha1s): $(tarballs)
+	@for sha in $@ ; do \
+	   echo -e "\n======= Downloading '$$sha' signature =======\n" ; \
+	   echo "$(url)/$$sha" | xargs -n 1 -P 100 wget $(WGET_OPTIONS) -i & wait %1 ; \
+	   touch $$sha ; \
+	   echo -e "\n======= Check the '$$sha' sha1sum =======\n" ; \
+	   sha1sum --check $$sha ; ret="$$?" ; \
+	   if [ "$$ret" == "1" ]; then \
+	     echo -e "\n======= ERROR: Bad '$$sha' sha1sum =======\n" ; \
+	     exit 1 ; \
+	   fi ; \
+	 done
+
+download_clean:
+	@rm -f $(tarballs) $(sha1s)
diff --git a/sources/packages/l/sdl/sdl-net/Makefile b/sources/packages/l/sdl/sdl-net/Makefile
new file mode 100644
index 000000000..1b5097284
--- /dev/null
+++ b/sources/packages/l/sdl/sdl-net/Makefile
@@ -0,0 +1,47 @@
+
+COMPONENT_TARGETS = $(HARDWARE_NOARCH)
+
+
+include ../../../../../build-system/constants.mk
+
+
+url         = $(DOWNLOAD_SERVER)/sources/packages/l/sdl/sdl-net
+
+versions    = 1.2.8
+pkgname     = SDL_net
+suffix      = tar.gz
+
+tarballs    = $(addsuffix .$(suffix), $(addprefix $(pkgname)-, $(versions)))
+sha1s       = $(addsuffix .sha1sum, $(tarballs))
+
+
+BUILD_TARGETS = $(tarballs) $(sha1s)
+
+
+include ../../../../../build-system/core.mk
+
+
+.PHONY: download_clean
+
+
+$(tarballs):
+	@echo -e "\n======= Downloading source tarballs =======" ; \
+	 for tarball in $(tarballs) ; do \
+	   echo "$(url)/$$tarball" | xargs -n 1 -P 100 wget $(WGET_OPTIONS) -i & \
+	 done ; wait
+
+$(sha1s): $(tarballs)
+	@for sha in $@ ; do \
+	   echo -e "\n======= Downloading '$$sha' signature =======\n" ; \
+	   echo "$(url)/$$sha" | xargs -n 1 -P 100 wget $(WGET_OPTIONS) -i & wait %1 ; \
+	   touch $$sha ; \
+	   echo -e "\n======= Check the '$$sha' sha1sum =======\n" ; \
+	   sha1sum --check $$sha ; ret="$$?" ; \
+	   if [ "$$ret" == "1" ]; then \
+	     echo -e "\n======= ERROR: Bad '$$sha' sha1sum =======\n" ; \
+	     exit 1 ; \
+	   fi ; \
+	 done
+
+download_clean:
+	@rm -f $(tarballs) $(sha1s)
diff --git a/sources/packages/l/sdl/sdl-ttf/Makefile b/sources/packages/l/sdl/sdl-ttf/Makefile
new file mode 100644
index 000000000..17f5d642b
--- /dev/null
+++ b/sources/packages/l/sdl/sdl-ttf/Makefile
@@ -0,0 +1,56 @@
+
+COMPONENT_TARGETS = $(HARDWARE_NOARCH)
+
+
+include ../../../../../build-system/constants.mk
+
+
+url         = $(DOWNLOAD_SERVER)/sources/packages/l/sdl/sdl-ttf
+
+versions    = 2.0.11
+pkgname     = SDL_ttf
+suffix      = tar.gz
+
+tarballs    = $(addsuffix .$(suffix), $(addprefix $(pkgname)-, $(versions)))
+sha1s       = $(addsuffix .sha1sum, $(tarballs))
+
+patches     = $(CURDIR)/patches/SDL_ttf-2.0.11-shaded-text.patch
+
+.NOTPARALLEL: $(patches)
+
+
+BUILD_TARGETS = $(tarballs) $(sha1s) $(patches)
+
+
+include ../../../../../build-system/core.mk
+
+
+.PHONY: download_clean
+
+
+$(tarballs):
+	@echo -e "\n======= Downloading source tarballs =======" ; \
+	 for tarball in $(tarballs) ; do \
+	   echo "$(url)/$$tarball" | xargs -n 1 -P 100 wget $(WGET_OPTIONS) -i & \
+	 done ; wait
+
+$(sha1s): $(tarballs)
+	@for sha in $@ ; do \
+	   echo -e "\n======= Downloading '$$sha' signature =======\n" ; \
+	   echo "$(url)/$$sha" | xargs -n 1 -P 100 wget $(WGET_OPTIONS) -i & wait %1 ; \
+	   touch $$sha ; \
+	   echo -e "\n======= Check the '$$sha' sha1sum =======\n" ; \
+	   sha1sum --check $$sha ; ret="$$?" ; \
+	   if [ "$$ret" == "1" ]; then \
+	     echo -e "\n======= ERROR: Bad '$$sha' sha1sum =======\n" ; \
+	     exit 1 ; \
+	   fi ; \
+	 done
+
+$(patches): $(sha1s)
+	@echo -e "\n======= Create Patches =======\n" ; \
+	 ( cd create-2.0.11-shaded-text-patch ; ./create.patch.sh ) ; \
+	 echo -e "\n"
+
+download_clean:
+	@rm -f $(tarballs) $(sha1s) $(patches)
diff --git a/sources/packages/l/sdl/sdl-ttf/create-2.0.11-shaded-text-patch/SDL_ttf-2.0.11-new/SDL_ttf.c b/sources/packages/l/sdl/sdl-ttf/create-2.0.11-shaded-text-patch/SDL_ttf-2.0.11-new/SDL_ttf.c
new file mode 100644
index 000000000..668cdbd96
--- /dev/null
+++ b/sources/packages/l/sdl/sdl-ttf/create-2.0.11-shaded-text-patch/SDL_ttf-2.0.11-new/SDL_ttf.c
@@ -0,0 +1,2092 @@
+/*
+  SDL_ttf:  A companion library to SDL for working with TrueType (tm) fonts
+  Copyright (C) 2001-2012 Sam Lantinga <slouken@libsdl.org>
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+*/
+
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#ifdef HAVE_ALLOCA_H
+#include <alloca.h>
+#endif
+
+#ifdef HAVE_ALLOCA
+#define ALLOCA(n) ((void*)alloca(n))
+#define FREEA(p)
+#else
+#define ALLOCA(n) malloc(n)
+#define FREEA(p) free(p)
+#endif
+
+#include <ft2build.h>
+#include FT_FREETYPE_H
+#include FT_OUTLINE_H
+#include FT_STROKER_H
+#include FT_GLYPH_H
+#include FT_TRUETYPE_IDS_H
+
+#include "SDL.h"
+#include "SDL_endian.h"
+#include "SDL_ttf.h"
+
+/* FIXME: Right now we assume the gray-scale renderer Freetype is using
+   supports 256 shades of gray, but we should instead key off of num_grays
+   in the result FT_Bitmap after the FT_Render_Glyph() call. */
+#define NUM_GRAYS       256
+
+/* Handy routines for converting from fixed point */
+#define FT_FLOOR(X)	((X & -64) / 64)
+#define FT_CEIL(X)	(((X + 63) & -64) / 64)
+
+#define CACHED_METRICS	0x10
+#define CACHED_BITMAP	0x01
+#define CACHED_PIXMAP	0x02
+
+/* Cached glyph information */
+typedef struct cached_glyph {
+	int stored;
+	FT_UInt index;
+	FT_Bitmap bitmap;
+	FT_Bitmap pixmap;
+	int minx;
+	int maxx;
+	int miny;
+	int maxy;
+	int yoffset;
+	int advance;
+	Uint16 cached;
+} c_glyph;
+
+/* The structure used to hold internal font information */
+struct _TTF_Font {
+	/* Freetype2 maintains all sorts of useful info itself */
+	FT_Face face;
+
+	/* We'll cache these ourselves */
+	int height;
+	int ascent;
+	int descent;
+	int lineskip;
+
+	/* The font style */
+	int face_style;
+	int style;
+	int outline;
+
+	/* Whether kerning is desired */
+	int kerning;
+
+	/* Extra width in glyph bounds for text styles */
+	int glyph_overhang;
+	float glyph_italics;
+
+	/* Information in the font for underlining */
+	int underline_offset;
+	int underline_height;
+
+	/* Cache for style-transformed glyphs */
+	c_glyph *current;
+	c_glyph cache[257]; /* 257 is a prime */
+
+	/* We are responsible for closing the font stream */
+	SDL_RWops *src;
+	int freesrc;
+	FT_Open_Args args;
+
+	/* For non-scalable formats, we must remember which font index size */
+	int font_size_family;
+	
+	/* really just flags passed into FT_Load_Glyph */
+	int hinting;
+};
+
+/* Handle a style only if the font does not already handle it */
+#define TTF_HANDLE_STYLE_BOLD(font) (((font)->style & TTF_STYLE_BOLD) && \
+                                    !((font)->face_style & TTF_STYLE_BOLD))
+#define TTF_HANDLE_STYLE_ITALIC(font) (((font)->style & TTF_STYLE_ITALIC) && \
+                                      !((font)->face_style & TTF_STYLE_ITALIC))
+#define TTF_HANDLE_STYLE_UNDERLINE(font) ((font)->style & TTF_STYLE_UNDERLINE)
+#define TTF_HANDLE_STYLE_STRIKETHROUGH(font) ((font)->style & TTF_STYLE_STRIKETHROUGH)
+
+/* Font styles that does not impact glyph drawing */
+#define TTF_STYLE_NO_GLYPH_CHANGE	(TTF_STYLE_UNDERLINE | TTF_STYLE_STRIKETHROUGH)
+
+/* The FreeType font engine/library */
+static FT_Library library;
+static int TTF_initialized = 0;
+static int TTF_byteswapped = 0;
+
+
+/* Gets the top row of the underline. The outline
+   is taken into account.
+*/
+static __inline__ int TTF_underline_top_row(TTF_Font *font)
+{
+	/* With outline, the underline_offset is underline_offset+outline. */
+	/* So, we don't have to remove the top part of the outline height. */
+	return font->ascent - font->underline_offset - 1;
+}
+
+/* Gets the top row of the underline. for a given glyph. The outline
+   is taken into account.
+   Need to update row according to height difference between font and glyph:
+   font_value - font->ascent + glyph->maxy
+*/
+static __inline__ int TTF_Glyph_underline_top_row(TTF_Font *font, c_glyph *glyph)
+{
+	return glyph->maxy - font->underline_offset - 1;
+}
+
+/* Gets the bottom row of the underline. The outline
+   is taken into account.
+*/
+static __inline__ int TTF_underline_bottom_row(TTF_Font *font)
+{
+	int row = TTF_underline_top_row(font) + font->underline_height;
+	if( font->outline  > 0 ) {
+		/* Add underline_offset outline offset and */
+		/* the bottom part of the outline. */
+		row += font->outline * 2;
+	}
+	return row;
+}
+
+/* Gets the bottom row of the underline. for a given glyph. The outline
+   is taken into account.
+   Need to update row according to height difference between font and glyph:
+   font_value - font->ascent + glyph->maxy
+*/
+static __inline__ int TTF_Glyph_underline_bottom_row(TTF_Font *font, c_glyph *glyph)
+{
+	return TTF_underline_bottom_row(font) - font->ascent + glyph->maxy;
+}
+
+/* Gets the top row of the strikethrough. The outline
+   is taken into account.
+*/
+static __inline__ int TTF_strikethrough_top_row(TTF_Font *font)
+{
+	/* With outline, the first text row is 'outline'. */
+	/* So, we don't have to remove the top part of the outline height. */
+	return font->height / 2;
+}
+
+/* Gets the top row of the strikethrough for a given glyph. The outline
+   is taken into account.
+   Need to update row according to height difference between font and glyph:
+   font_value - font->ascent + glyph->maxy
+*/
+static __inline__ int TTF_Glyph_strikethrough_top_row(TTF_Font *font, c_glyph *glyph)
+{
+	return TTF_strikethrough_top_row(font) - font->ascent + glyph->maxy;
+}
+
+static void TTF_initLineMectrics(const TTF_Font *font, const SDL_Surface *textbuf, const int row, Uint8 **pdst, int *pheight)
+{
+	Uint8 *dst;
+	int height;
+
+	dst = (Uint8 *)textbuf->pixels;
+	if( row > 0 ) {
+		dst += row * textbuf->pitch;
+	}
+
+	height = font->underline_height;
+	/* Take outline into account */
+	if( font->outline > 0 ) {
+		height += font->outline * 2;
+	}
+	*pdst = dst;
+	*pheight = height;
+}
+
+/* Draw a solid line of underline_height (+ optional outline)
+   at the given row. The row value must take the
+   outline into account.
+*/
+static void TTF_drawLine_Solid(const TTF_Font *font, const SDL_Surface *textbuf, const int row)
+{
+	int line;
+	Uint8 *dst_check = (Uint8*)textbuf->pixels + textbuf->pitch * textbuf->h;
+	Uint8 *dst;
+	int height;
+
+	TTF_initLineMectrics(font, textbuf, row, &dst, &height);
+
+	/* Draw line */
+	for ( line=height; line>0 && dst < dst_check; --line ) {
+		/* 1 because 0 is the bg color */
+		memset( dst, 1, textbuf->w );
+		dst += textbuf->pitch;
+	}
+}
+
+/* Draw a shaded line of underline_height (+ optional outline)
+   at the given row. The row value must take the
+   outline into account.
+*/
+static void TTF_drawLine_Shaded(const TTF_Font *font, const SDL_Surface *textbuf, const int row)
+{
+	int line;
+	Uint8 *dst_check = (Uint8*)textbuf->pixels + textbuf->pitch * textbuf->h;
+	Uint8 *dst;
+	int height;
+
+	TTF_initLineMectrics(font, textbuf, row, &dst, &height);
+
+	/* Draw line */
+	for ( line=height; line>0 && dst < dst_check; --line ) {
+		memset( dst, NUM_GRAYS - 1, textbuf->w );
+		dst += textbuf->pitch;
+	}
+}
+
+/* Draw a blended line of underline_height (+ optional outline)
+   at the given row. The row value must take the
+   outline into account.
+*/
+static void TTF_drawLine_Blended(const TTF_Font *font, const SDL_Surface *textbuf, const int row, const Uint32 color)
+{
+	int line;
+	Uint32 *dst_check = (Uint32*)textbuf->pixels + textbuf->pitch/4 * textbuf->h;
+	Uint8 *dst8; /* destination, byte version */
+	Uint32 *dst;
+	int height;
+	int col;
+	Uint32 pixel = color | 0xFF000000; /* Amask */
+
+	TTF_initLineMectrics(font, textbuf, row, &dst8, &height);
+	dst = (Uint32 *) dst8;
+
+	/* Draw line */
+	for ( line=height; line>0 && dst < dst_check; --line ) {
+		for ( col=0; col < textbuf->w; ++col ) {
+			dst[col] = pixel;
+		}
+		dst += textbuf->pitch/4;
+	}
+}
+
+/* rcg06192001 get linked library's version. */
+const SDL_version *TTF_Linked_Version(void)
+{
+	static SDL_version linked_version;
+	SDL_TTF_VERSION(&linked_version);
+	return(&linked_version);
+}
+
+/* This function tells the library whether UNICODE text is generally
+   byteswapped.  A UNICODE BOM character at the beginning of a string
+   will override this setting for that string.
+ */
+void TTF_ByteSwappedUNICODE(int swapped)
+{
+	TTF_byteswapped = swapped;
+}
+
+static void TTF_SetFTError(const char *msg, FT_Error error)
+{
+#ifdef USE_FREETYPE_ERRORS
+#undef FTERRORS_H
+#define FT_ERRORDEF( e, v, s )  { e, s },
+	static const struct
+	{
+	  int          err_code;
+	  const char*  err_msg;
+	} ft_errors[] = {
+#include <freetype/fterrors.h>
+	};
+	int i;
+	const char *err_msg;
+	char buffer[1024];
+
+	err_msg = NULL;
+	for ( i=0; i<((sizeof ft_errors)/(sizeof ft_errors[0])); ++i ) {
+		if ( error == ft_errors[i].err_code ) {
+			err_msg = ft_errors[i].err_msg;
+			break;
+		}
+	}
+	if ( ! err_msg ) {
+		err_msg = "unknown FreeType error";
+	}
+	sprintf(buffer, "%s: %s", msg, err_msg);
+	TTF_SetError(buffer);
+#else
+	TTF_SetError(msg);
+#endif /* USE_FREETYPE_ERRORS */
+}
+
+int TTF_Init( void )
+{
+	int status = 0;
+
+	if ( ! TTF_initialized ) {
+		FT_Error error = FT_Init_FreeType( &library );
+		if ( error ) {
+			TTF_SetFTError("Couldn't init FreeType engine", error);
+			status = -1;
+		}
+	}
+	if ( status == 0 ) {
+		++TTF_initialized;
+	}
+	return status;
+}
+
+static unsigned long RWread(
+	FT_Stream stream,
+	unsigned long offset,
+	unsigned char* buffer,
+	unsigned long count
+)
+{
+	SDL_RWops *src;
+
+	src = (SDL_RWops *)stream->descriptor.pointer;
+	SDL_RWseek( src, (int)offset, RW_SEEK_SET );
+	if ( count == 0 ) {
+		return 0;
+	}
+	return SDL_RWread( src, buffer, 1, (int)count );
+}
+
+TTF_Font* TTF_OpenFontIndexRW( SDL_RWops *src, int freesrc, int ptsize, long index )
+{
+	TTF_Font* font;
+	FT_Error error;
+	FT_Face face;
+	FT_Fixed scale;
+	FT_Stream stream;
+	FT_CharMap found;
+	int position, i;
+
+	if ( ! TTF_initialized ) {
+		TTF_SetError( "Library not initialized" );
+		return NULL;
+	}
+
+	/* Check to make sure we can seek in this stream */
+	position = SDL_RWtell(src);
+	if ( position < 0 ) {
+		TTF_SetError( "Can't seek in stream" );
+		return NULL;
+	}
+
+	font = (TTF_Font*) malloc(sizeof *font);
+	if ( font == NULL ) {
+		TTF_SetError( "Out of memory" );
+		return NULL;
+	}
+	memset(font, 0, sizeof(*font));
+
+	font->src = src;
+	font->freesrc = freesrc;
+
+	stream = (FT_Stream)malloc(sizeof(*stream));
+	if ( stream == NULL ) {
+		TTF_SetError( "Out of memory" );
+		TTF_CloseFont( font );
+		return NULL;
+	}
+	memset(stream, 0, sizeof(*stream));
+
+	stream->read = RWread;
+	stream->descriptor.pointer = src;
+	stream->pos = (unsigned long)position;
+	SDL_RWseek(src, 0, RW_SEEK_END);
+	stream->size = (unsigned long)(SDL_RWtell(src) - position);
+	SDL_RWseek(src, position, RW_SEEK_SET);
+
+	font->args.flags = FT_OPEN_STREAM;
+	font->args.stream = stream;
+
+	error = FT_Open_Face( library, &font->args, index, &font->face );
+	if( error ) {
+		TTF_SetFTError( "Couldn't load font file", error );
+		TTF_CloseFont( font );
+		return NULL;
+	}
+	face = font->face;
+
+	/* Set charmap for loaded font */
+	found = 0;
+	for (i = 0; i < face->num_charmaps; i++) {
+		FT_CharMap charmap = face->charmaps[i];
+		if ((charmap->platform_id == 3 && charmap->encoding_id == 1) /* Windows Unicode */
+		 || (charmap->platform_id == 3 && charmap->encoding_id == 0) /* Windows Symbol */
+		 || (charmap->platform_id == 2 && charmap->encoding_id == 1) /* ISO Unicode */
+		 || (charmap->platform_id == 0)) { /* Apple Unicode */
+			found = charmap;
+			break;
+		}
+	}
+	if ( found ) {
+		/* If this fails, continue using the default charmap */
+		FT_Set_Charmap(face, found);
+	}
+
+	/* Make sure that our font face is scalable (global metrics) */
+	if ( FT_IS_SCALABLE(face) ) {
+
+	  	/* Set the character size and use default DPI (72) */
+	  	error = FT_Set_Char_Size( font->face, 0, ptsize * 64, 0, 0 );
+			if( error ) {
+	    	TTF_SetFTError( "Couldn't set font size", error );
+	    	TTF_CloseFont( font );
+	    	return NULL;
+	  }
+
+	  /* Get the scalable font metrics for this font */
+	  scale = face->size->metrics.y_scale;
+	  font->ascent  = FT_CEIL(FT_MulFix(face->ascender, scale));
+	  font->descent = FT_CEIL(FT_MulFix(face->descender, scale));
+	  font->height  = font->ascent - font->descent + /* baseline */ 1;
+	  font->lineskip = FT_CEIL(FT_MulFix(face->height, scale));
+	  font->underline_offset = FT_FLOOR(FT_MulFix(face->underline_position, scale));
+	  font->underline_height = FT_FLOOR(FT_MulFix(face->underline_thickness, scale));
+
+	} else {
+		/* Non-scalable font case.  ptsize determines which family
+		 * or series of fonts to grab from the non-scalable format.
+		 * It is not the point size of the font.
+		 * */
+		if ( ptsize >= font->face->num_fixed_sizes )
+			ptsize = font->face->num_fixed_sizes - 1;
+		font->font_size_family = ptsize;
+		error = FT_Set_Pixel_Sizes( face,
+				face->available_sizes[ptsize].height,
+				face->available_sizes[ptsize].width );
+	  	/* With non-scalale fonts, Freetype2 likes to fill many of the
+		 * font metrics with the value of 0.  The size of the
+		 * non-scalable fonts must be determined differently
+		 * or sometimes cannot be determined.
+		 * */
+	  	font->ascent = face->available_sizes[ptsize].height;
+	  	font->descent = 0;
+	  	font->height = face->available_sizes[ptsize].height;
+	  	font->lineskip = FT_CEIL(font->ascent);
+	  	font->underline_offset = FT_FLOOR(face->underline_position);
+	  	font->underline_height = FT_FLOOR(face->underline_thickness);
+	}
+
+	if ( font->underline_height < 1 ) {
+		font->underline_height = 1;
+	}
+
+#ifdef DEBUG_FONTS
+	printf("Font metrics:\n");
+	printf("\tascent = %d, descent = %d\n",
+		font->ascent, font->descent);
+	printf("\theight = %d, lineskip = %d\n",
+		font->height, font->lineskip);
+	printf("\tunderline_offset = %d, underline_height = %d\n",
+		font->underline_offset, font->underline_height);
+	printf("\tunderline_top_row = %d, strikethrough_top_row = %d\n",
+		TTF_underline_top_row(font), TTF_strikethrough_top_row(font));
+#endif
+
+	/* Initialize the font face style */
+	font->face_style = TTF_STYLE_NORMAL;
+	if ( font->face->style_flags & FT_STYLE_FLAG_BOLD ) {
+		font->face_style |= TTF_STYLE_BOLD;
+	}
+	if ( font->face->style_flags & FT_STYLE_FLAG_ITALIC ) {
+		font->face_style |= TTF_STYLE_ITALIC;
+	}
+	/* Set the default font style */
+	font->style = font->face_style;
+	font->outline = 0;
+	font->kerning = 1;
+	font->glyph_overhang = face->size->metrics.y_ppem / 10;
+	/* x offset = cos(((90.0-12)/360)*2*M_PI), or 12 degree angle */
+	font->glyph_italics = 0.207f;
+	font->glyph_italics *= font->height;
+
+	return font;
+}
+
+TTF_Font* TTF_OpenFontRW( SDL_RWops *src, int freesrc, int ptsize )
+{
+	return TTF_OpenFontIndexRW(src, freesrc, ptsize, 0);
+}
+
+TTF_Font* TTF_OpenFontIndex( const char *file, int ptsize, long index )
+{
+	SDL_RWops *rw = SDL_RWFromFile(file, "rb");
+	if ( rw == NULL ) {
+		TTF_SetError(SDL_GetError());
+		return NULL;
+	}
+	return TTF_OpenFontIndexRW(rw, 1, ptsize, index);
+}
+
+TTF_Font* TTF_OpenFont( const char *file, int ptsize )
+{
+	return TTF_OpenFontIndex(file, ptsize, 0);
+}
+
+static void Flush_Glyph( c_glyph* glyph )
+{
+	glyph->stored = 0;
+	glyph->index = 0;
+	if( glyph->bitmap.buffer ) {
+		free( glyph->bitmap.buffer );
+		glyph->bitmap.buffer = 0;
+	}
+	if( glyph->pixmap.buffer ) {
+		free( glyph->pixmap.buffer );
+		glyph->pixmap.buffer = 0;
+	}
+	glyph->cached = 0;
+}
+	
+static void Flush_Cache( TTF_Font* font )
+{
+	int i;
+	int size = sizeof( font->cache ) / sizeof( font->cache[0] );
+
+	for( i = 0; i < size; ++i ) {
+		if( font->cache[i].cached ) {
+			Flush_Glyph( &font->cache[i] );
+		}
+
+	}
+}
+
+static FT_Error Load_Glyph( TTF_Font* font, Uint16 ch, c_glyph* cached, int want )
+{
+	FT_Face face;
+	FT_Error error;
+	FT_GlyphSlot glyph;
+	FT_Glyph_Metrics* metrics;
+	FT_Outline* outline;
+
+	if ( !font || !font->face ) {
+		return FT_Err_Invalid_Handle;
+	}
+
+	face = font->face;
+
+	/* Load the glyph */
+	if ( ! cached->index ) {
+		cached->index = FT_Get_Char_Index( face, ch );
+	}
+	error = FT_Load_Glyph( face, cached->index, FT_LOAD_DEFAULT | font->hinting);
+	if( error ) {
+		return error;
+	}
+
+	/* Get our glyph shortcuts */
+	glyph = face->glyph;
+	metrics = &glyph->metrics;
+	outline = &glyph->outline;
+
+	/* Get the glyph metrics if desired */
+	if ( (want & CACHED_METRICS) && !(cached->stored & CACHED_METRICS) ) {
+		if ( FT_IS_SCALABLE( face ) ) {
+			/* Get the bounding box */
+			cached->minx = FT_FLOOR(metrics->horiBearingX);
+			cached->maxx = cached->minx + FT_CEIL(metrics->width);
+			cached->maxy = FT_FLOOR(metrics->horiBearingY);
+			cached->miny = cached->maxy - FT_CEIL(metrics->height);
+			cached->yoffset = font->ascent - cached->maxy;
+			cached->advance = FT_CEIL(metrics->horiAdvance);
+		} else {
+			/* Get the bounding box for non-scalable format.
+			 * Again, freetype2 fills in many of the font metrics
+			 * with the value of 0, so some of the values we
+			 * need must be calculated differently with certain
+			 * assumptions about non-scalable formats.
+			 * */
+			cached->minx = FT_FLOOR(metrics->horiBearingX);
+			cached->maxx = cached->minx + FT_CEIL(metrics->horiAdvance);
+			cached->maxy = FT_FLOOR(metrics->horiBearingY);
+			cached->miny = cached->maxy - FT_CEIL(face->available_sizes[font->font_size_family].height);
+			cached->yoffset = 0;
+			cached->advance = FT_CEIL(metrics->horiAdvance);
+		}
+		
+		/* Adjust for bold and italic text */
+		if( TTF_HANDLE_STYLE_BOLD(font) ) {
+			cached->maxx += font->glyph_overhang;
+		}
+		if( TTF_HANDLE_STYLE_ITALIC(font) ) {
+			cached->maxx += (int)ceil(font->glyph_italics);
+		}
+		cached->stored |= CACHED_METRICS;
+	}
+
+	if ( ((want & CACHED_BITMAP) && !(cached->stored & CACHED_BITMAP)) ||
+	     ((want & CACHED_PIXMAP) && !(cached->stored & CACHED_PIXMAP)) ) {
+		int mono = (want & CACHED_BITMAP);
+		int i;
+		FT_Bitmap* src;
+		FT_Bitmap* dst;
+		FT_Glyph bitmap_glyph = NULL;
+
+		/* Handle the italic style */
+		if( TTF_HANDLE_STYLE_ITALIC(font) ) {
+			FT_Matrix shear;
+
+			shear.xx = 1 << 16;
+			shear.xy = (int) ( font->glyph_italics * ( 1 << 16 ) ) / font->height;
+			shear.yx = 0;
+			shear.yy = 1 << 16;
+
+			FT_Outline_Transform( outline, &shear );
+		}
+
+		/* Render as outline */
+		if( (font->outline > 0) && glyph->format != FT_GLYPH_FORMAT_BITMAP ) {
+			FT_Stroker stroker;
+			FT_Get_Glyph( glyph, &bitmap_glyph );
+			error = FT_Stroker_New( library, &stroker );
+			if( error ) {
+				return error;
+			}
+			FT_Stroker_Set( stroker, font->outline * 64, FT_STROKER_LINECAP_ROUND, FT_STROKER_LINEJOIN_ROUND, 0 ); 
+			FT_Glyph_Stroke( &bitmap_glyph, stroker, 1 /* delete the original glyph */ );
+			FT_Stroker_Done( stroker );
+			/* Render the glyph */
+			error = FT_Glyph_To_Bitmap( &bitmap_glyph, mono ? ft_render_mode_mono : ft_render_mode_normal, 0, 1 );
+			if( error ) {
+				FT_Done_Glyph( bitmap_glyph );
+				return error;
+			}
+			src = &((FT_BitmapGlyph)bitmap_glyph)->bitmap;
+		} else {
+			/* Render the glyph */
+			error = FT_Render_Glyph( glyph, mono ? ft_render_mode_mono : ft_render_mode_normal );
+			if( error ) {
+				return error;
+			}
+			src = &glyph->bitmap;
+		}
+		/* Copy over information to cache */
+		if ( mono ) {
+			dst = &cached->bitmap;
+		} else {
+			dst = &cached->pixmap;
+		}
+		memcpy( dst, src, sizeof( *dst ) );
+
+		/* FT_Render_Glyph() and .fon fonts always generate a
+		 * two-color (black and white) glyphslot surface, even
+		 * when rendered in ft_render_mode_normal. */
+		/* FT_IS_SCALABLE() means that the font is in outline format,
+		 * but does not imply that outline is rendered as 8-bit
+		 * grayscale, because embedded bitmap/graymap is preferred
+		 * (see FT_LOAD_DEFAULT section of FreeType2 API Reference).
+		 * FT_Render_Glyph() canreturn two-color bitmap or 4/16/256-
+		 * color graymap according to the format of embedded bitmap/
+		 * graymap. */
+		if ( src->pixel_mode == FT_PIXEL_MODE_MONO ) {
+			dst->pitch *= 8;
+		} else if ( src->pixel_mode == FT_PIXEL_MODE_GRAY2 ) {
+			dst->pitch *= 4;
+		} else if ( src->pixel_mode == FT_PIXEL_MODE_GRAY4 ) {
+			dst->pitch *= 2;
+		}
+
+		/* Adjust for bold and italic text */
+		if( TTF_HANDLE_STYLE_BOLD(font) ) {
+			int bump = font->glyph_overhang;
+			dst->pitch += bump;
+			dst->width += bump;
+		}
+		if( TTF_HANDLE_STYLE_ITALIC(font) ) {
+			int bump = (int)ceil(font->glyph_italics);
+			dst->pitch += bump;
+			dst->width += bump;
+		}
+
+		if (dst->rows != 0) {
+			dst->buffer = (unsigned char *)malloc( dst->pitch * dst->rows );
+			if( !dst->buffer ) {
+				return FT_Err_Out_Of_Memory;
+			}
+			memset( dst->buffer, 0, dst->pitch * dst->rows );
+
+			for( i = 0; i < src->rows; i++ ) {
+				int soffset = i * src->pitch;
+				int doffset = i * dst->pitch;
+				if ( mono ) {
+					unsigned char *srcp = src->buffer + soffset;
+					unsigned char *dstp = dst->buffer + doffset;
+					int j;
+					if ( src->pixel_mode == FT_PIXEL_MODE_MONO ) {
+						for ( j = 0; j < src->width; j += 8 ) {
+							unsigned char c = *srcp++;
+							*dstp++ = (c&0x80) >> 7;
+							c <<= 1;
+							*dstp++ = (c&0x80) >> 7;
+							c <<= 1;
+							*dstp++ = (c&0x80) >> 7;
+							c <<= 1;
+							*dstp++ = (c&0x80) >> 7;
+							c <<= 1;
+							*dstp++ = (c&0x80) >> 7;
+							c <<= 1;
+							*dstp++ = (c&0x80) >> 7;
+							c <<= 1;
+							*dstp++ = (c&0x80) >> 7;
+							c <<= 1;
+							*dstp++ = (c&0x80) >> 7;
+						}
+					}  else if ( src->pixel_mode == FT_PIXEL_MODE_GRAY2 ) {
+						for ( j = 0; j < src->width; j += 4 ) {
+							unsigned char c = *srcp++;
+							*dstp++ = (((c&0xA0) >> 6) >= 0x2) ? 1 : 0;
+							c <<= 2;
+							*dstp++ = (((c&0xA0) >> 6) >= 0x2) ? 1 : 0;
+							c <<= 2;
+							*dstp++ = (((c&0xA0) >> 6) >= 0x2) ? 1 : 0;
+							c <<= 2;
+							*dstp++ = (((c&0xA0) >> 6) >= 0x2) ? 1 : 0;
+						}
+					} else if ( src->pixel_mode == FT_PIXEL_MODE_GRAY4 ) {
+						for ( j = 0; j < src->width; j += 2 ) {
+							unsigned char c = *srcp++;
+							*dstp++ = (((c&0xF0) >> 4) >= 0x8) ? 1 : 0;
+							c <<= 4;
+							*dstp++ = (((c&0xF0) >> 4) >= 0x8) ? 1 : 0;
+						}
+					} else {
+						for ( j = 0; j < src->width; j++ ) {
+							unsigned char c = *srcp++;
+							*dstp++ = (c >= 0x80) ? 1 : 0;
+						}
+					}
+				} else if ( src->pixel_mode == FT_PIXEL_MODE_MONO ) {
+					/* This special case wouldn't
+					 * be here if the FT_Render_Glyph()
+					 * function wasn't buggy when it tried
+					 * to render a .fon font with 256
+					 * shades of gray.  Instead, it
+					 * returns a black and white surface
+					 * and we have to translate it back
+					 * to a 256 gray shaded surface. 
+					 * */
+					unsigned char *srcp = src->buffer + soffset;
+					unsigned char *dstp = dst->buffer + doffset;
+					unsigned char c;
+					int j, k;
+					for ( j = 0; j < src->width; j += 8) {
+						c = *srcp++;
+						for (k = 0; k < 8; ++k) {
+							if ((c&0x80) >> 7) {
+								*dstp++ = NUM_GRAYS - 1;
+							} else {
+								*dstp++ = 0x00;
+							}
+							c <<= 1;
+						}
+					}
+				} else if ( src->pixel_mode == FT_PIXEL_MODE_GRAY2 ) {
+					unsigned char *srcp = src->buffer + soffset;
+					unsigned char *dstp = dst->buffer + doffset;
+					unsigned char c;
+					int j, k;
+					for ( j = 0; j < src->width; j += 4 ) {
+						c = *srcp++;
+						for ( k = 0; k < 4; ++k ) {
+							if ((c&0xA0) >> 6) {
+								*dstp++ = NUM_GRAYS * ((c&0xA0) >> 6) / 3 - 1;
+							} else {
+								*dstp++ = 0x00;
+							}
+							c <<= 2;
+						}
+					}
+				} else if ( src->pixel_mode == FT_PIXEL_MODE_GRAY4 ) {
+					unsigned char *srcp = src->buffer + soffset;
+					unsigned char *dstp = dst->buffer + doffset;
+					unsigned char c;
+					int j, k;
+					for ( j = 0; j < src->width; j += 2 ) {
+						c = *srcp++;
+						for ( k = 0; k < 2; ++k ) {
+							if ((c&0xF0) >> 4) {
+							    *dstp++ = NUM_GRAYS * ((c&0xF0) >> 4) / 15 - 1;
+							} else {
+								*dstp++ = 0x00;
+							}
+							c <<= 4;
+						}
+					}
+				} else {
+					memcpy(dst->buffer+doffset,
+					       src->buffer+soffset, src->pitch);
+				}
+			}
+		}
+
+		/* Handle the bold style */
+		if ( TTF_HANDLE_STYLE_BOLD(font) ) {
+			int row;
+			int col;
+			int offset;
+			int pixel;
+			Uint8* pixmap;
+
+			/* The pixmap is a little hard, we have to add and clamp */
+			for( row = dst->rows - 1; row >= 0; --row ) {
+				pixmap = (Uint8*) dst->buffer + row * dst->pitch;
+				for( offset=1; offset <= font->glyph_overhang; ++offset ) {
+					for( col = dst->width - 1; col > 0; --col ) {
+						if( mono ) {
+							pixmap[col] |= pixmap[col-1];
+						} else {
+							pixel = (pixmap[col] + pixmap[col-1]);
+							if( pixel > NUM_GRAYS - 1 ) {
+								pixel = NUM_GRAYS - 1;
+							}
+							pixmap[col] = (Uint8) pixel;
+						}
+					}
+				}
+			}
+		}
+
+		/* Mark that we rendered this format */
+		if ( mono ) {
+			cached->stored |= CACHED_BITMAP;
+		} else {
+			cached->stored |= CACHED_PIXMAP;
+		}
+
+		/* Free outlined glyph */
+		if( bitmap_glyph ) {
+			FT_Done_Glyph( bitmap_glyph );
+		}
+	}
+
+	/* We're done, mark this glyph cached */
+	cached->cached = ch;
+
+	return 0;
+}
+
+static FT_Error Find_Glyph( TTF_Font* font, Uint16 ch, int want )
+{
+	int retval = 0;
+	int hsize = sizeof( font->cache ) / sizeof( font->cache[0] );
+
+	int h = ch % hsize;
+	font->current = &font->cache[h];
+
+	if (font->current->cached != ch)
+		Flush_Glyph( font->current );
+
+	if ( (font->current->stored & want) != want ) {
+		retval = Load_Glyph( font, ch, font->current, want );
+	}
+	return retval;
+}
+
+void TTF_CloseFont( TTF_Font* font )
+{
+	if ( font ) {
+		Flush_Cache( font );
+		if ( font->face ) {
+			FT_Done_Face( font->face );
+		}
+		if ( font->args.stream ) {
+			free( font->args.stream );
+		}
+		if ( font->freesrc ) {
+			SDL_RWclose( font->src );
+		}
+		free( font );
+	}
+}
+
+static Uint16 *LATIN1_to_UNICODE(Uint16 *unicode, const char *text, int len)
+{
+	int i;
+
+	for ( i=0; i < len; ++i ) {
+		unicode[i] = ((const unsigned char *)text)[i];
+	}
+	unicode[i] = 0;
+
+	return unicode;
+}
+
+static Uint16 *UTF8_to_UNICODE(Uint16 *unicode, const char *utf8, int len)
+{
+	int i, j;
+	Uint16 ch;
+
+	for ( i=0, j=0; i < len; ++i, ++j ) {
+		ch = ((const unsigned char *)utf8)[i];
+		if ( ch >= 0xF0 ) {
+			ch  =  (Uint16)(utf8[i]&0x07) << 18;
+			ch |=  (Uint16)(utf8[++i]&0x3F) << 12;
+			ch |=  (Uint16)(utf8[++i]&0x3F) << 6;
+			ch |=  (Uint16)(utf8[++i]&0x3F);
+		} else
+		if ( ch >= 0xE0 ) {
+			ch  =  (Uint16)(utf8[i]&0x0F) << 12;
+			ch |=  (Uint16)(utf8[++i]&0x3F) << 6;
+			ch |=  (Uint16)(utf8[++i]&0x3F);
+		} else
+		if ( ch >= 0xC0 ) {
+			ch  =  (Uint16)(utf8[i]&0x1F) << 6;
+			ch |=  (Uint16)(utf8[++i]&0x3F);
+		}
+		unicode[j] = ch;
+	}
+	unicode[j] = 0;
+
+	return unicode;
+}
+
+int TTF_FontHeight(const TTF_Font *font)
+{
+	return(font->height);
+}
+
+int TTF_FontAscent(const TTF_Font *font)
+{
+	return(font->ascent);
+}
+
+int TTF_FontDescent(const TTF_Font *font)
+{
+	return(font->descent);
+}
+
+int TTF_FontLineSkip(const TTF_Font *font)
+{
+	return(font->lineskip);
+}
+
+int TTF_GetFontKerning(const TTF_Font *font)
+{
+	return(font->kerning);
+}
+
+void TTF_SetFontKerning(TTF_Font *font, int allowed)
+{
+	font->kerning = allowed;
+}
+
+long TTF_FontFaces(const TTF_Font *font)
+{
+	return(font->face->num_faces);
+}
+
+int TTF_FontFaceIsFixedWidth(const TTF_Font *font)
+{
+	return(FT_IS_FIXED_WIDTH(font->face));
+}
+
+char *TTF_FontFaceFamilyName(const TTF_Font *font)
+{
+	return(font->face->family_name);
+}
+
+char *TTF_FontFaceStyleName(const TTF_Font *font)
+{
+	return(font->face->style_name);
+}
+
+int TTF_GlyphIsProvided(const TTF_Font *font, Uint16 ch)
+{
+  return(FT_Get_Char_Index(font->face, ch));
+}
+
+int TTF_GlyphMetrics(TTF_Font *font, Uint16 ch,
+                     int* minx, int* maxx, int* miny, int* maxy, int* advance)
+{
+	FT_Error error;
+
+	error = Find_Glyph(font, ch, CACHED_METRICS);
+	if ( error ) {
+		TTF_SetFTError("Couldn't find glyph", error);
+		return -1;
+	}
+
+	if ( minx ) {
+		*minx = font->current->minx;
+	}
+	if ( maxx ) {
+		*maxx = font->current->maxx;
+		if( TTF_HANDLE_STYLE_BOLD(font) ) {
+			*maxx += font->glyph_overhang;
+		}
+	}
+	if ( miny ) {
+		*miny = font->current->miny;
+	}
+	if ( maxy ) {
+		*maxy = font->current->maxy;
+	}
+	if ( advance ) {
+		*advance = font->current->advance;
+		if( TTF_HANDLE_STYLE_BOLD(font) ) {
+			*advance += font->glyph_overhang;
+		}
+	}
+	return 0;
+}
+
+int TTF_SizeText(TTF_Font *font, const char *text, int *w, int *h)
+{
+	Uint16 *unicode_text;
+	int unicode_len;
+	int status;
+
+	/* Copy the Latin-1 text to a UNICODE text buffer */
+	unicode_len = strlen(text);
+	unicode_text = (Uint16 *)ALLOCA((1+unicode_len+1)*(sizeof *unicode_text));
+	if ( unicode_text == NULL ) {
+		TTF_SetError("Out of memory");
+		return -1;
+	}
+	*unicode_text = UNICODE_BOM_NATIVE;
+	LATIN1_to_UNICODE(unicode_text+1, text, unicode_len);
+
+	/* Render the new text */
+	status = TTF_SizeUNICODE(font, unicode_text, w, h);
+
+	/* Free the text buffer and return */
+	FREEA(unicode_text);
+	return status;
+}
+
+int TTF_SizeUTF8(TTF_Font *font, const char *text, int *w, int *h)
+{
+	Uint16 *unicode_text;
+	int unicode_len;
+	int status;
+
+	/* Copy the UTF-8 text to a UNICODE text buffer */
+	unicode_len = strlen(text);
+	unicode_text = (Uint16 *)ALLOCA((1+unicode_len+1)*(sizeof *unicode_text));
+	if ( unicode_text == NULL ) {
+		TTF_SetError("Out of memory");
+		return -1;
+	}
+	*unicode_text = UNICODE_BOM_NATIVE;
+	UTF8_to_UNICODE(unicode_text+1, text, unicode_len);
+
+	/* Render the new text */
+	status = TTF_SizeUNICODE(font, unicode_text, w, h);
+
+	/* Free the text buffer and return */
+	FREEA(unicode_text);
+	return status;
+}
+
+int TTF_SizeUNICODE(TTF_Font *font, const Uint16 *text, int *w, int *h)
+{
+	int status;
+	const Uint16 *ch;
+	int swapped;
+	int x, z;
+	int minx, maxx;
+	int miny, maxy;
+	c_glyph *glyph;
+	FT_Error error;
+	FT_Long use_kerning;
+	FT_UInt prev_index = 0;
+	int outline_delta = 0;
+
+	/* Initialize everything to 0 */
+	if ( ! TTF_initialized ) {
+		TTF_SetError( "Library not initialized" );
+		return -1;
+	}
+	status = 0;
+	minx = maxx = 0;
+	miny = maxy = 0;
+	swapped = TTF_byteswapped;
+
+	/* check kerning */
+	use_kerning = FT_HAS_KERNING( font->face ) && font->kerning;
+
+	/* Init outline handling */
+	if ( font->outline  > 0 ) {
+		outline_delta = font->outline * 2;
+	}
+
+	/* Load each character and sum it's bounding box */
+	x= 0;
+	for ( ch=text; *ch; ++ch ) {
+		Uint16 c = *ch;
+		if ( c == UNICODE_BOM_NATIVE ) {
+			swapped = 0;
+			if ( text == ch ) {
+				++text;
+			}
+			continue;
+		}
+		if ( c == UNICODE_BOM_SWAPPED ) {
+			swapped = 1;
+			if ( text == ch ) {
+				++text;
+			}
+			continue;
+		}
+		if ( swapped ) {
+			c = SDL_Swap16(c);
+		}
+
+		error = Find_Glyph(font, c, CACHED_METRICS);
+		if ( error ) {
+			return -1;
+		}
+		glyph = font->current;
+
+		/* handle kerning */
+		if ( use_kerning && prev_index && glyph->index ) {
+			FT_Vector delta; 
+			FT_Get_Kerning( font->face, prev_index, glyph->index, ft_kerning_default, &delta ); 
+			x += delta.x >> 6;
+		}
+
+#if 0
+		if ( (ch == text) && (glyph->minx < 0) ) {
+		/* Fixes the texture wrapping bug when the first letter
+		 * has a negative minx value or horibearing value.  The entire
+		 * bounding box must be adjusted to be bigger so the entire
+		 * letter can fit without any texture corruption or wrapping.
+		 *
+		 * Effects: First enlarges bounding box.
+		 * Second, xstart has to start ahead of its normal spot in the
+		 * negative direction of the negative minx value.
+		 * (pushes everything to the right).
+		 *
+		 * This will make the memory copy of the glyph bitmap data
+		 * work out correctly.
+		 * */
+			z -= glyph->minx;
+			
+		}
+#endif
+		
+		z = x + glyph->minx;
+		if ( minx > z ) {
+			minx = z;
+		}
+		if ( TTF_HANDLE_STYLE_BOLD(font) ) {
+			x += font->glyph_overhang;
+		}
+		if ( glyph->advance > glyph->maxx ) {
+			z = x + glyph->advance;
+		} else {
+			z = x + glyph->maxx;
+		}
+		if ( maxx < z ) {
+			maxx = z;
+		}
+		x += glyph->advance;
+
+		if ( glyph->miny < miny ) {
+			miny = glyph->miny;
+		}
+		if ( glyph->maxy > maxy ) {
+			maxy = glyph->maxy;
+		}
+		prev_index = glyph->index;
+	}
+
+	/* Fill the bounds rectangle */
+	if ( w ) {
+		/* Add outline extra width */
+		*w = (maxx - minx) + outline_delta;
+	}
+	if ( h ) {
+		/* Some fonts descend below font height (FletcherGothicFLF) */
+		/* Add outline extra height */
+		*h = (font->ascent - miny) + outline_delta;
+		if ( *h < font->height ) {
+			*h = font->height;
+		}
+		/* Update height according to the needs of the underline style */
+		if( TTF_HANDLE_STYLE_UNDERLINE(font) ) {
+			int bottom_row = TTF_underline_bottom_row(font);
+			if ( *h < bottom_row ) {
+				*h = bottom_row;
+			}
+		}
+	}
+	return status;
+}
+
+/* Convert the Latin-1 text to UNICODE and render it
+*/
+SDL_Surface *TTF_RenderText_Solid(TTF_Font *font,
+				const char *text, SDL_Color fg)
+{
+	SDL_Surface *textbuf;
+	Uint16 *unicode_text;
+	int unicode_len;
+
+	/* Copy the Latin-1 text to a UNICODE text buffer */
+	unicode_len = strlen(text);
+	unicode_text = (Uint16 *)ALLOCA((1+unicode_len+1)*(sizeof *unicode_text));
+	if ( unicode_text == NULL ) {
+		TTF_SetError("Out of memory");
+		return(NULL);
+	}
+	*unicode_text = UNICODE_BOM_NATIVE;
+	LATIN1_to_UNICODE(unicode_text+1, text, unicode_len);
+
+	/* Render the new text */
+	textbuf = TTF_RenderUNICODE_Solid(font, unicode_text, fg);
+
+	/* Free the text buffer and return */
+	FREEA(unicode_text);
+	return(textbuf);
+}
+
+/* Convert the UTF-8 text to UNICODE and render it
+*/
+SDL_Surface *TTF_RenderUTF8_Solid(TTF_Font *font,
+				const char *text, SDL_Color fg)
+{
+	SDL_Surface *textbuf;
+	Uint16 *unicode_text;
+	int unicode_len;
+
+	/* Copy the UTF-8 text to a UNICODE text buffer */
+	unicode_len = strlen(text);
+	unicode_text = (Uint16 *)ALLOCA((1+unicode_len+1)*(sizeof *unicode_text));
+	if ( unicode_text == NULL ) {
+		TTF_SetError("Out of memory");
+		return(NULL);
+	}
+	*unicode_text = UNICODE_BOM_NATIVE;
+	UTF8_to_UNICODE(unicode_text+1, text, unicode_len);
+
+	/* Render the new text */
+	textbuf = TTF_RenderUNICODE_Solid(font, unicode_text, fg);
+
+	/* Free the text buffer and return */
+	FREEA(unicode_text);
+	return(textbuf);
+}
+
+SDL_Surface *TTF_RenderUNICODE_Solid(TTF_Font *font,
+				const Uint16 *text, SDL_Color fg)
+{
+	int xstart;
+	int width;
+	int height;
+	SDL_Surface* textbuf;
+	SDL_Palette* palette;
+	const Uint16* ch;
+	Uint8* src;
+	Uint8* dst;
+	Uint8 *dst_check;
+	int swapped;
+	int row, col;
+	c_glyph *glyph;
+
+	FT_Bitmap *current;
+	FT_Error error;
+	FT_Long use_kerning;
+	FT_UInt prev_index = 0;
+
+	/* Get the dimensions of the text surface */
+	if( ( TTF_SizeUNICODE(font, text, &width, &height) < 0 ) || !width ) {
+		TTF_SetError( "Text has zero width" );
+		return NULL;
+	}
+
+	/* Create the target surface */
+	textbuf = SDL_AllocSurface(SDL_SWSURFACE, width, height, 8, 0, 0, 0, 0);
+	if( textbuf == NULL ) {
+		return NULL;
+	}
+
+	/* Adding bound checking to avoid all kinds of memory corruption errors
+	   that may occur. */
+	dst_check = (Uint8*)textbuf->pixels + textbuf->pitch * textbuf->h;
+
+	/* Fill the palette with the foreground color */
+	palette = textbuf->format->palette;
+	palette->colors[0].r = 255 - fg.r;
+	palette->colors[0].g = 255 - fg.g;
+	palette->colors[0].b = 255 - fg.b;
+	palette->colors[1].r = fg.r;
+	palette->colors[1].g = fg.g;
+	palette->colors[1].b = fg.b;
+	SDL_SetColorKey( textbuf, SDL_SRCCOLORKEY, 0 );
+
+	/* check kerning */
+	use_kerning = FT_HAS_KERNING( font->face ) && font->kerning;
+	
+	/* Load and render each character */
+	xstart = 0;
+	swapped = TTF_byteswapped;
+	for( ch=text; *ch; ++ch ) {
+		Uint16 c = *ch;
+		if ( c == UNICODE_BOM_NATIVE ) {
+			swapped = 0;
+			if ( text == ch ) {
+				++text;
+			}
+			continue;
+		}
+		if ( c == UNICODE_BOM_SWAPPED ) {
+			swapped = 1;
+			if ( text == ch ) {
+				++text;
+			}
+			continue;
+		}
+		if ( swapped ) {
+			c = SDL_Swap16(c);
+		}
+
+		error = Find_Glyph(font, c, CACHED_METRICS|CACHED_BITMAP);
+		if( error ) {
+			SDL_FreeSurface( textbuf );
+			return NULL;
+		}
+		glyph = font->current;
+		current = &glyph->bitmap;
+		/* Ensure the width of the pixmap is correct. On some cases,
+		 * freetype may report a larger pixmap than possible.*/
+		width = current->width;
+		if (font->outline <= 0 && width > glyph->maxx - glyph->minx) {
+			width = glyph->maxx - glyph->minx;
+		}
+		/* do kerning, if possible AC-Patch */
+		if ( use_kerning && prev_index && glyph->index ) {
+			FT_Vector delta; 
+			FT_Get_Kerning( font->face, prev_index, glyph->index, ft_kerning_default, &delta ); 
+			xstart += delta.x >> 6;
+		}
+		/* Compensate for wrap around bug with negative minx's */
+		if ( (ch == text) && (glyph->minx < 0) ) {
+			xstart -= glyph->minx;
+		}
+		
+		for( row = 0; row < current->rows; ++row ) {
+			/* Make sure we don't go either over, or under the
+			 * limit */
+			if ( row+glyph->yoffset < 0 ) {
+				continue;
+			}
+			if ( row+glyph->yoffset >= textbuf->h ) {
+				continue;
+			}
+			dst = (Uint8*) textbuf->pixels +
+				(row+glyph->yoffset) * textbuf->pitch +
+				xstart + glyph->minx;
+			src = current->buffer + row * current->pitch;
+
+			for ( col=width; col>0 && dst < dst_check; --col ) {
+				*dst++ |= *src++;
+			}
+		}
+
+		xstart += glyph->advance;
+		if ( TTF_HANDLE_STYLE_BOLD(font) ) {
+			xstart += font->glyph_overhang;
+		}
+		prev_index = glyph->index;
+	}
+
+	/* Handle the underline style */
+	if( TTF_HANDLE_STYLE_UNDERLINE(font) ) {
+		row = TTF_underline_top_row(font);
+		TTF_drawLine_Solid(font, textbuf, row);
+	}
+
+	/* Handle the strikethrough style */
+	if( TTF_HANDLE_STYLE_STRIKETHROUGH(font) ) {
+		row = TTF_strikethrough_top_row(font);
+		TTF_drawLine_Solid(font, textbuf, row);
+	}
+	return textbuf;
+}
+
+SDL_Surface *TTF_RenderGlyph_Solid(TTF_Font *font, Uint16 ch, SDL_Color fg)
+{
+	SDL_Surface *textbuf;
+	SDL_Palette *palette;
+	Uint8 *src, *dst;
+	int row;
+	FT_Error error;
+	c_glyph *glyph;
+
+	/* Get the glyph itself */
+	error = Find_Glyph(font, ch, CACHED_METRICS|CACHED_BITMAP);
+	if ( error ) {
+		return(NULL);
+	}
+	glyph = font->current;
+
+	/* Create the target surface */
+	row = glyph->bitmap.rows;
+	if( TTF_HANDLE_STYLE_UNDERLINE(font) ) {
+		/* Update height according to the needs of the underline style */
+		int bottom_row = TTF_Glyph_underline_bottom_row(font, glyph);
+		if ( row < bottom_row ) {
+			row = bottom_row;
+		}
+	}
+
+	textbuf = SDL_CreateRGBSurface( SDL_SWSURFACE,
+					glyph->bitmap.width,
+					row,
+					8, 0, 0, 0, 0 );
+	if ( ! textbuf ) {
+		return(NULL);
+	}
+
+	/* Fill the palette with the foreground color */
+	palette = textbuf->format->palette;
+	palette->colors[0].r = 255-fg.r;
+	palette->colors[0].g = 255-fg.g;
+	palette->colors[0].b = 255-fg.b;
+	palette->colors[1].r = fg.r;
+	palette->colors[1].g = fg.g;
+	palette->colors[1].b = fg.b;
+	SDL_SetColorKey(textbuf, SDL_SRCCOLORKEY, 0);
+
+	/* Copy the character from the pixmap */
+	src = glyph->bitmap.buffer;
+	dst = (Uint8*) textbuf->pixels;
+	for ( row = 0; row < glyph->bitmap.rows; ++row ) {
+		memcpy( dst, src, glyph->bitmap.width );
+		src += glyph->bitmap.pitch;
+		dst += textbuf->pitch;
+	}
+
+	/* Handle the underline style */
+	if( TTF_HANDLE_STYLE_UNDERLINE(font) ) {
+		row = TTF_Glyph_underline_top_row(font, glyph);
+		TTF_drawLine_Solid(font, textbuf, row);
+	}
+
+	/* Handle the strikethrough style */
+	if( TTF_HANDLE_STYLE_STRIKETHROUGH(font) ) {
+		row = TTF_Glyph_strikethrough_top_row(font, glyph);
+		TTF_drawLine_Solid(font, textbuf, row);
+	}
+	return(textbuf);
+}
+
+
+/* Convert the Latin-1 text to UNICODE and render it
+*/
+SDL_Surface *TTF_RenderText_Shaded(TTF_Font *font,
+				const char *text, SDL_Color fg, SDL_Color bg)
+{
+	SDL_Surface *textbuf;
+	Uint16 *unicode_text;
+	int unicode_len;
+
+	/* Copy the Latin-1 text to a UNICODE text buffer */
+	unicode_len = strlen(text);
+	unicode_text = (Uint16 *)ALLOCA((1+unicode_len+1)*(sizeof *unicode_text));
+	if ( unicode_text == NULL ) {
+		TTF_SetError("Out of memory");
+		return(NULL);
+	}
+	*unicode_text = UNICODE_BOM_NATIVE;
+	LATIN1_to_UNICODE(unicode_text+1, text, unicode_len);
+
+	/* Render the new text */
+	textbuf = TTF_RenderUNICODE_Shaded(font, unicode_text, fg, bg);
+
+	/* Free the text buffer and return */
+	FREEA(unicode_text);
+	return(textbuf);
+}
+
+/* Convert the UTF-8 text to UNICODE and render it
+*/
+SDL_Surface *TTF_RenderUTF8_Shaded(TTF_Font *font,
+				const char *text, SDL_Color fg, SDL_Color bg)
+{
+	SDL_Surface *textbuf;
+	Uint16 *unicode_text;
+	int unicode_len;
+
+	/* Copy the UTF-8 text to a UNICODE text buffer */
+	unicode_len = strlen(text);
+	unicode_text = (Uint16 *)ALLOCA((1+unicode_len+1)*(sizeof *unicode_text));
+	if ( unicode_text == NULL ) {
+		TTF_SetError("Out of memory");
+		return(NULL);
+	}
+	*unicode_text = UNICODE_BOM_NATIVE;
+	UTF8_to_UNICODE(unicode_text+1, text, unicode_len);
+
+	/* Render the new text */
+	textbuf = TTF_RenderUNICODE_Shaded(font, unicode_text, fg, bg);
+
+	/* Free the text buffer and return */
+	FREEA(unicode_text);
+	return(textbuf);
+}
+
+SDL_Surface* TTF_RenderUNICODE_Shaded( TTF_Font* font,
+				       const Uint16* text,
+				       SDL_Color fg,
+				       SDL_Color bg )
+{
+	int xstart;
+	int width;
+	int height;
+	SDL_Surface* textbuf;
+	SDL_Palette* palette;
+	int index;
+	int rdiff;
+	int gdiff;
+	int bdiff;
+	const Uint16* ch;
+	Uint8* src;
+	Uint8* dst;
+	Uint8* dst_check;
+	int swapped;
+	int row, col;
+	FT_Bitmap* current;
+	c_glyph *glyph;
+	FT_Error error;
+	FT_Long use_kerning;
+	FT_UInt prev_index = 0;
+
+	/* Get the dimensions of the text surface */
+	if( ( TTF_SizeUNICODE(font, text, &width, &height) < 0 ) || !width ) {
+		TTF_SetError("Text has zero width");
+		return NULL;
+	}
+
+	/* Create the target surface */
+	textbuf = SDL_AllocSurface(SDL_SWSURFACE, width, height, 8, 0, 0, 0, 0);
+	if( textbuf == NULL ) {
+		return NULL;
+	}
+
+	/* Adding bound checking to avoid all kinds of memory corruption errors
+	   that may occur. */
+	dst_check = (Uint8*)textbuf->pixels + textbuf->pitch * textbuf->h;
+
+	/* Fill the palette with NUM_GRAYS levels of shading from bg to fg */
+	palette = textbuf->format->palette;
+	rdiff = fg.r - bg.r;
+	gdiff = fg.g - bg.g;
+	bdiff = fg.b - bg.b;
+
+	for( index = 0; index < NUM_GRAYS; ++index ) {
+		palette->colors[index].r = bg.r + (index*rdiff) / (NUM_GRAYS-1);
+		palette->colors[index].g = bg.g + (index*gdiff) / (NUM_GRAYS-1);
+		palette->colors[index].b = bg.b + (index*bdiff) / (NUM_GRAYS-1);
+	}
+
+	/* check kerning */
+	use_kerning = FT_HAS_KERNING( font->face ) && font->kerning;
+	
+	/* Load and render each character */
+	xstart = 0;
+	swapped = TTF_byteswapped;
+	for( ch = text; *ch; ++ch ) {
+		Uint16 c = *ch;
+		if ( c == UNICODE_BOM_NATIVE ) {
+			swapped = 0;
+			if ( text == ch ) {
+				++text;
+			}
+			continue;
+		}
+		if ( c == UNICODE_BOM_SWAPPED ) {
+			swapped = 1;
+			if ( text == ch ) {
+				++text;
+			}
+			continue;
+		}
+		if ( swapped ) {
+			c = SDL_Swap16(c);
+		}
+
+		error = Find_Glyph(font, c, CACHED_METRICS|CACHED_PIXMAP);
+		if( error ) {
+			SDL_FreeSurface( textbuf );
+			return NULL;
+		}
+		glyph = font->current;
+		/* Ensure the width of the pixmap is correct. On some cases,
+		 * freetype may report a larger pixmap than possible.*/
+		width = glyph->pixmap.width;
+		if (font->outline <= 0 && width > glyph->maxx - glyph->minx) {
+			width = glyph->maxx - glyph->minx;
+		}
+		/* do kerning, if possible AC-Patch */
+		if ( use_kerning && prev_index && glyph->index ) {
+			FT_Vector delta; 
+			FT_Get_Kerning( font->face, prev_index, glyph->index, ft_kerning_default, &delta ); 
+			xstart += delta.x >> 6;
+		}
+		/* Compensate for the wrap around with negative minx's */
+		if ( (ch == text) && (glyph->minx < 0) ) {
+			xstart -= glyph->minx;
+		}
+		
+		current = &glyph->pixmap;
+		for( row = 0; row < current->rows; ++row ) {
+			/* Make sure we don't go either over, or under the
+			 * limit */
+			if ( row+glyph->yoffset < 0 ) {
+				continue;
+			}
+			if ( row+glyph->yoffset >= textbuf->h ) {
+				continue;
+			}
+			dst = (Uint8*) textbuf->pixels +
+				(row+glyph->yoffset) * textbuf->pitch +
+				xstart + glyph->minx;
+			src = current->buffer + row * current->pitch;
+			for ( col=width; col>0 && dst < dst_check; --col ) {
+				*dst++ |= *src++;
+			}
+		}
+
+		xstart += glyph->advance;
+		if( TTF_HANDLE_STYLE_BOLD(font) ) {
+			xstart += font->glyph_overhang;
+		}
+		prev_index = glyph->index;
+	}
+
+	/* Handle the underline style */
+	if( TTF_HANDLE_STYLE_UNDERLINE(font) ) {
+		row = TTF_underline_top_row(font);
+		TTF_drawLine_Shaded(font, textbuf, row);
+	}
+
+	/* Handle the strikethrough style */
+	if( TTF_HANDLE_STYLE_STRIKETHROUGH(font) ) {
+		row = TTF_strikethrough_top_row(font);
+		TTF_drawLine_Shaded(font, textbuf, row);
+	}
+	return textbuf;
+}
+
+SDL_Surface* TTF_RenderGlyph_Shaded( TTF_Font* font,
+				     Uint16 ch,
+				     SDL_Color fg,
+				     SDL_Color bg )
+{
+	SDL_Surface* textbuf;
+	SDL_Palette* palette;
+	int index;
+	int rdiff;
+	int gdiff;
+	int bdiff;
+	Uint8* src;
+	Uint8* dst;
+	int row;
+	FT_Error error;
+	c_glyph* glyph;
+
+	/* Get the glyph itself */
+	error = Find_Glyph(font, ch, CACHED_METRICS|CACHED_PIXMAP);
+	if( error ) {
+		return NULL;
+	}
+	glyph = font->current;
+
+	/* Create the target surface */
+	row = glyph->pixmap.rows;
+	if( TTF_HANDLE_STYLE_UNDERLINE(font) ) {
+		/* Update height according to the needs of the underline style */
+		int bottom_row = TTF_Glyph_underline_bottom_row(font, glyph);
+		if ( row < bottom_row ) {
+			row = bottom_row;
+		}
+	}
+
+	textbuf = SDL_CreateRGBSurface( SDL_SWSURFACE,
+					glyph->pixmap.width,
+					row,
+					8, 0, 0, 0, 0 );
+	if( !textbuf ) {
+		return NULL;
+	}
+
+	/* Fill the palette with NUM_GRAYS levels of shading from bg to fg */
+	palette = textbuf->format->palette;
+	rdiff = fg.r - bg.r;
+	gdiff = fg.g - bg.g;
+	bdiff = fg.b - bg.b;
+	for( index = 0; index < NUM_GRAYS; ++index ) {
+		palette->colors[index].r = bg.r + (index*rdiff) / (NUM_GRAYS-1);
+		palette->colors[index].g = bg.g + (index*gdiff) / (NUM_GRAYS-1);
+		palette->colors[index].b = bg.b + (index*bdiff) / (NUM_GRAYS-1);
+	}
+
+	/* Copy the character from the pixmap */
+	src = glyph->pixmap.buffer;
+	dst = (Uint8*) textbuf->pixels;
+	for ( row = 0; row < glyph->pixmap.rows; ++row ) {
+		memcpy( dst, src, glyph->pixmap.width );
+		src += glyph->pixmap.pitch;
+		dst += textbuf->pitch;
+	}
+
+	/* Handle the underline style */
+	if( TTF_HANDLE_STYLE_UNDERLINE(font) ) {
+		row = TTF_Glyph_underline_top_row(font, glyph);
+		TTF_drawLine_Shaded(font, textbuf, row);
+	}
+
+	/* Handle the strikethrough style */
+	if( TTF_HANDLE_STYLE_STRIKETHROUGH(font) ) {
+		row = TTF_Glyph_strikethrough_top_row(font, glyph);
+		TTF_drawLine_Shaded(font, textbuf, row);
+	}
+	return textbuf;
+}
+
+/* Convert the Latin-1 text to UNICODE and render it
+*/
+SDL_Surface *TTF_RenderText_Blended(TTF_Font *font,
+				const char *text, SDL_Color fg)
+{
+	SDL_Surface *textbuf;
+	Uint16 *unicode_text;
+	int unicode_len;
+
+	/* Copy the Latin-1 text to a UNICODE text buffer */
+	unicode_len = strlen(text);
+	unicode_text = (Uint16 *)ALLOCA((1+unicode_len+1)*(sizeof *unicode_text));
+	if ( unicode_text == NULL ) {
+		TTF_SetError("Out of memory");
+		return(NULL);
+	}
+	*unicode_text = UNICODE_BOM_NATIVE;
+	LATIN1_to_UNICODE(unicode_text+1, text, unicode_len);
+
+	/* Render the new text */
+	textbuf = TTF_RenderUNICODE_Blended(font, unicode_text, fg);
+
+	/* Free the text buffer and return */
+	FREEA(unicode_text);
+	return(textbuf);
+}
+
+/* Convert the UTF-8 text to UNICODE and render it
+*/
+SDL_Surface *TTF_RenderUTF8_Blended(TTF_Font *font,
+				const char *text, SDL_Color fg)
+{
+	SDL_Surface *textbuf;
+	Uint16 *unicode_text;
+	int unicode_len;
+
+	/* Copy the UTF-8 text to a UNICODE text buffer */
+	unicode_len = strlen(text);
+	unicode_text = (Uint16 *)ALLOCA((1+unicode_len+1)*(sizeof *unicode_text));
+	if ( unicode_text == NULL ) {
+		TTF_SetError("Out of memory");
+		return(NULL);
+	}
+	*unicode_text = UNICODE_BOM_NATIVE;
+	UTF8_to_UNICODE(unicode_text+1, text, unicode_len);
+
+	/* Render the new text */
+	textbuf = TTF_RenderUNICODE_Blended(font, unicode_text, fg);
+
+	/* Free the text buffer and return */
+	FREEA(unicode_text);
+	return(textbuf);
+}
+
+SDL_Surface *TTF_RenderUNICODE_Blended(TTF_Font *font,
+				const Uint16 *text, SDL_Color fg)
+{
+	int xstart;
+	int width, height;
+	SDL_Surface *textbuf;
+	Uint32 alpha;
+	Uint32 pixel;
+	const Uint16 *ch;
+	Uint8 *src;
+	Uint32 *dst;
+	Uint32 *dst_check;
+	int swapped;
+	int row, col;
+	c_glyph *glyph;
+	FT_Error error;
+	FT_Long use_kerning;
+	FT_UInt prev_index = 0;
+
+	/* Get the dimensions of the text surface */
+	if ( (TTF_SizeUNICODE(font, text, &width, &height) < 0) || !width ) {
+		TTF_SetError("Text has zero width");
+		return(NULL);
+	}
+
+	/* Create the target surface */
+	textbuf = SDL_AllocSurface(SDL_SWSURFACE, width, height, 32,
+	                           0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000);
+	if ( textbuf == NULL ) {
+		return(NULL);
+	}
+
+	/* Adding bound checking to avoid all kinds of memory corruption errors
+	   that may occur. */
+	dst_check = (Uint32*)textbuf->pixels + textbuf->pitch/4 * textbuf->h;
+
+	/* check kerning */
+	use_kerning = FT_HAS_KERNING( font->face ) && font->kerning;
+	
+	/* Load and render each character */
+	xstart = 0;
+	swapped = TTF_byteswapped;
+	pixel = (fg.r<<16)|(fg.g<<8)|fg.b;
+	SDL_FillRect(textbuf, NULL, pixel);	/* Initialize with fg and 0 alpha */
+
+	for ( ch=text; *ch; ++ch ) {
+		Uint16 c = *ch;
+		if ( c == UNICODE_BOM_NATIVE ) {
+			swapped = 0;
+			if ( text == ch ) {
+				++text;
+			}
+			continue;
+		}
+		if ( c == UNICODE_BOM_SWAPPED ) {
+			swapped = 1;
+			if ( text == ch ) {
+				++text;
+			}
+			continue;
+		}
+		if ( swapped ) {
+			c = SDL_Swap16(c);
+		}
+		error = Find_Glyph(font, c, CACHED_METRICS|CACHED_PIXMAP);
+		if( error ) {
+			SDL_FreeSurface( textbuf );
+			return NULL;
+		}
+		glyph = font->current;
+		/* Ensure the width of the pixmap is correct. On some cases,
+		 * freetype may report a larger pixmap than possible.*/
+		width = glyph->pixmap.width;
+		if (font->outline <= 0 && width > glyph->maxx - glyph->minx) {
+			width = glyph->maxx - glyph->minx;
+		}
+		/* do kerning, if possible AC-Patch */
+		if ( use_kerning && prev_index && glyph->index ) {
+			FT_Vector delta; 
+			FT_Get_Kerning( font->face, prev_index, glyph->index, ft_kerning_default, &delta ); 
+			xstart += delta.x >> 6;
+		}
+		
+		/* Compensate for the wrap around bug with negative minx's */
+		if ( (ch == text) && (glyph->minx < 0) ) {
+			xstart -= glyph->minx;
+		}
+
+		for ( row = 0; row < glyph->pixmap.rows; ++row ) {
+			/* Make sure we don't go either over, or under the
+			 * limit */
+			if ( row+glyph->yoffset < 0 ) {
+				continue;
+			}
+			if ( row+glyph->yoffset >= textbuf->h ) {
+				continue;
+			}
+			dst = (Uint32*) textbuf->pixels +
+				(row+glyph->yoffset) * textbuf->pitch/4 +
+				xstart + glyph->minx;
+
+			/* Added code to adjust src pointer for pixmaps to
+			 * account for pitch.
+			 * */
+			src = (Uint8*) (glyph->pixmap.buffer + glyph->pixmap.pitch * row);
+			for ( col = width; col>0 && dst < dst_check; --col) {
+				alpha = *src++;
+				*dst++ |= pixel | (alpha << 24);
+			}
+		}
+
+		xstart += glyph->advance;
+		if ( TTF_HANDLE_STYLE_BOLD(font) ) {
+			xstart += font->glyph_overhang;
+		}
+		prev_index = glyph->index;
+	}
+
+	/* Handle the underline style */
+	if( TTF_HANDLE_STYLE_UNDERLINE(font) ) {
+		row = TTF_underline_top_row(font);
+		TTF_drawLine_Blended(font, textbuf, row, pixel);
+	}
+
+	/* Handle the strikethrough style */
+	if( TTF_HANDLE_STYLE_STRIKETHROUGH(font) ) {
+		row = TTF_strikethrough_top_row(font);
+		TTF_drawLine_Blended(font, textbuf, row, pixel);
+	}
+	return(textbuf);
+}
+
+SDL_Surface *TTF_RenderGlyph_Blended(TTF_Font *font, Uint16 ch, SDL_Color fg)
+{
+	SDL_Surface *textbuf;
+	Uint32 alpha;
+	Uint32 pixel;
+	Uint8 *src;
+	Uint32 *dst;
+	int row, col;
+	FT_Error error;
+	c_glyph *glyph;
+
+	/* Get the glyph itself */
+	error = Find_Glyph(font, ch, CACHED_METRICS|CACHED_PIXMAP);
+	if ( error ) {
+		return(NULL);
+	}
+	glyph = font->current;
+
+	/* Create the target surface */
+	row = glyph->pixmap.rows;
+	if( TTF_HANDLE_STYLE_UNDERLINE(font) ) {
+		/* Update height according to the needs of the underline style */
+		int bottom_row = TTF_Glyph_underline_bottom_row(font, glyph);
+		if ( row < bottom_row ) {
+			row = bottom_row;
+		}
+	}
+
+	textbuf = SDL_CreateRGBSurface(SDL_SWSURFACE,
+	              glyph->pixmap.width, row, 32,
+                  0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000);
+	if ( ! textbuf ) {
+		return(NULL);
+	}
+
+	/* Copy the character from the pixmap */
+	pixel = (fg.r<<16)|(fg.g<<8)|fg.b;
+	SDL_FillRect(textbuf, NULL, pixel);	/* Initialize with fg and 0 alpha */
+
+	for ( row=0; row<glyph->pixmap.rows; ++row ) {
+		/* Changed src to take pitch into account, not just width */
+		src = glyph->pixmap.buffer + row * glyph->pixmap.pitch;
+		dst = (Uint32 *)textbuf->pixels + row * textbuf->pitch/4;
+		for ( col=0; col<glyph->pixmap.width; ++col ) {
+			alpha = *src++;
+			*dst++ = pixel | (alpha << 24);
+		}
+	}
+
+	/* Handle the underline style */
+	if( TTF_HANDLE_STYLE_UNDERLINE(font) ) {
+		row = TTF_Glyph_underline_top_row(font, glyph);
+		TTF_drawLine_Blended(font, textbuf, row, pixel);
+	}
+
+	/* Handle the strikethrough style */
+	if( TTF_HANDLE_STYLE_STRIKETHROUGH(font) ) {
+		row = TTF_Glyph_strikethrough_top_row(font, glyph);
+		TTF_drawLine_Blended(font, textbuf, row, pixel);
+	}
+	return(textbuf);
+}
+
+void TTF_SetFontStyle( TTF_Font* font, int style )
+{
+	int prev_style = font->style;
+	font->style = style | font->face_style;
+
+	/* Flush the cache if the style has changed.
+	 * Ignore UNDERLINE which does not impact glyph drawning.
+	 * */
+	if ( (font->style | TTF_STYLE_NO_GLYPH_CHANGE ) != ( prev_style | TTF_STYLE_NO_GLYPH_CHANGE )) {
+		Flush_Cache( font );
+	}
+}
+
+int TTF_GetFontStyle( const TTF_Font* font )
+{
+	return font->style;
+}
+
+void TTF_SetFontOutline( TTF_Font* font, int outline )
+{
+	font->outline = outline;
+	Flush_Cache( font );
+}
+
+int TTF_GetFontOutline( const TTF_Font* font )
+{
+	return font->outline;
+}
+
+void TTF_SetFontHinting( TTF_Font* font, int hinting )
+{
+	if (hinting == TTF_HINTING_LIGHT)
+		font->hinting = FT_LOAD_TARGET_LIGHT;
+	else if (hinting == TTF_HINTING_MONO)
+		font->hinting = FT_LOAD_TARGET_MONO;
+	else if (hinting == TTF_HINTING_NONE)
+		font->hinting = FT_LOAD_NO_HINTING;
+	else
+		font->hinting = 0;
+
+	Flush_Cache( font );
+}
+
+int TTF_GetFontHinting( const TTF_Font* font )
+{
+	if (font->hinting == FT_LOAD_TARGET_LIGHT)
+		return TTF_HINTING_LIGHT;
+	else if (font->hinting == FT_LOAD_TARGET_MONO)
+		return TTF_HINTING_MONO;
+	else if (font->hinting == FT_LOAD_NO_HINTING)
+		return TTF_HINTING_NONE;
+	return 0;
+}
+
+void TTF_Quit( void )
+{
+	if ( TTF_initialized ) {
+		if ( --TTF_initialized == 0 ) {
+			FT_Done_FreeType( library );
+		}
+	}
+}
+
+int TTF_WasInit( void )
+{
+	return TTF_initialized;
+}
+
+int TTF_GetFontKerningSize(TTF_Font* font, int prev_index, int index)
+{
+	FT_Vector delta; 
+	FT_Get_Kerning( font->face, prev_index, index, ft_kerning_default, &delta ); 
+	return (delta.x >> 6);
+}
diff --git a/sources/packages/l/sdl/sdl-ttf/create-2.0.11-shaded-text-patch/create.patch.sh b/sources/packages/l/sdl/sdl-ttf/create-2.0.11-shaded-text-patch/create.patch.sh
new file mode 100755
index 000000000..1c364ad7c
--- /dev/null
+++ b/sources/packages/l/sdl/sdl-ttf/create-2.0.11-shaded-text-patch/create.patch.sh
@@ -0,0 +1,15 @@
+#!/bin/sh
+
+VERSION=2.0.11
+
+tar --files-from=file.list -xzvf ../SDL_ttf-$VERSION.tar.gz
+mv SDL_ttf-$VERSION SDL_ttf-$VERSION-orig
+
+cp -rf ./SDL_ttf-$VERSION-new ./SDL_ttf-$VERSION
+
+diff -b --unified -Nr  SDL_ttf-$VERSION-orig  SDL_ttf-$VERSION > SDL_ttf-$VERSION-shaded-text.patch
+
+mv SDL_ttf-$VERSION-shaded-text.patch ../patches
+
+rm -rf ./SDL_ttf-$VERSION
+rm -rf ./SDL_ttf-$VERSION-orig
diff --git a/sources/packages/l/sdl/sdl-ttf/create-2.0.11-shaded-text-patch/file.list b/sources/packages/l/sdl/sdl-ttf/create-2.0.11-shaded-text-patch/file.list
new file mode 100644
index 000000000..e9dcf33f2
--- /dev/null
+++ b/sources/packages/l/sdl/sdl-ttf/create-2.0.11-shaded-text-patch/file.list
@@ -0,0 +1 @@
+SDL_ttf-2.0.11/SDL_ttf.c
diff --git a/sources/packages/l/sdl/sdl/Makefile b/sources/packages/l/sdl/sdl/Makefile
new file mode 100644
index 000000000..bcad30eda
--- /dev/null
+++ b/sources/packages/l/sdl/sdl/Makefile
@@ -0,0 +1,66 @@
+
+COMPONENT_TARGETS = $(HARDWARE_NOARCH)
+
+
+include ../../../../../build-system/constants.mk
+
+
+url         = $(DOWNLOAD_SERVER)/sources/packages/l/sdl/sdl
+
+versions    = 1.2.15
+pkgname     = SDL
+suffix      = tar.gz
+
+tarballs    = $(addsuffix .$(suffix), $(addprefix $(pkgname)-, $(versions)))
+sha1s       = $(addsuffix .sha1sum, $(tarballs))
+
+patches     = $(CURDIR)/patches/SDL-1.2.15-bypass-gamma.patch
+patches    += $(CURDIR)/patches/SDL-1.2.15-disable-mmx.patch
+patches    += $(CURDIR)/patches/SDL-1.2.15-joystick-axis.patch
+patches    += $(CURDIR)/patches/SDL-1.2.15-x11-XData32.patch
+patches    += $(CURDIR)/patches/SDL-1.2.15-x11-events.patch
+patches    += $(CURDIR)/patches/SDL-1.2.15-x11-grab.patch
+
+.NOTPARALLEL: $(patches)
+
+
+BUILD_TARGETS = $(tarballs) $(sha1s) $(patches)
+
+
+include ../../../../../build-system/core.mk
+
+
+.PHONY: download_clean
+
+
+$(tarballs):
+	@echo -e "\n======= Downloading source tarballs =======" ; \
+	 for tarball in $(tarballs) ; do \
+	   echo "$(url)/$$tarball" | xargs -n 1 -P 100 wget $(WGET_OPTIONS) -i & \
+	 done ; wait
+
+$(sha1s): $(tarballs)
+	@for sha in $@ ; do \
+	   echo -e "\n======= Downloading '$$sha' signature =======\n" ; \
+	   echo "$(url)/$$sha" | xargs -n 1 -P 100 wget $(WGET_OPTIONS) -i & wait %1 ; \
+	   touch $$sha ; \
+	   echo -e "\n======= Check the '$$sha' sha1sum =======\n" ; \
+	   sha1sum --check $$sha ; ret="$$?" ; \
+	   if [ "$$ret" == "1" ]; then \
+	     echo -e "\n======= ERROR: Bad '$$sha' sha1sum =======\n" ; \
+	     exit 1 ; \
+	   fi ; \
+	 done
+
+$(patches): $(sha1s)
+	@echo -e "\n======= Create Patches =======\n" ; \
+	 ( cd create-1.2.15-bypass-gamma-patch  ; ./create.patch.sh ) ; \
+	 ( cd create-1.2.15-disable-mmx-patch   ; ./create.patch.sh ) ; \
+	 ( cd create-1.2.15-joystick-axis-patch ; ./create.patch.sh ) ; \
+	 ( cd create-1.2.15-x11-XData32-patch   ; ./create.patch.sh ) ; \
+	 ( cd create-1.2.15-x11-events-patch    ; ./create.patch.sh ) ; \
+	 ( cd create-1.2.15-x11-grab-patch      ; ./create.patch.sh ) ; \
+	 echo -e "\n"
+
+download_clean:
+	@rm -f $(tarballs) $(sha1s) $(patches)
diff --git a/sources/packages/l/sdl/sdl/create-1.2.15-bypass-gamma-patch/SDL-1.2.15-new/src/video/SDL_gamma.c b/sources/packages/l/sdl/sdl/create-1.2.15-bypass-gamma-patch/SDL-1.2.15-new/src/video/SDL_gamma.c
new file mode 100644
index 000000000..464ab8827
--- /dev/null
+++ b/sources/packages/l/sdl/sdl/create-1.2.15-bypass-gamma-patch/SDL-1.2.15-new/src/video/SDL_gamma.c
@@ -0,0 +1,222 @@
+/*
+    SDL - Simple DirectMedia Layer
+    Copyright (C) 1997-2012 Sam Lantinga
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+    Sam Lantinga
+    slouken@libsdl.org
+*/
+#include "SDL_config.h"
+
+/* Gamma correction support */
+
+#ifdef HAVE_MATH_H
+#include <math.h>	/* Used for calculating gamma ramps */
+#else
+/* Math routines from uClibc: http://www.uclibc.org */
+#include "math_private.h"
+#include "e_sqrt.h"
+#include "e_pow.h"
+#include "e_log.h"
+#define pow(x, y)	__ieee754_pow(x, y)
+#define log(x)		__ieee754_log(x)
+#endif
+
+#include "SDL_sysvideo.h"
+
+
+static void CalculateGammaRamp(float gamma, Uint16 *ramp)
+{
+	int i;
+
+	/* 0.0 gamma is all black */
+	if ( gamma <= 0.0f ) {
+		for ( i=0; i<256; ++i ) {
+			ramp[i] = 0;
+		}
+		return;
+	} else
+	/* 1.0 gamma is identity */
+	if ( gamma == 1.0f ) {
+		for ( i=0; i<256; ++i ) {
+			ramp[i] = (i << 8) | i;
+		}
+		return;
+	} else
+	/* Calculate a real gamma ramp */
+	{ int value;
+		gamma = 1.0f / gamma;
+		for ( i=0; i<256; ++i ) {
+			value = (int)(pow((double)i/256.0, gamma)*65535.0+0.5);
+			if ( value > 65535 ) {
+				value = 65535;
+			}
+			ramp[i] = (Uint16)value;
+		}
+	}
+}
+static void CalculateGammaFromRamp(float *gamma, Uint16 *ramp)
+{
+	/* The following is adapted from a post by Garrett Bass on OpenGL
+	   Gamedev list, March 4, 2000.
+	 */
+	float sum = 0.0f;
+	int i, count = 0;
+
+	*gamma = 1.0;
+	for ( i = 1; i < 256; ++i ) {
+	    if ( (ramp[i] != 0) && (ramp[i] != 65535) ) {
+	        double B = (double)i / 256.0;
+	        double A = ramp[i] / 65535.0;
+	        sum += (float) ( log(A) / log(B) );
+	        count++;
+	    }
+	}
+	if ( count && sum > 0.0f ) {
+		*gamma = 1.0f / (sum / count);
+	}
+}
+
+int SDL_SetGamma(float red, float green, float blue)
+{
+	int succeeded = -1;
+	SDL_VideoDevice *video = current_video;
+	SDL_VideoDevice *this  = current_video;	
+
+	if ( video->SetGamma ) {
+		succeeded = video->SetGamma(this, red, green, blue);
+	}
+	return succeeded;
+}
+
+/* Calculating the gamma by integrating the gamma ramps isn't exact,
+   so this function isn't officially supported.
+*/
+int SDL_GetGamma(float *red, float *green, float *blue)
+{
+	int succeeded;
+	SDL_VideoDevice *video = current_video;
+	SDL_VideoDevice *this  = current_video;	
+
+	succeeded = -1;
+	/* Prefer using GetGammaRamp(), as it's more flexible */
+	{
+		Uint16 ramp[3][256];
+
+		succeeded = SDL_GetGammaRamp(ramp[0], ramp[1], ramp[2]);
+		if ( succeeded >= 0 ) {
+			CalculateGammaFromRamp(red, ramp[0]);
+			CalculateGammaFromRamp(green, ramp[1]);
+			CalculateGammaFromRamp(blue, ramp[2]);
+		}
+	}
+	if ( (succeeded < 0) && video->GetGamma ) {
+		SDL_ClearError();
+		succeeded = video->GetGamma(this, red, green, blue);
+	}
+	return succeeded;
+}
+
+int SDL_SetGammaRamp(const Uint16 *red, const Uint16 *green, const Uint16 *blue)
+{
+	int succeeded;
+	SDL_VideoDevice *video = current_video;
+	SDL_VideoDevice *this  = current_video;	
+	SDL_Surface *screen = SDL_PublicSurface;
+
+	/* Verify the screen parameter */
+	if ( !screen ) {
+		SDL_SetError("No video mode has been set");
+		return -1;
+	}
+
+	/* Lazily allocate the gamma tables */
+	if ( ! video->gamma ) {
+		SDL_GetGammaRamp(0, 0, 0);
+	}
+
+	/* Fill the gamma table with the new values */
+	if ( red ) {
+		SDL_memcpy(&video->gamma[0*256], red, 256*sizeof(*video->gamma));
+	}
+	if ( green ) {
+		SDL_memcpy(&video->gamma[1*256], green, 256*sizeof(*video->gamma));
+	}
+	if ( blue ) {
+		SDL_memcpy(&video->gamma[2*256], blue, 256*sizeof(*video->gamma));
+	}
+
+	/* Gamma correction always possible on split palettes */
+	if ( (screen->flags & SDL_HWPALETTE) == SDL_HWPALETTE ) {
+		SDL_Palette *pal = screen->format->palette;
+
+		/* If physical palette has been set independently, use it */
+		if(video->physpal)
+		        pal = video->physpal;
+		      
+		SDL_SetPalette(screen, SDL_PHYSPAL,
+			       pal->colors, 0, pal->ncolors);
+		return 0;
+	}
+
+	/* Try to set the gamma ramp in the driver */
+	succeeded = -1;
+	if ( video->SetGammaRamp ) {
+		succeeded = video->SetGammaRamp(this, video->gamma);
+	} else {
+		SDL_SetError("Gamma ramp manipulation not supported");
+	}
+	return succeeded;
+}
+
+int SDL_GetGammaRamp(Uint16 *red, Uint16 *green, Uint16 *blue)
+{
+	SDL_VideoDevice *video = current_video;
+	SDL_VideoDevice *this  = current_video;	
+
+	/* Lazily allocate the gamma table */
+	if ( ! video->gamma ) {
+		video->gamma = SDL_malloc(3*256*sizeof(*video->gamma));
+		if ( ! video->gamma ) {
+			SDL_OutOfMemory();
+			return -1;
+		}
+		if ( video->GetGammaRamp ) {
+			/* Get the real hardware gamma */
+			video->GetGammaRamp(this, video->gamma);
+		} else {
+			/* Assume an identity gamma */
+			int i;
+			for ( i=0; i<256; ++i ) {
+				video->gamma[0*256+i] = (i << 8) | i;
+				video->gamma[1*256+i] = (i << 8) | i;
+				video->gamma[2*256+i] = (i << 8) | i;
+			}
+		}
+	}
+
+	/* Just copy from our internal table */
+	if ( red ) {
+		SDL_memcpy(red, &video->gamma[0*256], 256*sizeof(*red));
+	}
+	if ( green ) {
+		SDL_memcpy(green, &video->gamma[1*256], 256*sizeof(*green));
+	}
+	if ( blue ) {
+		SDL_memcpy(blue, &video->gamma[2*256], 256*sizeof(*blue));
+	}
+	return 0;
+}
diff --git a/sources/packages/l/sdl/sdl/create-1.2.15-bypass-gamma-patch/create.patch.sh b/sources/packages/l/sdl/sdl/create-1.2.15-bypass-gamma-patch/create.patch.sh
new file mode 100755
index 000000000..4bdf2b133
--- /dev/null
+++ b/sources/packages/l/sdl/sdl/create-1.2.15-bypass-gamma-patch/create.patch.sh
@@ -0,0 +1,15 @@
+#!/bin/sh
+
+VERSION=1.2.15
+
+tar --files-from=file.list -xzvf ../SDL-$VERSION.tar.gz
+mv SDL-$VERSION SDL-$VERSION-orig
+
+cp -rf ./SDL-$VERSION-new ./SDL-$VERSION
+
+diff -b --unified -Nr  SDL-$VERSION-orig  SDL-$VERSION > SDL-$VERSION-bypass-gamma.patch
+
+mv SDL-$VERSION-bypass-gamma.patch ../patches
+
+rm -rf ./SDL-$VERSION
+rm -rf ./SDL-$VERSION-orig
diff --git a/sources/packages/l/sdl/sdl/create-1.2.15-bypass-gamma-patch/file.list b/sources/packages/l/sdl/sdl/create-1.2.15-bypass-gamma-patch/file.list
new file mode 100644
index 000000000..67b8b40d9
--- /dev/null
+++ b/sources/packages/l/sdl/sdl/create-1.2.15-bypass-gamma-patch/file.list
@@ -0,0 +1 @@
+SDL-1.2.15/src/video/SDL_gamma.c
diff --git a/sources/packages/l/sdl/sdl/create-1.2.15-disable-mmx-patch/SDL-1.2.15-new/src/video/SDL_yuv_sw.c b/sources/packages/l/sdl/sdl/create-1.2.15-disable-mmx-patch/SDL-1.2.15-new/src/video/SDL_yuv_sw.c
new file mode 100644
index 000000000..86f436b1b
--- /dev/null
+++ b/sources/packages/l/sdl/sdl/create-1.2.15-disable-mmx-patch/SDL-1.2.15-new/src/video/SDL_yuv_sw.c
@@ -0,0 +1,1301 @@
+/*
+    SDL - Simple DirectMedia Layer
+    Copyright (C) 1997-2012 Sam Lantinga
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+    Sam Lantinga
+    slouken@libsdl.org
+*/
+#include "SDL_config.h"
+
+/* This is the software implementation of the YUV video overlay support */
+
+/* This code was derived from code carrying the following copyright notices:
+
+ * Copyright (c) 1995 The Regents of the University of California.
+ * All rights reserved.
+ * 
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice and the following
+ * two paragraphs appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+
+ * Copyright (c) 1995 Erik Corry
+ * All rights reserved.
+ * 
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice and the following
+ * two paragraphs appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL ERIK CORRY BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
+ * SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
+ * THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF ERIK CORRY HAS BEEN ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * ERIK CORRY SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+ * PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS"
+ * BASIS, AND ERIK CORRY HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
+ * UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+
+ * Portions of this software Copyright (c) 1995 Brown University.
+ * All rights reserved.
+ * 
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement
+ * is hereby granted, provided that the above copyright notice and the
+ * following two paragraphs appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL BROWN UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF BROWN
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * BROWN UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+ * PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS"
+ * BASIS, AND BROWN UNIVERSITY HAS NO OBLIGATION TO PROVIDE MAINTENANCE,
+ * SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ */
+
+#include "SDL_video.h"
+#include "SDL_cpuinfo.h"
+#include "SDL_stretch_c.h"
+#include "SDL_yuvfuncs.h"
+#include "SDL_yuv_sw_c.h"
+
+#undef __OPTIMIZE__
+
+/* The functions used to manipulate software video overlays */
+static struct private_yuvhwfuncs sw_yuvfuncs = {
+	SDL_LockYUV_SW,
+	SDL_UnlockYUV_SW,
+	SDL_DisplayYUV_SW,
+	SDL_FreeYUV_SW
+};
+
+/* RGB conversion lookup tables */
+struct private_yuvhwdata {
+	SDL_Surface *stretch;
+	SDL_Surface *display;
+	Uint8 *pixels;
+	int *colortab;
+	Uint32 *rgb_2_pix;
+	void (*Display1X)(int *colortab, Uint32 *rgb_2_pix,
+                          unsigned char *lum, unsigned char *cr,
+                          unsigned char *cb, unsigned char *out,
+                          int rows, int cols, int mod );
+	void (*Display2X)(int *colortab, Uint32 *rgb_2_pix,
+	                  unsigned char *lum, unsigned char *cr,
+                          unsigned char *cb, unsigned char *out,
+                          int rows, int cols, int mod );
+
+	/* These are just so we don't have to allocate them separately */
+	Uint16 pitches[3];
+	Uint8 *planes[3];
+};
+
+
+/* The colorspace conversion functions */
+
+#if (__GNUC__ > 2) && defined(__i386__) && __OPTIMIZE__ && SDL_ASSEMBLY_ROUTINES
+extern void Color565DitherYV12MMX1X( int *colortab, Uint32 *rgb_2_pix,
+                                     unsigned char *lum, unsigned char *cr,
+                                     unsigned char *cb, unsigned char *out,
+                                     int rows, int cols, int mod );
+extern void ColorRGBDitherYV12MMX1X( int *colortab, Uint32 *rgb_2_pix,
+                                     unsigned char *lum, unsigned char *cr,
+                                     unsigned char *cb, unsigned char *out,
+                                     int rows, int cols, int mod );
+#endif 
+
+static void Color16DitherYV12Mod1X( int *colortab, Uint32 *rgb_2_pix,
+                                    unsigned char *lum, unsigned char *cr,
+                                    unsigned char *cb, unsigned char *out,
+                                    int rows, int cols, int mod )
+{
+    unsigned short* row1;
+    unsigned short* row2;
+    unsigned char* lum2;
+    int x, y;
+    int cr_r;
+    int crb_g;
+    int cb_b;
+    int cols_2 = cols / 2;
+
+    row1 = (unsigned short*) out;
+    row2 = row1 + cols + mod;
+    lum2 = lum + cols;
+
+    mod += cols + mod;
+
+    y = rows / 2;
+    while( y-- )
+    {
+        x = cols_2;
+        while( x-- )
+        {
+            register int L;
+
+            cr_r   = 0*768+256 + colortab[ *cr + 0*256 ];
+            crb_g  = 1*768+256 + colortab[ *cr + 1*256 ]
+                               + colortab[ *cb + 2*256 ];
+            cb_b   = 2*768+256 + colortab[ *cb + 3*256 ];
+            ++cr; ++cb;
+
+            L = *lum++;
+            *row1++ = (unsigned short)(rgb_2_pix[ L + cr_r ] |
+                                       rgb_2_pix[ L + crb_g ] |
+                                       rgb_2_pix[ L + cb_b ]);
+
+            L = *lum++;
+            *row1++ = (unsigned short)(rgb_2_pix[ L + cr_r ] |
+                                       rgb_2_pix[ L + crb_g ] |
+                                       rgb_2_pix[ L + cb_b ]);
+
+
+            /* Now, do second row.  */
+
+            L = *lum2++;
+            *row2++ = (unsigned short)(rgb_2_pix[ L + cr_r ] |
+                                       rgb_2_pix[ L + crb_g ] |
+                                       rgb_2_pix[ L + cb_b ]);
+
+            L = *lum2++;
+            *row2++ = (unsigned short)(rgb_2_pix[ L + cr_r ] |
+                                       rgb_2_pix[ L + crb_g ] |
+                                       rgb_2_pix[ L + cb_b ]);
+        }
+
+        /*
+         * These values are at the start of the next line, (due
+         * to the ++'s above),but they need to be at the start
+         * of the line after that.
+         */
+        lum  += cols;
+        lum2 += cols;
+        row1 += mod;
+        row2 += mod;
+    }
+}
+
+static void Color24DitherYV12Mod1X( int *colortab, Uint32 *rgb_2_pix,
+                                    unsigned char *lum, unsigned char *cr,
+                                    unsigned char *cb, unsigned char *out,
+                                    int rows, int cols, int mod )
+{
+    unsigned int value;
+    unsigned char* row1;
+    unsigned char* row2;
+    unsigned char* lum2;
+    int x, y;
+    int cr_r;
+    int crb_g;
+    int cb_b;
+    int cols_2 = cols / 2;
+
+    row1 = out;
+    row2 = row1 + cols*3 + mod*3;
+    lum2 = lum + cols;
+
+    mod += cols + mod;
+    mod *= 3;
+
+    y = rows / 2;
+    while( y-- )
+    {
+        x = cols_2;
+        while( x-- )
+        {
+            register int L;
+
+            cr_r   = 0*768+256 + colortab[ *cr + 0*256 ];
+            crb_g  = 1*768+256 + colortab[ *cr + 1*256 ]
+                               + colortab[ *cb + 2*256 ];
+            cb_b   = 2*768+256 + colortab[ *cb + 3*256 ];
+            ++cr; ++cb;
+
+            L = *lum++;
+            value = (rgb_2_pix[ L + cr_r ] |
+                     rgb_2_pix[ L + crb_g ] |
+                     rgb_2_pix[ L + cb_b ]);
+            *row1++ = (value      ) & 0xFF;
+            *row1++ = (value >>  8) & 0xFF;
+            *row1++ = (value >> 16) & 0xFF;
+
+            L = *lum++;
+            value = (rgb_2_pix[ L + cr_r ] |
+                     rgb_2_pix[ L + crb_g ] |
+                     rgb_2_pix[ L + cb_b ]);
+            *row1++ = (value      ) & 0xFF;
+            *row1++ = (value >>  8) & 0xFF;
+            *row1++ = (value >> 16) & 0xFF;
+
+
+            /* Now, do second row.  */
+
+            L = *lum2++;
+            value = (rgb_2_pix[ L + cr_r ] |
+                     rgb_2_pix[ L + crb_g ] |
+                     rgb_2_pix[ L + cb_b ]);
+            *row2++ = (value      ) & 0xFF;
+            *row2++ = (value >>  8) & 0xFF;
+            *row2++ = (value >> 16) & 0xFF;
+
+            L = *lum2++;
+            value = (rgb_2_pix[ L + cr_r ] |
+                     rgb_2_pix[ L + crb_g ] |
+                     rgb_2_pix[ L + cb_b ]);
+            *row2++ = (value      ) & 0xFF;
+            *row2++ = (value >>  8) & 0xFF;
+            *row2++ = (value >> 16) & 0xFF;
+        }
+
+        /*
+         * These values are at the start of the next line, (due
+         * to the ++'s above),but they need to be at the start
+         * of the line after that.
+         */
+        lum  += cols;
+        lum2 += cols;
+        row1 += mod;
+        row2 += mod;
+    }
+}
+
+static void Color32DitherYV12Mod1X( int *colortab, Uint32 *rgb_2_pix,
+                                    unsigned char *lum, unsigned char *cr,
+                                    unsigned char *cb, unsigned char *out,
+                                    int rows, int cols, int mod )
+{
+    unsigned int* row1;
+    unsigned int* row2;
+    unsigned char* lum2;
+    int x, y;
+    int cr_r;
+    int crb_g;
+    int cb_b;
+    int cols_2 = cols / 2;
+
+    row1 = (unsigned int*) out;
+    row2 = row1 + cols + mod;
+    lum2 = lum + cols;
+
+    mod += cols + mod;
+
+    y = rows / 2;
+    while( y-- )
+    {
+        x = cols_2;
+        while( x-- )
+        {
+            register int L;
+
+            cr_r   = 0*768+256 + colortab[ *cr + 0*256 ];
+            crb_g  = 1*768+256 + colortab[ *cr + 1*256 ]
+                               + colortab[ *cb + 2*256 ];
+            cb_b   = 2*768+256 + colortab[ *cb + 3*256 ];
+            ++cr; ++cb;
+
+            L = *lum++;
+            *row1++ = (rgb_2_pix[ L + cr_r ] |
+                       rgb_2_pix[ L + crb_g ] |
+                       rgb_2_pix[ L + cb_b ]);
+
+            L = *lum++;
+            *row1++ = (rgb_2_pix[ L + cr_r ] |
+                       rgb_2_pix[ L + crb_g ] |
+                       rgb_2_pix[ L + cb_b ]);
+
+
+            /* Now, do second row.  */
+
+            L = *lum2++;
+            *row2++ = (rgb_2_pix[ L + cr_r ] |
+                       rgb_2_pix[ L + crb_g ] |
+                       rgb_2_pix[ L + cb_b ]);
+
+            L = *lum2++;
+            *row2++ = (rgb_2_pix[ L + cr_r ] |
+                       rgb_2_pix[ L + crb_g ] |
+                       rgb_2_pix[ L + cb_b ]);
+        }
+
+        /*
+         * These values are at the start of the next line, (due
+         * to the ++'s above),but they need to be at the start
+         * of the line after that.
+         */
+        lum  += cols;
+        lum2 += cols;
+        row1 += mod;
+        row2 += mod;
+    }
+}
+
+/*
+ * In this function I make use of a nasty trick. The tables have the lower
+ * 16 bits replicated in the upper 16. This means I can write ints and get
+ * the horisontal doubling for free (almost).
+ */
+static void Color16DitherYV12Mod2X( int *colortab, Uint32 *rgb_2_pix,
+                                    unsigned char *lum, unsigned char *cr,
+                                    unsigned char *cb, unsigned char *out,
+                                    int rows, int cols, int mod )
+{
+    unsigned int* row1 = (unsigned int*) out;
+    const int next_row = cols+(mod/2);
+    unsigned int* row2 = row1 + 2*next_row;
+    unsigned char* lum2;
+    int x, y;
+    int cr_r;
+    int crb_g;
+    int cb_b;
+    int cols_2 = cols / 2;
+
+    lum2 = lum + cols;
+
+    mod = (next_row * 3) + (mod/2);
+
+    y = rows / 2;
+    while( y-- )
+    {
+        x = cols_2;
+        while( x-- )
+        {
+            register int L;
+
+            cr_r   = 0*768+256 + colortab[ *cr + 0*256 ];
+            crb_g  = 1*768+256 + colortab[ *cr + 1*256 ]
+                               + colortab[ *cb + 2*256 ];
+            cb_b   = 2*768+256 + colortab[ *cb + 3*256 ];
+            ++cr; ++cb;
+
+            L = *lum++;
+            row1[0] = row1[next_row] = (rgb_2_pix[ L + cr_r ] |
+                                        rgb_2_pix[ L + crb_g ] |
+                                        rgb_2_pix[ L + cb_b ]);
+            row1++;
+
+            L = *lum++;
+            row1[0] = row1[next_row] = (rgb_2_pix[ L + cr_r ] |
+                                        rgb_2_pix[ L + crb_g ] |
+                                        rgb_2_pix[ L + cb_b ]);
+            row1++;
+
+
+            /* Now, do second row. */
+
+            L = *lum2++;
+            row2[0] = row2[next_row] = (rgb_2_pix[ L + cr_r ] |
+                                        rgb_2_pix[ L + crb_g ] |
+                                        rgb_2_pix[ L + cb_b ]);
+            row2++;
+
+            L = *lum2++;
+            row2[0] = row2[next_row] = (rgb_2_pix[ L + cr_r ] |
+                                        rgb_2_pix[ L + crb_g ] |
+                                        rgb_2_pix[ L + cb_b ]);
+            row2++;
+        }
+
+        /*
+         * These values are at the start of the next line, (due
+         * to the ++'s above),but they need to be at the start
+         * of the line after that.
+         */
+        lum  += cols;
+        lum2 += cols;
+        row1 += mod;
+        row2 += mod;
+    }
+}
+
+static void Color24DitherYV12Mod2X( int *colortab, Uint32 *rgb_2_pix,
+                                    unsigned char *lum, unsigned char *cr,
+                                    unsigned char *cb, unsigned char *out,
+                                    int rows, int cols, int mod )
+{
+    unsigned int value;
+    unsigned char* row1 = out;
+    const int next_row = (cols*2 + mod) * 3;
+    unsigned char* row2 = row1 + 2*next_row;
+    unsigned char* lum2;
+    int x, y;
+    int cr_r;
+    int crb_g;
+    int cb_b;
+    int cols_2 = cols / 2;
+
+    lum2 = lum + cols;
+
+    mod = next_row*3 + mod*3;
+
+    y = rows / 2;
+    while( y-- )
+    {
+        x = cols_2;
+        while( x-- )
+        {
+            register int L;
+
+            cr_r   = 0*768+256 + colortab[ *cr + 0*256 ];
+            crb_g  = 1*768+256 + colortab[ *cr + 1*256 ]
+                               + colortab[ *cb + 2*256 ];
+            cb_b   = 2*768+256 + colortab[ *cb + 3*256 ];
+            ++cr; ++cb;
+
+            L = *lum++;
+            value = (rgb_2_pix[ L + cr_r ] |
+                     rgb_2_pix[ L + crb_g ] |
+                     rgb_2_pix[ L + cb_b ]);
+            row1[0+0] = row1[3+0] = row1[next_row+0] = row1[next_row+3+0] =
+                     (value      ) & 0xFF;
+            row1[0+1] = row1[3+1] = row1[next_row+1] = row1[next_row+3+1] =
+                     (value >>  8) & 0xFF;
+            row1[0+2] = row1[3+2] = row1[next_row+2] = row1[next_row+3+2] =
+                     (value >> 16) & 0xFF;
+            row1 += 2*3;
+
+            L = *lum++;
+            value = (rgb_2_pix[ L + cr_r ] |
+                     rgb_2_pix[ L + crb_g ] |
+                     rgb_2_pix[ L + cb_b ]);
+            row1[0+0] = row1[3+0] = row1[next_row+0] = row1[next_row+3+0] =
+                     (value      ) & 0xFF;
+            row1[0+1] = row1[3+1] = row1[next_row+1] = row1[next_row+3+1] =
+                     (value >>  8) & 0xFF;
+            row1[0+2] = row1[3+2] = row1[next_row+2] = row1[next_row+3+2] =
+                     (value >> 16) & 0xFF;
+            row1 += 2*3;
+
+
+            /* Now, do second row. */
+
+            L = *lum2++;
+            value = (rgb_2_pix[ L + cr_r ] |
+                     rgb_2_pix[ L + crb_g ] |
+                     rgb_2_pix[ L + cb_b ]);
+            row2[0+0] = row2[3+0] = row2[next_row+0] = row2[next_row+3+0] =
+                     (value      ) & 0xFF;
+            row2[0+1] = row2[3+1] = row2[next_row+1] = row2[next_row+3+1] =
+                     (value >>  8) & 0xFF;
+            row2[0+2] = row2[3+2] = row2[next_row+2] = row2[next_row+3+2] =
+                     (value >> 16) & 0xFF;
+            row2 += 2*3;
+
+            L = *lum2++;
+            value = (rgb_2_pix[ L + cr_r ] |
+                     rgb_2_pix[ L + crb_g ] |
+                     rgb_2_pix[ L + cb_b ]);
+            row2[0+0] = row2[3+0] = row2[next_row+0] = row2[next_row+3+0] =
+                     (value      ) & 0xFF;
+            row2[0+1] = row2[3+1] = row2[next_row+1] = row2[next_row+3+1] =
+                     (value >>  8) & 0xFF;
+            row2[0+2] = row2[3+2] = row2[next_row+2] = row2[next_row+3+2] =
+                     (value >> 16) & 0xFF;
+            row2 += 2*3;
+        }
+
+        /*
+         * These values are at the start of the next line, (due
+         * to the ++'s above),but they need to be at the start
+         * of the line after that.
+         */
+        lum  += cols;
+        lum2 += cols;
+        row1 += mod;
+        row2 += mod;
+    }
+}
+
+static void Color32DitherYV12Mod2X( int *colortab, Uint32 *rgb_2_pix,
+                                    unsigned char *lum, unsigned char *cr,
+                                    unsigned char *cb, unsigned char *out,
+                                    int rows, int cols, int mod )
+{
+    unsigned int* row1 = (unsigned int*) out;
+    const int next_row = cols*2+mod;
+    unsigned int* row2 = row1 + 2*next_row;
+    unsigned char* lum2;
+    int x, y;
+    int cr_r;
+    int crb_g;
+    int cb_b;
+    int cols_2 = cols / 2;
+
+    lum2 = lum + cols;
+
+    mod = (next_row * 3) + mod;
+
+    y = rows / 2;
+    while( y-- )
+    {
+        x = cols_2;
+        while( x-- )
+        {
+            register int L;
+
+            cr_r   = 0*768+256 + colortab[ *cr + 0*256 ];
+            crb_g  = 1*768+256 + colortab[ *cr + 1*256 ]
+                               + colortab[ *cb + 2*256 ];
+            cb_b   = 2*768+256 + colortab[ *cb + 3*256 ];
+            ++cr; ++cb;
+
+            L = *lum++;
+            row1[0] = row1[1] = row1[next_row] = row1[next_row+1] =
+                                       (rgb_2_pix[ L + cr_r ] |
+                                        rgb_2_pix[ L + crb_g ] |
+                                        rgb_2_pix[ L + cb_b ]);
+            row1 += 2;
+
+            L = *lum++;
+            row1[0] = row1[1] = row1[next_row] = row1[next_row+1] =
+                                       (rgb_2_pix[ L + cr_r ] |
+                                        rgb_2_pix[ L + crb_g ] |
+                                        rgb_2_pix[ L + cb_b ]);
+            row1 += 2;
+
+
+            /* Now, do second row. */
+
+            L = *lum2++;
+            row2[0] = row2[1] = row2[next_row] = row2[next_row+1] =
+                                       (rgb_2_pix[ L + cr_r ] |
+                                        rgb_2_pix[ L + crb_g ] |
+                                        rgb_2_pix[ L + cb_b ]);
+            row2 += 2;
+
+            L = *lum2++;
+            row2[0] = row2[1] = row2[next_row] = row2[next_row+1] =
+                                       (rgb_2_pix[ L + cr_r ] |
+                                        rgb_2_pix[ L + crb_g ] |
+                                        rgb_2_pix[ L + cb_b ]);
+            row2 += 2;
+        }
+
+        /*
+         * These values are at the start of the next line, (due
+         * to the ++'s above),but they need to be at the start
+         * of the line after that.
+         */
+        lum  += cols;
+        lum2 += cols;
+        row1 += mod;
+        row2 += mod;
+    }
+}
+
+static void Color16DitherYUY2Mod1X( int *colortab, Uint32 *rgb_2_pix,
+                                    unsigned char *lum, unsigned char *cr,
+                                    unsigned char *cb, unsigned char *out,
+                                    int rows, int cols, int mod )
+{
+    unsigned short* row;
+    int x, y;
+    int cr_r;
+    int crb_g;
+    int cb_b;
+    int cols_2 = cols / 2;
+
+    row = (unsigned short*) out;
+
+    y = rows;
+    while( y-- )
+    {
+        x = cols_2;
+        while( x-- )
+        {
+            register int L;
+
+            cr_r   = 0*768+256 + colortab[ *cr + 0*256 ];
+            crb_g  = 1*768+256 + colortab[ *cr + 1*256 ]
+                               + colortab[ *cb + 2*256 ];
+            cb_b   = 2*768+256 + colortab[ *cb + 3*256 ];
+            cr += 4; cb += 4;
+
+            L = *lum; lum += 2;
+            *row++ = (unsigned short)(rgb_2_pix[ L + cr_r ] |
+                                      rgb_2_pix[ L + crb_g ] |
+                                      rgb_2_pix[ L + cb_b ]);
+
+            L = *lum; lum += 2;
+            *row++ = (unsigned short)(rgb_2_pix[ L + cr_r ] |
+                                      rgb_2_pix[ L + crb_g ] |
+                                      rgb_2_pix[ L + cb_b ]);
+
+        }
+
+        row += mod;
+    }
+}
+
+static void Color24DitherYUY2Mod1X( int *colortab, Uint32 *rgb_2_pix,
+                                    unsigned char *lum, unsigned char *cr,
+                                    unsigned char *cb, unsigned char *out,
+                                    int rows, int cols, int mod )
+{
+    unsigned int value;
+    unsigned char* row;
+    int x, y;
+    int cr_r;
+    int crb_g;
+    int cb_b;
+    int cols_2 = cols / 2;
+
+    row = (unsigned char*) out;
+    mod *= 3;
+    y = rows;
+    while( y-- )
+    {
+        x = cols_2;
+        while( x-- )
+        {
+            register int L;
+
+            cr_r   = 0*768+256 + colortab[ *cr + 0*256 ];
+            crb_g  = 1*768+256 + colortab[ *cr + 1*256 ]
+                               + colortab[ *cb + 2*256 ];
+            cb_b   = 2*768+256 + colortab[ *cb + 3*256 ];
+            cr += 4; cb += 4;
+
+            L = *lum; lum += 2;
+            value = (rgb_2_pix[ L + cr_r ] |
+                     rgb_2_pix[ L + crb_g ] |
+                     rgb_2_pix[ L + cb_b ]);
+            *row++ = (value      ) & 0xFF;
+            *row++ = (value >>  8) & 0xFF;
+            *row++ = (value >> 16) & 0xFF;
+
+            L = *lum; lum += 2;
+            value = (rgb_2_pix[ L + cr_r ] |
+                     rgb_2_pix[ L + crb_g ] |
+                     rgb_2_pix[ L + cb_b ]);
+            *row++ = (value      ) & 0xFF;
+            *row++ = (value >>  8) & 0xFF;
+            *row++ = (value >> 16) & 0xFF;
+
+        }
+        row += mod;
+    }
+}
+
+static void Color32DitherYUY2Mod1X( int *colortab, Uint32 *rgb_2_pix,
+                                    unsigned char *lum, unsigned char *cr,
+                                    unsigned char *cb, unsigned char *out,
+                                    int rows, int cols, int mod )
+{
+    unsigned int* row;
+    int x, y;
+    int cr_r;
+    int crb_g;
+    int cb_b;
+    int cols_2 = cols / 2;
+
+    row = (unsigned int*) out;
+    y = rows;
+    while( y-- )
+    {
+        x = cols_2;
+        while( x-- )
+        {
+            register int L;
+
+            cr_r   = 0*768+256 + colortab[ *cr + 0*256 ];
+            crb_g  = 1*768+256 + colortab[ *cr + 1*256 ]
+                               + colortab[ *cb + 2*256 ];
+            cb_b   = 2*768+256 + colortab[ *cb + 3*256 ];
+            cr += 4; cb += 4;
+
+            L = *lum; lum += 2;
+            *row++ = (rgb_2_pix[ L + cr_r ] |
+                       rgb_2_pix[ L + crb_g ] |
+                       rgb_2_pix[ L + cb_b ]);
+
+            L = *lum; lum += 2;
+            *row++ = (rgb_2_pix[ L + cr_r ] |
+                       rgb_2_pix[ L + crb_g ] |
+                       rgb_2_pix[ L + cb_b ]);
+
+
+        }
+        row += mod;
+    }
+}
+
+/*
+ * In this function I make use of a nasty trick. The tables have the lower
+ * 16 bits replicated in the upper 16. This means I can write ints and get
+ * the horisontal doubling for free (almost).
+ */
+static void Color16DitherYUY2Mod2X( int *colortab, Uint32 *rgb_2_pix,
+                                    unsigned char *lum, unsigned char *cr,
+                                    unsigned char *cb, unsigned char *out,
+                                    int rows, int cols, int mod )
+{
+    unsigned int* row = (unsigned int*) out;
+    const int next_row = cols+(mod/2);
+    int x, y;
+    int cr_r;
+    int crb_g;
+    int cb_b;
+    int cols_2 = cols / 2;
+
+    y = rows;
+    while( y-- )
+    {
+        x = cols_2;
+        while( x-- )
+        {
+            register int L;
+
+            cr_r   = 0*768+256 + colortab[ *cr + 0*256 ];
+            crb_g  = 1*768+256 + colortab[ *cr + 1*256 ]
+                               + colortab[ *cb + 2*256 ];
+            cb_b   = 2*768+256 + colortab[ *cb + 3*256 ];
+            cr += 4; cb += 4;
+
+            L = *lum; lum += 2;
+            row[0] = row[next_row] = (rgb_2_pix[ L + cr_r ] |
+                                        rgb_2_pix[ L + crb_g ] |
+                                        rgb_2_pix[ L + cb_b ]);
+            row++;
+
+            L = *lum; lum += 2;
+            row[0] = row[next_row] = (rgb_2_pix[ L + cr_r ] |
+                                        rgb_2_pix[ L + crb_g ] |
+                                        rgb_2_pix[ L + cb_b ]);
+            row++;
+
+        }
+        row += next_row;
+    }
+}
+
+static void Color24DitherYUY2Mod2X( int *colortab, Uint32 *rgb_2_pix,
+                                    unsigned char *lum, unsigned char *cr,
+                                    unsigned char *cb, unsigned char *out,
+                                    int rows, int cols, int mod )
+{
+    unsigned int value;
+    unsigned char* row = out;
+    const int next_row = (cols*2 + mod) * 3;
+    int x, y;
+    int cr_r;
+    int crb_g;
+    int cb_b;
+    int cols_2 = cols / 2;
+    y = rows;
+    while( y-- )
+    {
+        x = cols_2;
+        while( x-- )
+        {
+            register int L;
+
+            cr_r   = 0*768+256 + colortab[ *cr + 0*256 ];
+            crb_g  = 1*768+256 + colortab[ *cr + 1*256 ]
+                               + colortab[ *cb + 2*256 ];
+            cb_b   = 2*768+256 + colortab[ *cb + 3*256 ];
+            cr += 4; cb += 4;
+
+            L = *lum; lum += 2;
+            value = (rgb_2_pix[ L + cr_r ] |
+                     rgb_2_pix[ L + crb_g ] |
+                     rgb_2_pix[ L + cb_b ]);
+            row[0+0] = row[3+0] = row[next_row+0] = row[next_row+3+0] =
+                     (value      ) & 0xFF;
+            row[0+1] = row[3+1] = row[next_row+1] = row[next_row+3+1] =
+                     (value >>  8) & 0xFF;
+            row[0+2] = row[3+2] = row[next_row+2] = row[next_row+3+2] =
+                     (value >> 16) & 0xFF;
+            row += 2*3;
+
+            L = *lum; lum += 2;
+            value = (rgb_2_pix[ L + cr_r ] |
+                     rgb_2_pix[ L + crb_g ] |
+                     rgb_2_pix[ L + cb_b ]);
+            row[0+0] = row[3+0] = row[next_row+0] = row[next_row+3+0] =
+                     (value      ) & 0xFF;
+            row[0+1] = row[3+1] = row[next_row+1] = row[next_row+3+1] =
+                     (value >>  8) & 0xFF;
+            row[0+2] = row[3+2] = row[next_row+2] = row[next_row+3+2] =
+                     (value >> 16) & 0xFF;
+            row += 2*3;
+
+        }
+        row += next_row;
+    }
+}
+
+static void Color32DitherYUY2Mod2X( int *colortab, Uint32 *rgb_2_pix,
+                                    unsigned char *lum, unsigned char *cr,
+                                    unsigned char *cb, unsigned char *out,
+                                    int rows, int cols, int mod )
+{
+    unsigned int* row = (unsigned int*) out;
+    const int next_row = cols*2+mod;
+    int x, y;
+    int cr_r;
+    int crb_g;
+    int cb_b;
+    int cols_2 = cols / 2;
+    mod+=mod;
+    y = rows;
+    while( y-- )
+    {
+        x = cols_2;
+        while( x-- )
+        {
+            register int L;
+
+            cr_r   = 0*768+256 + colortab[ *cr + 0*256 ];
+            crb_g  = 1*768+256 + colortab[ *cr + 1*256 ]
+                               + colortab[ *cb + 2*256 ];
+            cb_b   = 2*768+256 + colortab[ *cb + 3*256 ];
+            cr += 4; cb += 4;
+
+            L = *lum; lum += 2;
+            row[0] = row[1] = row[next_row] = row[next_row+1] =
+                                       (rgb_2_pix[ L + cr_r ] |
+                                        rgb_2_pix[ L + crb_g ] |
+                                        rgb_2_pix[ L + cb_b ]);
+            row += 2;
+
+            L = *lum; lum += 2;
+            row[0] = row[1] = row[next_row] = row[next_row+1] =
+                                       (rgb_2_pix[ L + cr_r ] |
+                                        rgb_2_pix[ L + crb_g ] |
+                                        rgb_2_pix[ L + cb_b ]);
+            row += 2;
+
+
+        }
+
+        row += next_row;
+    }
+}
+
+/*
+ * How many 1 bits are there in the Uint32.
+ * Low performance, do not call often.
+ */
+static int number_of_bits_set( Uint32 a )
+{
+    if(!a) return 0;
+    if(a & 1) return 1 + number_of_bits_set(a >> 1);
+    return(number_of_bits_set(a >> 1));
+}
+
+/*
+ * How many 0 bits are there at least significant end of Uint32.
+ * Low performance, do not call often.
+ */
+static int free_bits_at_bottom( Uint32 a )
+{
+      /* assume char is 8 bits */
+    if(!a) return sizeof(Uint32) * 8;
+    if(((Sint32)a) & 1l) return 0;
+    return 1 + free_bits_at_bottom ( a >> 1);
+}
+
+
+SDL_Overlay *SDL_CreateYUV_SW(_THIS, int width, int height, Uint32 format, SDL_Surface *display)
+{
+	SDL_Overlay *overlay;
+	struct private_yuvhwdata *swdata;
+	int *Cr_r_tab;
+	int *Cr_g_tab;
+	int *Cb_g_tab;
+	int *Cb_b_tab;
+	Uint32 *r_2_pix_alloc;
+	Uint32 *g_2_pix_alloc;
+	Uint32 *b_2_pix_alloc;
+	int i;
+	int CR, CB;
+	Uint32 Rmask, Gmask, Bmask;
+
+	/* Only RGB packed pixel conversion supported */
+	if ( (display->format->BytesPerPixel != 2) &&
+	     (display->format->BytesPerPixel != 3) &&
+	     (display->format->BytesPerPixel != 4) ) {
+		SDL_SetError("Can't use YUV data on non 16/24/32 bit surfaces");
+		return(NULL);
+	}
+
+	/* Verify that we support the format */
+	switch (format) {
+	    case SDL_YV12_OVERLAY:
+	    case SDL_IYUV_OVERLAY:
+	    case SDL_YUY2_OVERLAY:
+	    case SDL_UYVY_OVERLAY:
+	    case SDL_YVYU_OVERLAY:
+		break;
+	    default:
+		SDL_SetError("Unsupported YUV format");
+		return(NULL);
+	}
+
+	/* Create the overlay structure */
+	overlay = (SDL_Overlay *)SDL_malloc(sizeof *overlay);
+	if ( overlay == NULL ) {
+		SDL_OutOfMemory();
+		return(NULL);
+	}
+	SDL_memset(overlay, 0, (sizeof *overlay));
+
+	/* Fill in the basic members */
+	overlay->format = format;
+	overlay->w = width;
+	overlay->h = height;
+
+	/* Set up the YUV surface function structure */
+	overlay->hwfuncs = &sw_yuvfuncs;
+
+	/* Create the pixel data and lookup tables */
+	swdata = (struct private_yuvhwdata *)SDL_malloc(sizeof *swdata);
+	overlay->hwdata = swdata;
+	if ( swdata == NULL ) {
+		SDL_OutOfMemory();
+		SDL_FreeYUVOverlay(overlay);
+		return(NULL);
+	}
+	swdata->stretch = NULL;
+	swdata->display = display;
+	swdata->pixels = (Uint8 *) SDL_malloc(width*height*2);
+	swdata->colortab = (int *)SDL_malloc(4*256*sizeof(int));
+	Cr_r_tab = &swdata->colortab[0*256];
+	Cr_g_tab = &swdata->colortab[1*256];
+	Cb_g_tab = &swdata->colortab[2*256];
+	Cb_b_tab = &swdata->colortab[3*256];
+	swdata->rgb_2_pix = (Uint32 *)SDL_malloc(3*768*sizeof(Uint32));
+	r_2_pix_alloc = &swdata->rgb_2_pix[0*768];
+	g_2_pix_alloc = &swdata->rgb_2_pix[1*768];
+	b_2_pix_alloc = &swdata->rgb_2_pix[2*768];
+	if ( ! swdata->pixels || ! swdata->colortab || ! swdata->rgb_2_pix ) {
+		SDL_OutOfMemory();
+		SDL_FreeYUVOverlay(overlay);
+		return(NULL);
+	}
+
+	/* Generate the tables for the display surface */
+	for (i=0; i<256; i++) {
+		/* Gamma correction (luminescence table) and chroma correction
+		   would be done here.  See the Berkeley mpeg_play sources.
+		*/
+		CB = CR = (i-128);
+		Cr_r_tab[i] = (int) ( (0.419/0.299) * CR);
+		Cr_g_tab[i] = (int) (-(0.299/0.419) * CR);
+		Cb_g_tab[i] = (int) (-(0.114/0.331) * CB); 
+		Cb_b_tab[i] = (int) ( (0.587/0.331) * CB);
+	}
+
+	/* 
+	 * Set up entries 0-255 in rgb-to-pixel value tables.
+	 */
+	Rmask = display->format->Rmask;
+	Gmask = display->format->Gmask;
+	Bmask = display->format->Bmask;
+	for ( i=0; i<256; ++i ) {
+		r_2_pix_alloc[i+256] = i >> (8 - number_of_bits_set(Rmask));
+		r_2_pix_alloc[i+256] <<= free_bits_at_bottom(Rmask);
+		g_2_pix_alloc[i+256] = i >> (8 - number_of_bits_set(Gmask));
+		g_2_pix_alloc[i+256] <<= free_bits_at_bottom(Gmask);
+		b_2_pix_alloc[i+256] = i >> (8 - number_of_bits_set(Bmask));
+		b_2_pix_alloc[i+256] <<= free_bits_at_bottom(Bmask);
+	}
+
+	/*
+	 * If we have 16-bit output depth, then we double the value
+	 * in the top word. This means that we can write out both
+	 * pixels in the pixel doubling mode with one op. It is 
+	 * harmless in the normal case as storing a 32-bit value
+	 * through a short pointer will lose the top bits anyway.
+	 */
+	if( display->format->BytesPerPixel == 2 ) {
+		for ( i=0; i<256; ++i ) {
+			r_2_pix_alloc[i+256] |= (r_2_pix_alloc[i+256]) << 16;
+			g_2_pix_alloc[i+256] |= (g_2_pix_alloc[i+256]) << 16;
+			b_2_pix_alloc[i+256] |= (b_2_pix_alloc[i+256]) << 16;
+		}
+	}
+
+	/*
+	 * Spread out the values we have to the rest of the array so that
+	 * we do not need to check for overflow.
+	 */
+	for ( i=0; i<256; ++i ) {
+		r_2_pix_alloc[i] = r_2_pix_alloc[256];
+		r_2_pix_alloc[i+512] = r_2_pix_alloc[511];
+		g_2_pix_alloc[i] = g_2_pix_alloc[256];
+		g_2_pix_alloc[i+512] = g_2_pix_alloc[511];
+		b_2_pix_alloc[i] = b_2_pix_alloc[256];
+		b_2_pix_alloc[i+512] = b_2_pix_alloc[511];
+	}
+
+	/* You have chosen wisely... */
+	switch (format) {
+	    case SDL_YV12_OVERLAY:
+	    case SDL_IYUV_OVERLAY:
+		if ( display->format->BytesPerPixel == 2 ) {
+#if (__GNUC__ > 2) && defined(__i386__) && __OPTIMIZE__ && SDL_ASSEMBLY_ROUTINES
+			/* inline assembly functions */
+			if ( SDL_HasMMX() && (Rmask == 0xF800) &&
+			                     (Gmask == 0x07E0) &&
+				             (Bmask == 0x001F) &&
+			                     (width & 15) == 0) {
+/*printf("Using MMX 16-bit 565 dither\n");*/
+				swdata->Display1X = Color565DitherYV12MMX1X;
+			} else {
+/*printf("Using C 16-bit dither\n");*/
+				swdata->Display1X = Color16DitherYV12Mod1X;
+			}
+#else
+			swdata->Display1X = Color16DitherYV12Mod1X;
+#endif
+			swdata->Display2X = Color16DitherYV12Mod2X;
+		}
+		if ( display->format->BytesPerPixel == 3 ) {
+			swdata->Display1X = Color24DitherYV12Mod1X;
+			swdata->Display2X = Color24DitherYV12Mod2X;
+		}
+		if ( display->format->BytesPerPixel == 4 ) {
+#if (__GNUC__ > 2) && defined(__i386__) && __OPTIMIZE__ && SDL_ASSEMBLY_ROUTINES
+			/* inline assembly functions */
+			if ( SDL_HasMMX() && (Rmask == 0x00FF0000) &&
+			                     (Gmask == 0x0000FF00) &&
+				             (Bmask == 0x000000FF) && 
+			                     (width & 15) == 0) {
+/*printf("Using MMX 32-bit dither\n");*/
+				swdata->Display1X = ColorRGBDitherYV12MMX1X;
+			} else {
+/*printf("Using C 32-bit dither\n");*/
+				swdata->Display1X = Color32DitherYV12Mod1X;
+			}
+#else
+			swdata->Display1X = Color32DitherYV12Mod1X;
+#endif
+			swdata->Display2X = Color32DitherYV12Mod2X;
+		}
+		break;
+	    case SDL_YUY2_OVERLAY:
+	    case SDL_UYVY_OVERLAY:
+	    case SDL_YVYU_OVERLAY:
+		if ( display->format->BytesPerPixel == 2 ) {
+			swdata->Display1X = Color16DitherYUY2Mod1X;
+			swdata->Display2X = Color16DitherYUY2Mod2X;
+		}
+		if ( display->format->BytesPerPixel == 3 ) {
+			swdata->Display1X = Color24DitherYUY2Mod1X;
+			swdata->Display2X = Color24DitherYUY2Mod2X;
+		}
+		if ( display->format->BytesPerPixel == 4 ) {
+			swdata->Display1X = Color32DitherYUY2Mod1X;
+			swdata->Display2X = Color32DitherYUY2Mod2X;
+		}
+		break;
+	    default:
+		/* We should never get here (caught above) */
+		break;
+	}
+
+	/* Find the pitch and offset values for the overlay */
+	overlay->pitches = swdata->pitches;
+	overlay->pixels = swdata->planes;
+	switch (format) {
+	    case SDL_YV12_OVERLAY:
+	    case SDL_IYUV_OVERLAY:
+		overlay->pitches[0] = overlay->w;
+		overlay->pitches[1] = overlay->pitches[0] / 2;
+		overlay->pitches[2] = overlay->pitches[0] / 2;
+	        overlay->pixels[0] = swdata->pixels;
+	        overlay->pixels[1] = overlay->pixels[0] +
+		                     overlay->pitches[0] * overlay->h;
+	        overlay->pixels[2] = overlay->pixels[1] +
+		                     overlay->pitches[1] * overlay->h / 2;
+		overlay->planes = 3;
+		break;
+	    case SDL_YUY2_OVERLAY:
+	    case SDL_UYVY_OVERLAY:
+	    case SDL_YVYU_OVERLAY:
+		overlay->pitches[0] = overlay->w*2;
+	        overlay->pixels[0] = swdata->pixels;
+		overlay->planes = 1;
+		break;
+	    default:
+		/* We should never get here (caught above) */
+		break;
+	}
+
+	/* We're all done.. */
+	return(overlay);
+}
+
+int SDL_LockYUV_SW(_THIS, SDL_Overlay *overlay)
+{
+	return(0);
+}
+
+void SDL_UnlockYUV_SW(_THIS, SDL_Overlay *overlay)
+{
+	return;
+}
+
+int SDL_DisplayYUV_SW(_THIS, SDL_Overlay *overlay, SDL_Rect *src, SDL_Rect *dst)
+{
+	struct private_yuvhwdata *swdata;
+	int stretch;
+	int scale_2x;
+	SDL_Surface *display;
+	Uint8 *lum, *Cr, *Cb;
+	Uint8 *dstp;
+	int mod;
+
+	swdata = overlay->hwdata;
+	stretch = 0;
+	scale_2x = 0;
+	if ( src->x || src->y || src->w < overlay->w || src->h < overlay->h ) {
+		/* The source rectangle has been clipped.
+		   Using a scratch surface is easier than adding clipped
+		   source support to all the blitters, plus that would
+		   slow them down in the general unclipped case.
+		*/
+		stretch = 1;
+	} else if ( (src->w != dst->w) || (src->h != dst->h) ) {
+		if ( (dst->w == 2*src->w) &&
+		     (dst->h == 2*src->h) ) {
+			scale_2x = 1;
+		} else {
+			stretch = 1;
+		}
+	}
+	if ( stretch ) {
+		if ( ! swdata->stretch ) {
+			display = swdata->display;
+			swdata->stretch = SDL_CreateRGBSurface(
+				SDL_SWSURFACE,
+				overlay->w, overlay->h,
+				display->format->BitsPerPixel,
+				display->format->Rmask,
+				display->format->Gmask,
+				display->format->Bmask, 0);
+			if ( ! swdata->stretch ) {
+				return(-1);
+			}
+		}
+		display = swdata->stretch;
+	} else {
+		display = swdata->display;
+	}
+	switch (overlay->format) {
+	    case SDL_YV12_OVERLAY:
+		lum = overlay->pixels[0];
+		Cr =  overlay->pixels[1];
+		Cb =  overlay->pixels[2];
+		break;
+	    case SDL_IYUV_OVERLAY:
+		lum = overlay->pixels[0];
+		Cr =  overlay->pixels[2];
+		Cb =  overlay->pixels[1];
+		break;
+	    case SDL_YUY2_OVERLAY:
+		lum = overlay->pixels[0];
+		Cr = lum + 3;
+		Cb = lum + 1;
+		break;
+	    case SDL_UYVY_OVERLAY:
+		lum = overlay->pixels[0]+1;
+		Cr = lum + 1;
+		Cb = lum - 1;
+		break;
+	    case SDL_YVYU_OVERLAY:
+		lum = overlay->pixels[0];
+		Cr = lum + 1;
+		Cb = lum + 3;
+		break;
+	    default:
+		SDL_SetError("Unsupported YUV format in blit");
+		return(-1);
+	}
+	if ( SDL_MUSTLOCK(display) ) {
+        	if ( SDL_LockSurface(display) < 0 ) {
+			return(-1);
+		}
+	}
+	if ( stretch ) {
+		dstp = (Uint8 *)swdata->stretch->pixels;
+	} else {
+		dstp = (Uint8 *)display->pixels
+			+ dst->x * display->format->BytesPerPixel
+			+ dst->y * display->pitch;
+	}
+	mod = (display->pitch / display->format->BytesPerPixel);
+
+	if ( scale_2x ) {
+		mod -= (overlay->w * 2);
+		swdata->Display2X(swdata->colortab, swdata->rgb_2_pix,
+		                  lum, Cr, Cb, dstp, overlay->h, overlay->w, mod);
+	} else {
+		mod -= overlay->w;
+		swdata->Display1X(swdata->colortab, swdata->rgb_2_pix,
+		                  lum, Cr, Cb, dstp, overlay->h, overlay->w, mod);
+	}
+	if ( SDL_MUSTLOCK(display) ) {
+		SDL_UnlockSurface(display);
+	}
+	if ( stretch ) {
+		display = swdata->display;
+		SDL_SoftStretch(swdata->stretch, src, display, dst);
+	}
+	SDL_UpdateRects(display, 1, dst);
+
+	return(0);
+}
+
+void SDL_FreeYUV_SW(_THIS, SDL_Overlay *overlay)
+{
+	struct private_yuvhwdata *swdata;
+
+	swdata = overlay->hwdata;
+	if ( swdata ) {
+		if ( swdata->stretch ) {
+			SDL_FreeSurface(swdata->stretch);
+		}
+		if ( swdata->pixels ) {
+			SDL_free(swdata->pixels);
+		}
+		if ( swdata->colortab ) {
+			SDL_free(swdata->colortab);
+		}
+		if ( swdata->rgb_2_pix ) {
+			SDL_free(swdata->rgb_2_pix);
+		}
+		SDL_free(swdata);
+		overlay->hwdata = NULL;
+	}
+}
diff --git a/sources/packages/l/sdl/sdl/create-1.2.15-disable-mmx-patch/create.patch.sh b/sources/packages/l/sdl/sdl/create-1.2.15-disable-mmx-patch/create.patch.sh
new file mode 100755
index 000000000..d5667605f
--- /dev/null
+++ b/sources/packages/l/sdl/sdl/create-1.2.15-disable-mmx-patch/create.patch.sh
@@ -0,0 +1,15 @@
+#!/bin/sh
+
+VERSION=1.2.15
+
+tar --files-from=file.list -xzvf ../SDL-$VERSION.tar.gz
+mv SDL-$VERSION SDL-$VERSION-orig
+
+cp -rf ./SDL-$VERSION-new ./SDL-$VERSION
+
+diff -b --unified -Nr  SDL-$VERSION-orig  SDL-$VERSION > SDL-$VERSION-disable-mmx.patch
+
+mv SDL-$VERSION-disable-mmx.patch ../patches
+
+rm -rf ./SDL-$VERSION
+rm -rf ./SDL-$VERSION-orig
diff --git a/sources/packages/l/sdl/sdl/create-1.2.15-disable-mmx-patch/file.list b/sources/packages/l/sdl/sdl/create-1.2.15-disable-mmx-patch/file.list
new file mode 100644
index 000000000..0b04b4384
--- /dev/null
+++ b/sources/packages/l/sdl/sdl/create-1.2.15-disable-mmx-patch/file.list
@@ -0,0 +1 @@
+SDL-1.2.15/src/video/SDL_yuv_sw.c
diff --git a/sources/packages/l/sdl/sdl/create-1.2.15-joystick-axis-patch/SDL-1.2.15-new/src/joystick/linux/SDL_sysjoystick.c b/sources/packages/l/sdl/sdl/create-1.2.15-joystick-axis-patch/SDL-1.2.15-new/src/joystick/linux/SDL_sysjoystick.c
new file mode 100644
index 000000000..2b763139a
--- /dev/null
+++ b/sources/packages/l/sdl/sdl/create-1.2.15-joystick-axis-patch/SDL-1.2.15-new/src/joystick/linux/SDL_sysjoystick.c
@@ -0,0 +1,1221 @@
+/*
+    SDL - Simple DirectMedia Layer
+    Copyright (C) 1997-2012 Sam Lantinga
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+    Sam Lantinga
+    slouken@libsdl.org
+*/
+#include "SDL_config.h"
+
+#ifdef SDL_JOYSTICK_LINUX
+
+/* This is the system specific header for the SDL joystick API */
+
+#include <sys/stat.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <limits.h>		/* For the definition of PATH_MAX */
+#include <linux/joystick.h>
+#if SDL_INPUT_LINUXEV
+#include <linux/input.h>
+#endif
+
+#include "SDL_joystick.h"
+#include "../SDL_sysjoystick.h"
+#include "../SDL_joystick_c.h"
+
+/* Special joystick configurations */
+static struct {
+	const char *name;
+	int naxes;
+	int nhats;
+	int nballs;
+} special_joysticks[] = {
+	{ "MadCatz Panther XL", 3, 2, 1 }, /* We don't handle rudder (axis 8) */
+	{ "SideWinder Precision Pro", 4, 1, 0 },
+	{ "SideWinder 3D Pro", 4, 1, 0 },
+	{ "Microsoft SideWinder 3D Pro", 4, 1, 0 },
+	{ "Microsoft SideWinder Precision Pro", 4, 1, 0 },
+	{ "Microsoft SideWinder Dual Strike USB version 1.0", 2, 1, 0 },
+	{ "WingMan Interceptor", 3, 3, 0 },
+	{ "WingMan Extreme Digital 3D", 4, 1, 0 },
+	{ "Microsoft SideWinder Precision 2 Joystick", 4, 1, 0 },
+	{ "Logitech Inc. WingMan Extreme Digital 3D", 4, 1, 0 },
+	{ "Saitek Saitek X45", 6, 1, 0 }
+};
+
+/* It looks like newer kernels have the logical mapping at the driver level */
+#define NO_LOGICAL_JOYSTICKS
+
+#ifndef NO_LOGICAL_JOYSTICKS
+
+/*
+   Some USB HIDs show up as a single joystick even though they actually
+   control 2 or more joysticks.
+*/
+/*
+   This code handles the MP-8800 (Quad) and MP-8866 (Dual), which can
+   be identified by their transparent blue design. It's quite trivial
+   to add other joysticks with similar quirky behavior.
+   -id
+*/
+
+struct joystick_logical_mapping {
+        int njoy;
+        int nthing;
+};
+
+/*
+   {logical joy, logical axis},
+   {logical joy, logical hat},
+   {logical joy, logical ball},
+   {logical joy, logical button}
+*/
+
+static struct joystick_logical_mapping mp88xx_1_logical_axismap[] = {
+   {0,0},{0,1},{0,2},{0,3},{0,4},{0,5}
+};
+static struct joystick_logical_mapping mp88xx_1_logical_buttonmap[] = {
+   {0,0},{0,1},{0,2},{0,3},{0,4},{0,5},{0,6},{0,7},{0,8},{0,9},{0,10},{0,11}
+};
+
+static struct joystick_logical_mapping mp88xx_2_logical_axismap[] = {
+   {0,0},{0,1},{0,2},{1,0},{1,1},{0,3},
+   {1,2},{1,3},{0,4},{0,5},{1,4},{1,5}
+};
+static struct joystick_logical_mapping mp88xx_2_logical_buttonmap[] = {
+   {0,0},{0,1},{0,2},{0,3},{0,4},{0,5},{0,6},{0,7},{0,8},{0,9},{0,10},{0,11},
+   {1,0},{1,1},{1,2},{1,3},{1,4},{1,5},{1,6},{1,7},{1,8},{1,9},{1,10},{1,11}
+};
+
+static struct joystick_logical_mapping mp88xx_3_logical_axismap[] = {
+   {0,0},{0,1},{0,2},{1,0},{1,1},{0,3},
+   {1,2},{1,3},{2,0},{2,1},{2,2},{2,3},
+   {0,4},{0,5},{1,4},{1,5},{2,4},{2,5}
+};
+static struct joystick_logical_mapping mp88xx_3_logical_buttonmap[] = {
+   {0,0},{0,1},{0,2},{0,3},{0,4},{0,5},{0,6},{0,7},{0,8},{0,9},{0,10},{0,11},
+   {1,0},{1,1},{1,2},{1,3},{1,4},{1,5},{1,6},{1,7},{1,8},{1,9},{1,10},{1,11},
+   {2,0},{2,1},{2,2},{2,3},{2,4},{2,5},{2,6},{2,7},{2,8},{2,9},{2,10},{2,11}
+};
+
+static struct joystick_logical_mapping mp88xx_4_logical_axismap[] = {
+   {0,0},{0,1},{0,2},{1,0},{1,1},{0,3},
+   {1,2},{1,3},{2,0},{2,1},{2,2},{2,3},
+   {3,0},{3,1},{3,2},{3,3},{0,4},{0,5},
+   {1,4},{1,5},{2,4},{2,5},{3,4},{3,5}
+};
+static struct joystick_logical_mapping mp88xx_4_logical_buttonmap[] = {
+   {0,0},{0,1},{0,2},{0,3},{0,4},{0,5},{0,6},{0,7},{0,8},{0,9},{0,10},{0,11},
+   {1,0},{1,1},{1,2},{1,3},{1,4},{1,5},{1,6},{1,7},{1,8},{1,9},{1,10},{1,11},
+   {2,0},{2,1},{2,2},{2,3},{2,4},{2,5},{2,6},{2,7},{2,8},{2,9},{2,10},{2,11},
+   {3,0},{3,1},{3,2},{3,3},{3,4},{3,5},{3,6},{3,7},{3,8},{3,9},{3,10},{3,11}
+};
+
+struct joystick_logical_layout {
+        int naxes;
+        int nhats;
+        int nballs;
+        int nbuttons;
+};
+
+static struct joystick_logical_layout mp88xx_1_logical_layout[] = {
+        {6, 0, 0, 12}
+};
+static struct joystick_logical_layout mp88xx_2_logical_layout[] = {
+        {6, 0, 0, 12},
+        {6, 0, 0, 12}
+};
+static struct joystick_logical_layout mp88xx_3_logical_layout[] = {
+        {6, 0, 0, 12},
+        {6, 0, 0, 12},
+        {6, 0, 0, 12}
+};
+static struct joystick_logical_layout mp88xx_4_logical_layout[] = {
+        {6, 0, 0, 12},
+        {6, 0, 0, 12},
+        {6, 0, 0, 12},
+        {6, 0, 0, 12}
+};
+
+/*
+   This array sets up a means of mapping a single physical joystick to
+   multiple logical joysticks. (djm)
+                                                                                
+   njoys
+        the number of logical joysticks
+                                                                                
+   layouts
+        an array of layout structures, one to describe each logical joystick
+                                                                                
+   axes, hats, balls, buttons
+        arrays that map a physical thingy to a logical thingy
+ */
+struct joystick_logicalmap {
+        const char *name;
+	int nbuttons;
+        int njoys;
+        struct joystick_logical_layout *layout;
+        struct joystick_logical_mapping *axismap;
+        struct joystick_logical_mapping *hatmap;
+        struct joystick_logical_mapping *ballmap;
+        struct joystick_logical_mapping *buttonmap;
+};
+
+static struct joystick_logicalmap joystick_logicalmap[] = {
+        {
+		"WiseGroup.,Ltd MP-8866 Dual USB Joypad",
+		12,
+		1,
+		mp88xx_1_logical_layout,
+        	mp88xx_1_logical_axismap,
+		NULL,
+		NULL,
+        	mp88xx_1_logical_buttonmap
+	},
+        {
+		"WiseGroup.,Ltd MP-8866 Dual USB Joypad",
+		24,
+		2,
+		mp88xx_2_logical_layout,
+        	mp88xx_2_logical_axismap,
+		NULL,
+		NULL,
+        	mp88xx_2_logical_buttonmap
+	},
+        {
+		"WiseGroup.,Ltd MP-8800 Quad USB Joypad",
+		12,
+		1,
+		mp88xx_1_logical_layout,
+        	mp88xx_1_logical_axismap,
+		NULL,
+		NULL,
+        	mp88xx_1_logical_buttonmap
+	},
+        {
+		"WiseGroup.,Ltd MP-8800 Quad USB Joypad",
+		24,
+		2,
+		mp88xx_2_logical_layout,
+        	mp88xx_2_logical_axismap,
+		NULL,
+		NULL,
+        	mp88xx_2_logical_buttonmap
+	},
+        {
+		"WiseGroup.,Ltd MP-8800 Quad USB Joypad",
+		36,
+		3,
+		mp88xx_3_logical_layout,
+        	mp88xx_3_logical_axismap,
+		NULL,
+		NULL,
+        	mp88xx_3_logical_buttonmap
+	},
+        {
+		"WiseGroup.,Ltd MP-8800 Quad USB Joypad",
+		48,
+		4,
+		mp88xx_4_logical_layout,
+        	mp88xx_4_logical_axismap,
+		NULL,
+		NULL,
+        	mp88xx_4_logical_buttonmap
+	}
+};
+
+/* find the head of a linked list, given a point in it
+ */
+#define SDL_joylist_head(i, start)\
+        for(i = start; SDL_joylist[i].fname == NULL;) i = SDL_joylist[i].prev;
+
+#define SDL_logical_joydecl(d) d
+
+
+#else
+
+#define SDL_logical_joydecl(d)
+
+#endif /* USE_LOGICAL_JOYSTICKS */
+
+/* The maximum number of joysticks we'll detect */
+#define MAX_JOYSTICKS	32
+
+/* A list of available joysticks */
+static struct
+{
+        char* fname;
+#ifndef NO_LOGICAL_JOYSTICKS
+        SDL_Joystick* joy;
+        struct joystick_logicalmap* map;
+        int prev;
+        int next;
+        int logicalno;
+#endif /* USE_LOGICAL_JOYSTICKS */
+} SDL_joylist[MAX_JOYSTICKS];
+
+
+/* The private structure used to keep track of a joystick */
+struct joystick_hwdata {
+	int fd;
+	/* The current linux joystick driver maps hats to two axes */
+	struct hwdata_hat {
+		int axis[2];
+	} *hats;
+	/* The current linux joystick driver maps balls to two axes */
+	struct hwdata_ball {
+		int axis[2];
+	} *balls;
+
+	/* Support for the Linux 2.4 unified input interface */
+#if SDL_INPUT_LINUXEV
+	SDL_bool is_hid;
+	Uint8 key_map[KEY_MAX-BTN_MISC];
+	Uint8 abs_map[ABS_MAX];
+	struct axis_correct {
+		int used;
+		int coef[3];
+	} abs_correct[ABS_MAX];
+#endif
+};
+
+
+#ifndef NO_LOGICAL_JOYSTICKS
+
+static int CountLogicalJoysticks(int max)
+{
+   register int i, j, k, ret, prev;
+   const char* name;
+   int nbuttons, fd;
+   unsigned char n;
+
+   ret = 0;
+
+   for(i = 0; i < max; i++) {
+      name = SDL_SYS_JoystickName(i);
+	
+      fd = open(SDL_joylist[i].fname, O_RDONLY, 0);
+      if ( fd >= 0 ) {
+	 if ( ioctl(fd, JSIOCGBUTTONS, &n) < 0 ) {
+	    nbuttons = -1;
+	 } else {
+            nbuttons = n;
+	 }
+	 close(fd);
+      }
+      else {
+	 nbuttons=-1;
+      }
+
+      if (name) {
+         for(j = 0; j < SDL_arraysize(joystick_logicalmap); j++) {
+            if (!SDL_strcmp(name, joystick_logicalmap[j].name) && (nbuttons==-1 || nbuttons==joystick_logicalmap[j].nbuttons)) {
+               prev = i;
+               SDL_joylist[prev].map = &(joystick_logicalmap[j]);
+
+               for(k = 1; k < joystick_logicalmap[j].njoys; k++) {
+                  SDL_joylist[prev].next = max + ret;
+                  SDL_joylist[max+ret].prev = prev;
+		  
+                  prev = max + ret;
+                  SDL_joylist[prev].logicalno = k;
+                  SDL_joylist[prev].map = &(joystick_logicalmap[j]);
+                  ret++;
+               }
+
+               break;
+            }
+         }
+      }
+   }
+
+   return ret;
+}
+
+static void LogicalSuffix(int logicalno, char* namebuf, int len)
+{
+   register int slen;
+   const static char suffixs[] =
+      "01020304050607080910111213141516171819"
+      "20212223242526272829303132";
+   const char* suffix;
+   slen = SDL_strlen(namebuf);
+   suffix = NULL;
+
+   if (logicalno*2<sizeof(suffixs))
+      suffix = suffixs + (logicalno*2);
+
+   if (slen + 4 < len && suffix) {
+      namebuf[slen++] = ' ';
+      namebuf[slen++] = '#';
+      namebuf[slen++] = suffix[0];
+      namebuf[slen++] = suffix[1];
+      namebuf[slen++] = 0;
+   }
+}
+
+#endif /* USE_LOGICAL_JOYSTICKS */
+
+#if SDL_INPUT_LINUXEV
+#define test_bit(nr, addr) \
+	(((1UL << ((nr) % (sizeof(long) * 8))) & ((addr)[(nr) / (sizeof(long) * 8)])) != 0)
+#define NBITS(x) ((((x)-1)/(sizeof(long) * 8))+1)
+
+static int EV_IsJoystick(int fd)
+{
+	unsigned long evbit[NBITS(EV_MAX)] = { 0 };
+	unsigned long keybit[NBITS(KEY_MAX)] = { 0 };
+	unsigned long absbit[NBITS(ABS_MAX)] = { 0 };
+
+	if ( (ioctl(fd, EVIOCGBIT(0, sizeof(evbit)), evbit) < 0) ||
+	     (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) < 0) ||
+	     (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) < 0) ) {
+		return(0);
+	}
+	if (!(test_bit(EV_KEY, evbit) && test_bit(EV_ABS, evbit) &&
+	      test_bit(ABS_X, absbit) && test_bit(ABS_Y, absbit) &&
+	     (test_bit(BTN_TRIGGER, keybit) || test_bit(BTN_A, keybit) || test_bit(BTN_1, keybit)))) return 0;
+	return(1);
+}
+
+#endif /* SDL_INPUT_LINUXEV */
+
+/* Function to scan the system for joysticks */
+int SDL_SYS_JoystickInit(void)
+{
+	/* The base path of the joystick devices */
+	const char *joydev_pattern[] = {
+#if SDL_INPUT_LINUXEV
+		"/dev/input/event%d",
+#endif
+		"/dev/input/js%d",
+		"/dev/js%d"
+	};
+	int numjoysticks;
+	int i, j;
+	int fd;
+	char path[PATH_MAX];
+	dev_t dev_nums[MAX_JOYSTICKS];  /* major/minor device numbers */
+	struct stat sb;
+	int n, duplicate;
+
+	numjoysticks = 0;
+
+	/* First see if the user specified one or more joysticks to use */
+	if ( SDL_getenv("SDL_JOYSTICK_DEVICE") != NULL ) {
+		char *envcopy, *envpath, *delim;
+		envcopy = SDL_strdup(SDL_getenv("SDL_JOYSTICK_DEVICE"));
+		envpath = envcopy;
+		while ( envpath != NULL ) {
+			delim = SDL_strchr(envpath, ':');
+			if ( delim != NULL ) {
+				*delim++ = '\0';
+			}
+			if ( stat(envpath, &sb) == 0 ) {
+				fd = open(envpath, O_RDONLY, 0);
+				if ( fd >= 0 ) {
+					/* Assume the user knows what they're doing. */
+					SDL_joylist[numjoysticks].fname = SDL_strdup(envpath);
+					if ( SDL_joylist[numjoysticks].fname ) {
+						dev_nums[numjoysticks] = sb.st_rdev;
+						++numjoysticks;
+					}
+					close(fd);
+				}
+			}
+			envpath = delim;
+		}
+		SDL_free(envcopy);
+	}
+
+	for ( i=0; i<SDL_arraysize(joydev_pattern); ++i ) {
+		for ( j=0; j < MAX_JOYSTICKS; ++j ) {
+			SDL_snprintf(path, SDL_arraysize(path), joydev_pattern[i], j);
+
+			/* rcg06302000 replaced access(F_OK) call with stat().
+			 * stat() will fail if the file doesn't exist, so it's
+			 * equivalent behaviour.
+			 */
+			if ( stat(path, &sb) == 0 ) {
+				/* Check to make sure it's not already in list.
+				 * This happens when we see a stick via symlink.
+				 */
+				duplicate = 0;
+				for (n=0; (n<numjoysticks) && !duplicate; ++n) {
+					if ( sb.st_rdev == dev_nums[n] ) {
+						duplicate = 1;
+					}
+				}
+				if (duplicate) {
+					continue;
+				}
+
+				fd = open(path, O_RDONLY, 0);
+				if ( fd < 0 ) {
+					continue;
+				}
+#if SDL_INPUT_LINUXEV
+#ifdef DEBUG_INPUT_EVENTS
+				printf("Checking %s\n", path);
+#endif
+				if ( (i == 0) && ! EV_IsJoystick(fd) ) {
+					close(fd);
+					continue;
+				}
+#endif
+				close(fd);
+
+				/* We're fine, add this joystick */
+				SDL_joylist[numjoysticks].fname = SDL_strdup(path);
+				if ( SDL_joylist[numjoysticks].fname ) {
+					dev_nums[numjoysticks] = sb.st_rdev;
+					++numjoysticks;
+				}
+			}
+		}
+
+#if SDL_INPUT_LINUXEV
+		/* This is a special case...
+		   If the event devices are valid then the joystick devices
+		   will be duplicates but without extra information about their
+		   hats or balls. Unfortunately, the event devices can't
+		   currently be calibrated, so it's a win-lose situation.
+		   So : /dev/input/eventX = /dev/input/jsY = /dev/jsY
+		*/
+		if ( (i == 0) && (numjoysticks > 0) )
+			break;
+#endif
+	}
+#ifndef NO_LOGICAL_JOYSTICKS
+	numjoysticks += CountLogicalJoysticks(numjoysticks);
+#endif
+
+	return(numjoysticks);
+}
+
+/* Function to get the device-dependent name of a joystick */
+const char *SDL_SYS_JoystickName(int index)
+{
+	int fd;
+	static char namebuf[128];
+	char *name;
+	SDL_logical_joydecl(int oindex = index);
+
+#ifndef NO_LOGICAL_JOYSTICKS
+	SDL_joylist_head(index, index);
+#endif
+	name = NULL;
+	fd = open(SDL_joylist[index].fname, O_RDONLY, 0);
+	if ( fd >= 0 ) {
+		if ( 
+#if SDL_INPUT_LINUXEV
+		     (ioctl(fd, EVIOCGNAME(sizeof(namebuf)), namebuf) <= 0) &&
+#endif
+		     (ioctl(fd, JSIOCGNAME(sizeof(namebuf)), namebuf) <= 0) ) {
+			name = SDL_joylist[index].fname;
+		} else {
+			name = namebuf;
+		}
+		close(fd);
+
+
+#ifndef NO_LOGICAL_JOYSTICKS
+		if (SDL_joylist[oindex].prev || SDL_joylist[oindex].next || index!=oindex)
+		{
+       		   LogicalSuffix(SDL_joylist[oindex].logicalno, namebuf, 128);
+		}
+#endif
+	}
+	return name;
+}
+
+static int allocate_hatdata(SDL_Joystick *joystick)
+{
+	int i;
+
+	joystick->hwdata->hats = (struct hwdata_hat *)SDL_malloc(
+		joystick->nhats * sizeof(struct hwdata_hat));
+	if ( joystick->hwdata->hats == NULL ) {
+		return(-1);
+	}
+	for ( i=0; i<joystick->nhats; ++i ) {
+		joystick->hwdata->hats[i].axis[0] = 1;
+		joystick->hwdata->hats[i].axis[1] = 1;
+	}
+	return(0);
+}
+
+static int allocate_balldata(SDL_Joystick *joystick)
+{
+	int i;
+
+	joystick->hwdata->balls = (struct hwdata_ball *)SDL_malloc(
+		joystick->nballs * sizeof(struct hwdata_ball));
+	if ( joystick->hwdata->balls == NULL ) {
+		return(-1);
+	}
+	for ( i=0; i<joystick->nballs; ++i ) {
+		joystick->hwdata->balls[i].axis[0] = 0;
+		joystick->hwdata->balls[i].axis[1] = 0;
+	}
+	return(0);
+}
+
+static SDL_bool JS_ConfigJoystick(SDL_Joystick *joystick, int fd)
+{
+	SDL_bool handled;
+	unsigned char n;
+	int tmp_naxes, tmp_nhats, tmp_nballs;
+	const char *name;
+	char *env, env_name[128];
+	int i;
+
+	handled = SDL_FALSE;
+
+	/* Default joystick device settings */
+	if ( ioctl(fd, JSIOCGAXES, &n) < 0 ) {
+		joystick->naxes = 2;
+	} else {
+		joystick->naxes = n;
+	}
+	if ( ioctl(fd, JSIOCGBUTTONS, &n) < 0 ) {
+		joystick->nbuttons = 2;
+	} else {
+		joystick->nbuttons = n;
+	}
+
+	name = SDL_SYS_JoystickName(joystick->index);
+
+	/* Generic analog joystick support */
+	if ( SDL_strstr(name, "Analog") == name && SDL_strstr(name, "-hat") ) {
+		if ( SDL_sscanf(name,"Analog %d-axis %*d-button %d-hat",
+			&tmp_naxes, &tmp_nhats) == 2 ) {
+
+			joystick->naxes = tmp_naxes;
+			joystick->nhats = tmp_nhats;
+
+			handled = SDL_TRUE;
+		}
+	}
+
+	/* Special joystick support */
+	for ( i=0; i < SDL_arraysize(special_joysticks); ++i ) {
+		if ( SDL_strcmp(name, special_joysticks[i].name) == 0 ) {
+
+			joystick->naxes = special_joysticks[i].naxes;
+			joystick->nhats = special_joysticks[i].nhats;
+			joystick->nballs = special_joysticks[i].nballs;
+
+			handled = SDL_TRUE;
+			break;
+		}
+	}
+
+	/* User environment joystick support */
+	if ( (env = SDL_getenv("SDL_LINUX_JOYSTICK")) ) {
+		*env_name = '\0';
+		if ( *env == '\'' && SDL_sscanf(env, "'%[^']s'", env_name) == 1 )
+			env += SDL_strlen(env_name)+2;
+		else if ( SDL_sscanf(env, "%s", env_name) == 1 )
+			env += SDL_strlen(env_name);
+
+		if ( SDL_strcmp(name, env_name) == 0 ) {
+
+			if ( SDL_sscanf(env, "%d %d %d", &tmp_naxes, &tmp_nhats,
+				&tmp_nballs) == 3 ) {
+
+				joystick->naxes = tmp_naxes;
+				joystick->nhats = tmp_nhats;
+				joystick->nballs = tmp_nballs;
+
+				handled = SDL_TRUE;
+			}
+		}
+	}
+
+	/* Remap hats and balls */
+	if (handled) {
+		if ( joystick->nhats > 0 ) {
+			if ( allocate_hatdata(joystick) < 0 ) {
+				joystick->nhats = 0;
+			}
+		}
+		if ( joystick->nballs > 0 ) {
+			if ( allocate_balldata(joystick) < 0 ) {
+				joystick->nballs = 0;
+			}
+		}
+	}
+
+	return(handled);
+}
+
+#if SDL_INPUT_LINUXEV
+
+static SDL_bool EV_ConfigJoystick(SDL_Joystick *joystick, int fd)
+{
+	int i, t;
+	unsigned long keybit[NBITS(KEY_MAX)] = { 0 };
+	unsigned long absbit[NBITS(ABS_MAX)] = { 0 };
+	unsigned long relbit[NBITS(REL_MAX)] = { 0 };
+
+	/* See if this device uses the new unified event API */
+	if ( (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybit)), keybit) >= 0) &&
+	     (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(absbit)), absbit) >= 0) &&
+	     (ioctl(fd, EVIOCGBIT(EV_REL, sizeof(relbit)), relbit) >= 0) ) {
+		joystick->hwdata->is_hid = SDL_TRUE;
+
+		/* Get the number of buttons, axes, and other thingamajigs */
+		for ( i=BTN_JOYSTICK; i < KEY_MAX; ++i ) {
+			if ( test_bit(i, keybit) ) {
+#ifdef DEBUG_INPUT_EVENTS
+				printf("Joystick has button: 0x%x\n", i);
+#endif
+				joystick->hwdata->key_map[i-BTN_MISC] =
+						joystick->nbuttons;
+				++joystick->nbuttons;
+			}
+		}
+		for ( i=BTN_MISC; i < BTN_JOYSTICK; ++i ) {
+			if ( test_bit(i, keybit) ) {
+#ifdef DEBUG_INPUT_EVENTS
+				printf("Joystick has button: 0x%x\n", i);
+#endif
+				joystick->hwdata->key_map[i-BTN_MISC] =
+						joystick->nbuttons;
+				++joystick->nbuttons;
+			}
+		}
+		for ( i=0; i<ABS_MISC; ++i ) {
+			/* Skip hats */
+			if ( i == ABS_HAT0X ) {
+				i = ABS_HAT3Y;
+				continue;
+			}
+			if ( test_bit(i, absbit) ) {
+				struct input_absinfo absinfo;
+
+				if ( ioctl(fd, EVIOCGABS(i), &absinfo) < 0 )
+					continue;
+#ifdef DEBUG_INPUT_EVENTS
+				printf("Joystick has absolute axis: %x\n", i);
+				printf("Values = { %d, %d, %d, %d, %d }\n",
+					absinfo.value, absinfo.minimum,
+					absinfo.maximum, absinfo.fuzz, absinfo.flat);
+#endif /* DEBUG_INPUT_EVENTS */
+				joystick->hwdata->abs_map[i] = joystick->naxes;
+				if ( absinfo.minimum == absinfo.maximum ) {
+				    joystick->hwdata->abs_correct[i].used = 0;
+				} else {
+				    joystick->hwdata->abs_correct[i].used = 1;
+				    joystick->hwdata->abs_correct[i].coef[0] =
+					(absinfo.maximum + absinfo.minimum) / 2 - absinfo.flat;
+				    joystick->hwdata->abs_correct[i].coef[1] =
+					(absinfo.maximum + absinfo.minimum) / 2 + absinfo.flat;
+				    t = ((absinfo.maximum - absinfo.minimum) / 2 - 2 * absinfo.flat);
+				    if ( t != 0 ) {
+					joystick->hwdata->abs_correct[i].coef[2] = (1 << 29) / t;
+				    } else {
+					joystick->hwdata->abs_correct[i].coef[2] = 0;
+				    }
+				}
+				++joystick->naxes;
+			}
+		}
+		for ( i=ABS_HAT0X; i <= ABS_HAT3Y; i += 2 ) {
+			if ( test_bit(i, absbit) || test_bit(i+1, absbit) ) {
+#ifdef DEBUG_INPUT_EVENTS
+				printf("Joystick has hat %d\n",(i-ABS_HAT0X)/2);
+#endif
+				++joystick->nhats;
+			}
+		}
+		if ( test_bit(REL_X, relbit) || test_bit(REL_Y, relbit) ) {
+			++joystick->nballs;
+		}
+
+		/* Allocate data to keep track of these thingamajigs */
+		if ( joystick->nhats > 0 ) {
+			if ( allocate_hatdata(joystick) < 0 ) {
+				joystick->nhats = 0;
+			}
+		}
+		if ( joystick->nballs > 0 ) {
+			if ( allocate_balldata(joystick) < 0 ) {
+				joystick->nballs = 0;
+			}
+		}
+	}
+	return(joystick->hwdata->is_hid);
+}
+
+#endif /* SDL_INPUT_LINUXEV */
+
+#ifndef NO_LOGICAL_JOYSTICKS
+static void ConfigLogicalJoystick(SDL_Joystick *joystick)
+{
+        struct joystick_logical_layout* layout;
+                                                                                
+        layout = SDL_joylist[joystick->index].map->layout +
+                SDL_joylist[joystick->index].logicalno;
+                                                                                
+        joystick->nbuttons = layout->nbuttons;
+        joystick->nhats = layout->nhats;
+        joystick->naxes = layout->naxes;
+        joystick->nballs = layout->nballs;
+}
+#endif
+
+
+/* Function to open a joystick for use.
+   The joystick to open is specified by the index field of the joystick.
+   This should fill the nbuttons and naxes fields of the joystick structure.
+   It returns 0, or -1 if there is an error.
+ */
+int SDL_SYS_JoystickOpen(SDL_Joystick *joystick)
+{
+	int fd;
+	SDL_logical_joydecl(int realindex);
+	SDL_logical_joydecl(SDL_Joystick *realjoy = NULL);
+
+	/* Open the joystick and set the joystick file descriptor */
+#ifndef NO_LOGICAL_JOYSTICKS
+	if (SDL_joylist[joystick->index].fname == NULL) {
+		SDL_joylist_head(realindex, joystick->index);
+		realjoy = SDL_JoystickOpen(realindex);
+
+		if (realjoy == NULL)
+			return(-1);
+                                                                                
+		fd = realjoy->hwdata->fd;
+
+	} else {
+		fd = open(SDL_joylist[joystick->index].fname, O_RDONLY, 0);
+	}
+	SDL_joylist[joystick->index].joy = joystick;
+#else
+	fd = open(SDL_joylist[joystick->index].fname, O_RDONLY, 0);
+#endif
+
+	if ( fd < 0 ) {
+		SDL_SetError("Unable to open %s\n",
+		             SDL_joylist[joystick->index]);
+		return(-1);
+	}
+	joystick->hwdata = (struct joystick_hwdata *)
+	                   SDL_malloc(sizeof(*joystick->hwdata));
+	if ( joystick->hwdata == NULL ) {
+		SDL_OutOfMemory();
+		close(fd);
+		return(-1);
+	}
+	SDL_memset(joystick->hwdata, 0, sizeof(*joystick->hwdata));
+	joystick->hwdata->fd = fd;
+
+	/* Set the joystick to non-blocking read mode */
+	fcntl(fd, F_SETFL, O_NONBLOCK);
+
+	/* Get the number of buttons and axes on the joystick */
+#ifndef NO_LOGICAL_JOYSTICKS
+	if (realjoy)
+		ConfigLogicalJoystick(joystick);
+	else
+#endif
+#if SDL_INPUT_LINUXEV
+	if ( ! EV_ConfigJoystick(joystick, fd) )
+#endif
+		JS_ConfigJoystick(joystick, fd);
+
+	return(0);
+}
+
+#ifndef NO_LOGICAL_JOYSTICKS
+
+static SDL_Joystick* FindLogicalJoystick(
+   SDL_Joystick *joystick, struct joystick_logical_mapping* v)
+{
+        SDL_Joystick *logicaljoy;
+        register int i;
+
+        i = joystick->index;
+        logicaljoy = NULL;
+
+        /* get the fake joystick that will receive the event
+         */
+        for(;;) {
+
+           if (SDL_joylist[i].logicalno == v->njoy) {
+              logicaljoy = SDL_joylist[i].joy;
+              break;
+           }
+
+           if (SDL_joylist[i].next == 0)
+              break;
+
+           i = SDL_joylist[i].next;
+
+        }
+
+        return logicaljoy;
+}
+
+static int LogicalJoystickButton(
+   SDL_Joystick *joystick, Uint8 button, Uint8 state){
+        struct joystick_logical_mapping* buttons;
+        SDL_Joystick *logicaljoy = NULL;
+
+        /* if there's no map then this is just a regular joystick
+         */
+        if (SDL_joylist[joystick->index].map == NULL)
+           return 0;
+
+        /* get the logical joystick that will receive the event
+         */
+        buttons = SDL_joylist[joystick->index].map->buttonmap+button;
+        logicaljoy = FindLogicalJoystick(joystick, buttons);
+
+        if (logicaljoy == NULL)
+           return 1;
+
+        SDL_PrivateJoystickButton(logicaljoy, buttons->nthing, state);
+
+        return 1;
+}
+
+static int LogicalJoystickAxis(
+	SDL_Joystick *joystick, Uint8 axis, Sint16 value)
+{
+        struct joystick_logical_mapping* axes;
+        SDL_Joystick *logicaljoy = NULL;
+
+        /* if there's no map then this is just a regular joystick
+         */
+        if (SDL_joylist[joystick->index].map == NULL)
+           return 0;
+
+        /* get the logical joystick that will receive the event
+         */
+        axes = SDL_joylist[joystick->index].map->axismap+axis;
+        logicaljoy = FindLogicalJoystick(joystick, axes);
+
+        if (logicaljoy == NULL)
+           return 1;
+
+        SDL_PrivateJoystickAxis(logicaljoy, axes->nthing, value);
+
+        return 1;
+}
+#endif /* USE_LOGICAL_JOYSTICKS */
+
+static __inline__
+void HandleHat(SDL_Joystick *stick, Uint8 hat, int axis, int value)
+{
+	struct hwdata_hat *the_hat;
+	const Uint8 position_map[3][3] = {
+		{ SDL_HAT_LEFTUP, SDL_HAT_UP, SDL_HAT_RIGHTUP },
+		{ SDL_HAT_LEFT, SDL_HAT_CENTERED, SDL_HAT_RIGHT },
+		{ SDL_HAT_LEFTDOWN, SDL_HAT_DOWN, SDL_HAT_RIGHTDOWN }
+	};
+	SDL_logical_joydecl(SDL_Joystick *logicaljoy = NULL);
+	SDL_logical_joydecl(struct joystick_logical_mapping* hats = NULL);
+
+	if (stick->nhats <= hat) {
+		return;  /* whoops, that shouldn't happen! */
+	}
+
+	the_hat = &stick->hwdata->hats[hat];
+	if ( value < 0 ) {
+		value = 0;
+	} else
+	if ( value == 0 ) {
+		value = 1;
+	} else
+	if ( value > 0 ) {
+		value = 2;
+	}
+	if ( value != the_hat->axis[axis] ) {
+		the_hat->axis[axis] = value;
+
+#ifndef NO_LOGICAL_JOYSTICKS
+		/* if there's no map then this is just a regular joystick
+		*/
+		if (SDL_joylist[stick->index].map != NULL) {
+
+			/* get the fake joystick that will receive the event
+			*/
+			hats = SDL_joylist[stick->index].map->hatmap+hat;
+			logicaljoy = FindLogicalJoystick(stick, hats);
+		}
+
+		if (logicaljoy) {
+			stick = logicaljoy;
+			hat = hats->nthing;
+		}
+#endif /* USE_LOGICAL_JOYSTICKS */
+
+		SDL_PrivateJoystickHat(stick, hat,
+			position_map[the_hat->axis[1]][the_hat->axis[0]]);
+	}
+}
+
+static __inline__
+void HandleBall(SDL_Joystick *stick, Uint8 ball, int axis, int value)
+{
+	if ((stick->nballs <= ball) || (axis >= 2)) {
+		return;  /* whoops, that shouldn't happen! */
+	}
+	stick->hwdata->balls[ball].axis[axis] += value;
+}
+
+/* Function to update the state of a joystick - called as a device poll.
+ * This function shouldn't update the joystick structure directly,
+ * but instead should call SDL_PrivateJoystick*() to deliver events
+ * and update joystick device state.
+ */
+static __inline__ void JS_HandleEvents(SDL_Joystick *joystick)
+{
+	struct js_event events[32];
+	int i, len;
+	Uint8 other_axis;
+
+#ifndef NO_LOGICAL_JOYSTICKS
+	if (SDL_joylist[joystick->index].fname == NULL) {
+		SDL_joylist_head(i, joystick->index);
+		JS_HandleEvents(SDL_joylist[i].joy);
+		return;
+	}
+#endif
+
+	while ((len=read(joystick->hwdata->fd, events, (sizeof events))) > 0) {
+		len /= sizeof(events[0]);
+		for ( i=0; i<len; ++i ) {
+			switch (events[i].type & ~JS_EVENT_INIT) {
+			    case JS_EVENT_AXIS:
+				if ( events[i].number < joystick->naxes ) {
+#ifndef NO_LOGICAL_JOYSTICKS
+					if (!LogicalJoystickAxis(joystick,
+				           events[i].number, events[i].value))
+#endif
+					SDL_PrivateJoystickAxis(joystick,
+				           events[i].number, events[i].value);
+					break;
+				}
+				events[i].number -= joystick->naxes;
+				other_axis = (events[i].number / 2);
+				if ( other_axis < joystick->nhats ) {
+					HandleHat(joystick, other_axis,
+						events[i].number%2,
+						events[i].value);
+					break;
+				}
+				events[i].number -= joystick->nhats*2;
+				other_axis = (events[i].number / 2);
+				if ( other_axis < joystick->nballs ) {
+					HandleBall(joystick, other_axis,
+						events[i].number%2,
+						events[i].value);
+					break;
+				}
+				break;
+			    case JS_EVENT_BUTTON:
+#ifndef NO_LOGICAL_JOYSTICKS
+				if (!LogicalJoystickButton(joystick,
+				           events[i].number, events[i].value))
+#endif
+				SDL_PrivateJoystickButton(joystick,
+				           events[i].number, events[i].value);
+				break;
+			    default:
+				/* ?? */
+				break;
+			}
+		}
+	}
+}
+#if SDL_INPUT_LINUXEV
+static __inline__ int EV_AxisCorrect(SDL_Joystick *joystick, int which, int value)
+{
+	struct axis_correct *correct;
+
+	correct = &joystick->hwdata->abs_correct[which];
+	if ( correct->used ) {
+		if ( value > correct->coef[0] ) {
+			if ( value < correct->coef[1] ) {
+				return 0;
+			}
+			value -= correct->coef[1];
+		} else {
+			value -= correct->coef[0];
+		}
+		value *= correct->coef[2];
+		value >>= 14;
+	}
+
+	/* Clamp and return */
+	if ( value < -32768 ) return -32768;
+	if ( value >  32767 ) return  32767;
+
+	return value;
+}
+
+static __inline__ void EV_HandleEvents(SDL_Joystick *joystick)
+{
+	struct input_event events[32];
+	int i, len;
+	int code;
+
+#ifndef NO_LOGICAL_JOYSTICKS
+	if (SDL_joylist[joystick->index].fname == NULL) {
+		SDL_joylist_head(i, joystick->index);
+		return EV_HandleEvents(SDL_joylist[i].joy);
+	}
+#endif
+
+	while ((len=read(joystick->hwdata->fd, events, (sizeof events))) > 0) {
+		len /= sizeof(events[0]);
+		for ( i=0; i<len; ++i ) {
+			code = events[i].code;
+			switch (events[i].type) {
+			    case EV_KEY:
+				if ( code >= BTN_MISC ) {
+					code -= BTN_MISC;
+#ifndef NO_LOGICAL_JOYSTICKS
+					if (!LogicalJoystickButton(joystick,
+				           joystick->hwdata->key_map[code],
+					   events[i].value))
+#endif
+					SDL_PrivateJoystickButton(joystick,
+				           joystick->hwdata->key_map[code],
+					   events[i].value);
+				}
+				break;
+			    case EV_ABS:
+				if (code > ABS_MISC) {
+					break;
+				}
+				switch (code) {
+				    case ABS_HAT0X:
+				    case ABS_HAT0Y:
+				    case ABS_HAT1X:
+				    case ABS_HAT1Y:
+				    case ABS_HAT2X:
+				    case ABS_HAT2Y:
+				    case ABS_HAT3X:
+				    case ABS_HAT3Y:
+					code -= ABS_HAT0X;
+					HandleHat(joystick, code/2, code%2,
+							events[i].value);
+					break;
+				    default:
+					events[i].value = EV_AxisCorrect(joystick, code, events[i].value);
+#ifndef NO_LOGICAL_JOYSTICKS
+					if (!LogicalJoystickAxis(joystick,
+				           joystick->hwdata->abs_map[code],
+					   events[i].value))
+#endif
+					SDL_PrivateJoystickAxis(joystick,
+				           joystick->hwdata->abs_map[code],
+					   events[i].value);
+					break;
+				}
+				break;
+			    case EV_REL:
+				switch (code) {
+				    case REL_X:
+				    case REL_Y:
+					code -= REL_X;
+					HandleBall(joystick, code/2, code%2,
+							events[i].value);
+					break;
+				    default:
+					break;
+				}
+				break;
+			    default:
+				break;
+			}
+		}
+	}
+}
+#endif /* SDL_INPUT_LINUXEV */
+
+void SDL_SYS_JoystickUpdate(SDL_Joystick *joystick)
+{
+	int i;
+	
+#if SDL_INPUT_LINUXEV
+	if ( joystick->hwdata->is_hid )
+		EV_HandleEvents(joystick);
+	else
+#endif
+		JS_HandleEvents(joystick);
+
+	/* Deliver ball motion updates */
+	for ( i=0; i<joystick->nballs; ++i ) {
+		int xrel, yrel;
+
+		xrel = joystick->hwdata->balls[i].axis[0];
+		yrel = joystick->hwdata->balls[i].axis[1];
+		if ( xrel || yrel ) {
+			joystick->hwdata->balls[i].axis[0] = 0;
+			joystick->hwdata->balls[i].axis[1] = 0;
+			SDL_PrivateJoystickBall(joystick, (Uint8)i, xrel, yrel);
+		}
+	}
+}
+
+/* Function to close a joystick after use */
+void SDL_SYS_JoystickClose(SDL_Joystick *joystick)
+{
+#ifndef NO_LOGICAL_JOYSTICKS
+	register int i;
+	if (SDL_joylist[joystick->index].fname == NULL) {
+		SDL_joylist_head(i, joystick->index);
+		SDL_JoystickClose(SDL_joylist[i].joy);
+	}
+#endif
+
+	if ( joystick->hwdata ) {
+#ifndef NO_LOGICAL_JOYSTICKS
+		if (SDL_joylist[joystick->index].fname != NULL)
+#endif
+		close(joystick->hwdata->fd);
+		if ( joystick->hwdata->hats ) {
+			SDL_free(joystick->hwdata->hats);
+		}
+		if ( joystick->hwdata->balls ) {
+			SDL_free(joystick->hwdata->balls);
+		}
+		SDL_free(joystick->hwdata);
+		joystick->hwdata = NULL;
+	}
+}
+
+/* Function to perform any system-specific joystick related cleanup */
+void SDL_SYS_JoystickQuit(void)
+{
+	int i;
+
+	for ( i=0; SDL_joylist[i].fname; ++i ) {
+		SDL_free(SDL_joylist[i].fname);
+		SDL_joylist[i].fname = NULL;
+	}
+}
+
+#endif /* SDL_JOYSTICK_LINUX */
diff --git a/sources/packages/l/sdl/sdl/create-1.2.15-joystick-axis-patch/create.patch.sh b/sources/packages/l/sdl/sdl/create-1.2.15-joystick-axis-patch/create.patch.sh
new file mode 100755
index 000000000..132e8f325
--- /dev/null
+++ b/sources/packages/l/sdl/sdl/create-1.2.15-joystick-axis-patch/create.patch.sh
@@ -0,0 +1,15 @@
+#!/bin/sh
+
+VERSION=1.2.15
+
+tar --files-from=file.list -xzvf ../SDL-$VERSION.tar.gz
+mv SDL-$VERSION SDL-$VERSION-orig
+
+cp -rf ./SDL-$VERSION-new ./SDL-$VERSION
+
+diff -b --unified -Nr  SDL-$VERSION-orig  SDL-$VERSION > SDL-$VERSION-joystick-axis.patch
+
+mv SDL-$VERSION-joystick-axis.patch ../patches
+
+rm -rf ./SDL-$VERSION
+rm -rf ./SDL-$VERSION-orig
diff --git a/sources/packages/l/sdl/sdl/create-1.2.15-joystick-axis-patch/file.list b/sources/packages/l/sdl/sdl/create-1.2.15-joystick-axis-patch/file.list
new file mode 100644
index 000000000..3d36ff92c
--- /dev/null
+++ b/sources/packages/l/sdl/sdl/create-1.2.15-joystick-axis-patch/file.list
@@ -0,0 +1 @@
+SDL-1.2.15/src/joystick/linux/SDL_sysjoystick.c
diff --git a/sources/packages/l/sdl/sdl/create-1.2.15-x11-XData32-patch/SDL-1.2.15-new/src/video/x11/SDL_x11sym.h b/sources/packages/l/sdl/sdl/create-1.2.15-x11-XData32-patch/SDL-1.2.15-new/src/video/x11/SDL_x11sym.h
new file mode 100644
index 000000000..cc58bd435
--- /dev/null
+++ b/sources/packages/l/sdl/sdl/create-1.2.15-x11-XData32-patch/SDL-1.2.15-new/src/video/x11/SDL_x11sym.h
@@ -0,0 +1,201 @@
+/*
+    SDL - Simple DirectMedia Layer
+    Copyright (C) 1997-2012 Sam Lantinga
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Library General Public
+    License as published by the Free Software Foundation; either
+    version 2 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Library General Public License for more details.
+
+    You should have received a copy of the GNU Library General Public
+    License along with this library; if not, write to the Free
+    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+    Sam Lantinga
+    slouken@libsdl.org
+*/
+
+SDL_X11_MODULE(BASEXLIB)
+SDL_X11_SYM(XClassHint*,XAllocClassHint,(void),(),return)
+SDL_X11_SYM(Status,XAllocColor,(Display* a,Colormap b,XColor* c),(a,b,c),return)
+SDL_X11_SYM(XSizeHints*,XAllocSizeHints,(void),(),return)
+SDL_X11_SYM(XWMHints*,XAllocWMHints,(void),(),return)
+SDL_X11_SYM(int,XChangePointerControl,(Display* a,Bool b,Bool c,int d,int e,int f),(a,b,c,d,e,f),return)
+SDL_X11_SYM(int,XChangeProperty,(Display* a,Window b,Atom c,Atom d,int e,int f,_Xconst unsigned char* g,int h),(a,b,c,d,e,f,g,h),return)
+SDL_X11_SYM(int,XChangeWindowAttributes,(Display* a,Window b,unsigned long c,XSetWindowAttributes* d),(a,b,c,d),return)
+SDL_X11_SYM(Bool,XCheckTypedEvent,(Display* a,int b,XEvent* c),(a,b,c),return)
+SDL_X11_SYM(int,XClearWindow,(Display* a,Window b),(a,b),return)
+SDL_X11_SYM(int,XCloseDisplay,(Display* a),(a),return)
+SDL_X11_SYM(Colormap,XCreateColormap,(Display* a,Window b,Visual* c,int d),(a,b,c,d),return)
+SDL_X11_SYM(Cursor,XCreatePixmapCursor,(Display* a,Pixmap b,Pixmap c,XColor* d,XColor* e,unsigned int f,unsigned int g),(a,b,c,d,e,f,g),return)
+SDL_X11_SYM(GC,XCreateGC,(Display* a,Drawable b,unsigned long c,XGCValues* d),(a,b,c,d),return)
+SDL_X11_SYM(XImage*,XCreateImage,(Display* a,Visual* b,unsigned int c,int d,int e,char* f,unsigned int g,unsigned int h,int i,int j),(a,b,c,d,e,f,g,h,i,j),return)
+SDL_X11_SYM(Pixmap,XCreatePixmap,(Display* a,Drawable b,unsigned int c,unsigned int d,unsigned int e),(a,b,c,d,e),return)
+SDL_X11_SYM(Pixmap,XCreatePixmapFromBitmapData,(Display* a,Drawable b,char* c,unsigned int d,unsigned int e,unsigned long f,unsigned long g,unsigned int h),(a,b,c,d,e,f,g,h),return)
+SDL_X11_SYM(Window,XCreateSimpleWindow,(Display* a,Window b,int c,int d,unsigned int e,unsigned int f,unsigned int g,unsigned long h,unsigned long i),(a,b,c,d,e,f,g,h,i),return)
+SDL_X11_SYM(Window,XCreateWindow,(Display* a,Window b,int c,int d,unsigned int e,unsigned int f,unsigned int g,int h,unsigned int i,Visual* j,unsigned long k,XSetWindowAttributes* l),(a,b,c,d,e,f,g,h,i,j,k,l),return)
+SDL_X11_SYM(int,XDefineCursor,(Display* a,Window b,Cursor c),(a,b,c),return)
+SDL_X11_SYM(int,XDeleteProperty,(Display* a,Window b,Atom c),(a,b,c),return)
+SDL_X11_SYM(int,XDestroyWindow,(Display* a,Window b),(a,b),return)
+SDL_X11_SYM(char*,XDisplayName,(_Xconst char* a),(a),return)
+SDL_X11_SYM(int,XEventsQueued,(Display* a,int b),(a,b),return)
+SDL_X11_SYM(Bool,XFilterEvent,(XEvent *event, Window w),(event,w),return)
+SDL_X11_SYM(int,XFlush,(Display* a),(a),return)
+SDL_X11_SYM(int,XFree,(void*a),(a),return)
+SDL_X11_SYM(int,XFreeColormap,(Display* a,Colormap b),(a,b),return)
+SDL_X11_SYM(int,XFreeColors,(Display* a,Colormap b,unsigned long* c,int d,unsigned long e),(a,b,c,d,e),return)
+SDL_X11_SYM(int,XFreeCursor,(Display* a,Cursor b),(a,b),return)
+SDL_X11_SYM(int,XFreeGC,(Display* a,GC b),(a,b),return)
+SDL_X11_SYM(int,XFreeModifiermap,(XModifierKeymap* a),(a),return)
+SDL_X11_SYM(int,XFreePixmap,(Display* a,Pixmap b),(a,b),return)
+SDL_X11_SYM(int,XGetErrorDatabaseText,(Display* a,_Xconst char* b,_Xconst char* c,_Xconst char* d,char* e,int f),(a,b,c,d,e,f),return)
+SDL_X11_SYM(XModifierKeymap*,XGetModifierMapping,(Display* a),(a),return)
+SDL_X11_SYM(int,XGetPointerControl,(Display* a,int* b,int* c,int* d),(a,b,c,d),return)
+SDL_X11_SYM(XVisualInfo*,XGetVisualInfo,(Display* a,long b,XVisualInfo* c,int* d),(a,b,c,d),return)
+SDL_X11_SYM(XWMHints*,XGetWMHints,(Display* a,Window b),(a,b),return)
+SDL_X11_SYM(Status,XGetWindowAttributes,(Display* a,Window b,XWindowAttributes* c),(a,b,c),return)
+SDL_X11_SYM(int,XGrabKeyboard,(Display* a,Window b,Bool c,int d,int e,Time f),(a,b,c,d,e,f),return)
+SDL_X11_SYM(int,XGrabPointer,(Display* a,Window b,Bool c,unsigned int d,int e,int f,Window g,Cursor h,Time i),(a,b,c,d,e,f,g,h,i),return)
+SDL_X11_SYM(Status,XIconifyWindow,(Display* a,Window b,int c),(a,b,c),return)
+SDL_X11_SYM(int,XInstallColormap,(Display* a,Colormap b),(a,b),return)
+SDL_X11_SYM(KeyCode,XKeysymToKeycode,(Display* a,KeySym b),(a,b),return)
+SDL_X11_SYM(Atom,XInternAtom,(Display* a,_Xconst char* b,Bool c),(a,b,c),return)
+SDL_X11_SYM(XPixmapFormatValues*,XListPixmapFormats,(Display* a,int* b),(a,b),return)
+SDL_X11_SYM(int,XLookupString,(XKeyEvent* a,char* b,int c,KeySym* d,XComposeStatus* e),(a,b,c,d,e),return)
+SDL_X11_SYM(int,XMapRaised,(Display* a,Window b),(a,b),return)
+SDL_X11_SYM(int,XMapWindow,(Display* a,Window b),(a,b),return)
+SDL_X11_SYM(int,XMaskEvent,(Display* a,long b,XEvent* c),(a,b,c),return)
+SDL_X11_SYM(Status,XMatchVisualInfo,(Display* a,int b,int c,int d,XVisualInfo* e),(a,b,c,d,e),return)
+SDL_X11_SYM(int,XMissingExtension,(Display* a,_Xconst char* b),(a,b),return)
+SDL_X11_SYM(int,XMoveResizeWindow,(Display* a,Window b,int c,int d,unsigned int e,unsigned int f),(a,b,c,d,e,f),return)
+SDL_X11_SYM(int,XMoveWindow,(Display* a,Window b,int c,int d),(a,b,c,d),return)
+SDL_X11_SYM(int,XNextEvent,(Display* a,XEvent* b),(a,b),return)
+SDL_X11_SYM(Display*,XOpenDisplay,(_Xconst char* a),(a),return)
+SDL_X11_SYM(int,XPeekEvent,(Display* a,XEvent* b),(a,b),return)
+SDL_X11_SYM(int,XPending,(Display* a),(a),return)
+SDL_X11_SYM(int,XPutImage,(Display* a,Drawable b,GC c,XImage* d,int e,int f,int g,int h,unsigned int i,unsigned int j),(a,b,c,d,e,f,g,h,i,j),return)
+SDL_X11_SYM(int,XQueryColors,(Display* a,Colormap b,XColor* c,int d),(a,b,c,d),return)
+SDL_X11_SYM(int,XQueryKeymap,(Display* a,char *b),(a,b),return)
+SDL_X11_SYM(Bool,XQueryPointer,(Display* a,Window b,Window* c,Window* d,int* e,int* f,int* g,int* h,unsigned int* i),(a,b,c,d,e,f,g,h,i),return)
+SDL_X11_SYM(int,XRaiseWindow,(Display* a,Window b),(a,b),return)
+SDL_X11_SYM(int,XReparentWindow,(Display* a,Window b,Window c,int d,int e),(a,b,c,d,e),return)
+SDL_X11_SYM(int,XResetScreenSaver,(Display* a),(a),return)
+SDL_X11_SYM(int,XResizeWindow,(Display* a,Window b,unsigned int c,unsigned int d),(a,b,c,d),return)
+SDL_X11_SYM(int,XSelectInput,(Display* a,Window b,long c),(a,b,c),return)
+SDL_X11_SYM(Status,XSendEvent,(Display* a,Window b,Bool c,long d,XEvent* e),(a,b,c,d,e),return)
+SDL_X11_SYM(int,XSetClassHint,(Display* a,Window b,XClassHint* c),(a,b,c),return)
+SDL_X11_SYM(XErrorHandler,XSetErrorHandler,(XErrorHandler a),(a),return)
+SDL_X11_SYM(XIOErrorHandler,XSetIOErrorHandler,(XIOErrorHandler a),(a),return)
+SDL_X11_SYM(int,XSetTransientForHint,(Display* a,Window b,Window c),(a,b,c),return)
+SDL_X11_SYM(int,XSetWMHints,(Display* a,Window b,XWMHints* c),(a,b,c),return)
+SDL_X11_SYM(void,XSetTextProperty,(Display* a,Window b,XTextProperty* c,Atom d),(a,b,c,d),)
+SDL_X11_SYM(void,XSetWMNormalHints,(Display* a,Window b,XSizeHints* c),(a,b,c),)
+SDL_X11_SYM(Status,XSetWMProtocols,(Display* a,Window b,Atom* c,int d),(a,b,c,d),return)
+SDL_X11_SYM(int,XSetWindowBackground,(Display* a,Window b,unsigned long c),(a,b,c),return)
+SDL_X11_SYM(int,XSetWindowBackgroundPixmap,(Display* a,Window b,Pixmap c),(a,b,c),return)
+SDL_X11_SYM(int,XSetWindowColormap,(Display* a,Window b,Colormap c),(a,b,c),return)
+SDL_X11_SYM(int,XStoreColors,(Display* a,Colormap b,XColor* c,int d),(a,b,c,d),return)
+SDL_X11_SYM(Status,XStringListToTextProperty,(char** a,int b,XTextProperty* c),(a,b,c),return)
+SDL_X11_SYM(int,XSync,(Display* a,Bool b),(a,b),return)
+SDL_X11_SYM(int,XUngrabKeyboard,(Display* a,Time b),(a,b),return)
+SDL_X11_SYM(int,XUngrabPointer,(Display* a,Time b),(a,b),return)
+SDL_X11_SYM(int,XUnmapWindow,(Display* a,Window b),(a,b),return)
+SDL_X11_SYM(int,XWarpPointer,(Display* a,Window b,Window c,int d,int e,unsigned int f,unsigned int g,int h, int i),(a,b,c,d,e,f,g,h,i),return)
+SDL_X11_SYM(VisualID,XVisualIDFromVisual,(Visual* a),(a),return)
+SDL_X11_SYM(XExtDisplayInfo*,XextAddDisplay,(XExtensionInfo* a,Display* b,char* c,XExtensionHooks* d,int e,XPointer f),(a,b,c,d,e,f),return)
+SDL_X11_SYM(XExtensionInfo*,XextCreateExtension,(void),(),return)
+SDL_X11_SYM(void,XextDestroyExtension,(XExtensionInfo* a),(a),)
+SDL_X11_SYM(XExtDisplayInfo*,XextFindDisplay,(XExtensionInfo* a,Display* b),(a,b),return)
+SDL_X11_SYM(int,XextRemoveDisplay,(XExtensionInfo* a,Display* b),(a,b),return)
+SDL_X11_SYM(Bool,XQueryExtension,(Display* a,_Xconst char* b,int* c,int* d,int* e),(a,b,c,d,e),return)
+SDL_X11_SYM(char *,XDisplayString,(Display* a),(a),return)
+SDL_X11_SYM(int,XGetErrorText,(Display* a,int b,char* c,int d),(a,b,c,d),return)
+SDL_X11_SYM(void,_XEatData,(Display* a,unsigned long b),(a,b),)
+SDL_X11_SYM(void,_XFlush,(Display* a),(a),)
+SDL_X11_SYM(void,_XFlushGCCache,(Display* a,GC b),(a,b),)
+SDL_X11_SYM(int,_XRead,(Display* a,char* b,long c),(a,b,c),return)
+SDL_X11_SYM(void,_XReadPad,(Display* a,char* b,long c),(a,b,c),)
+SDL_X11_SYM(void,_XSend,(Display* a,_Xconst char* b,long c),(a,b,c),)
+SDL_X11_SYM(Status,_XReply,(Display* a,xReply* b,int c,Bool d),(a,b,c,d),return)
+SDL_X11_SYM(unsigned long,_XSetLastRequestRead,(Display* a,xGenericReply* b),(a,b),return)
+SDL_X11_SYM(SDL_X11_XSynchronizeRetType,XSynchronize,(Display* a,Bool b),(a,b),return)
+SDL_X11_SYM(SDL_X11_XESetWireToEventRetType,XESetWireToEvent,(Display* a,int b,SDL_X11_XESetWireToEventRetType c),(a,b,c),return)
+SDL_X11_SYM(SDL_X11_XESetEventToWireRetType,XESetEventToWire,(Display* a,int b,SDL_X11_XESetEventToWireRetType c),(a,b,c),return)
+SDL_X11_SYM(XExtensionErrorHandler,XSetExtensionErrorHandler,(XExtensionErrorHandler a),(a),return)
+
+#if NeedWidePrototypes
+SDL_X11_SYM(KeySym,XKeycodeToKeysym,(Display* a,unsigned int b,int c),(a,b,c),return)
+#else
+SDL_X11_SYM(KeySym,XKeycodeToKeysym,(Display* a,KeyCode b,int c),(a,b,c),return)
+#endif
+
+#ifdef X_HAVE_UTF8_STRING
+SDL_X11_MODULE(UTF8)
+SDL_X11_SYM(int,Xutf8TextListToTextProperty,(Display* a,char** b,int c,XICCEncodingStyle d,XTextProperty* e),(a,b,c,d,e),return)
+SDL_X11_SYM(int,Xutf8LookupString,(XIC a,XKeyPressedEvent* b,char* c,int d,KeySym* e,Status* f),(a,b,c,d,e,f),return)
+/*SDL_X11_SYM(XIC,XCreateIC,(XIM, ...),return)  !!! ARGH! */
+SDL_X11_SYM(void,XDestroyIC,(XIC a),(a),)
+SDL_X11_SYM(void,XSetICFocus,(XIC a),(a),)
+SDL_X11_SYM(void,XUnsetICFocus,(XIC a),(a),)
+/*SDL_X11_SYM(char*,XGetICValues,(XIC a, ...),return)*/
+SDL_X11_SYM(XIM,XOpenIM,(Display* a,struct _XrmHashBucketRec* b,char* c,char* d),(a,b,c,d),return)
+SDL_X11_SYM(Status,XCloseIM,(XIM a),(a),return)
+SDL_X11_SYM(char*,XSetLocaleModifiers,(_Xconst char* a),(a),return)
+SDL_X11_SYM(int,XRefreshKeyboardMapping,(XMappingEvent* a),(a),return)
+SDL_X11_SYM(Display*,XDisplayOfIM,(XIM a),(a),return)
+#endif
+
+#ifndef NO_SHARED_MEMORY
+SDL_X11_MODULE(SHM)
+SDL_X11_SYM(Status,XShmAttach,(Display* a,XShmSegmentInfo* b),(a,b),return)
+SDL_X11_SYM(Status,XShmDetach,(Display* a,XShmSegmentInfo* b),(a,b),return)
+SDL_X11_SYM(Status,XShmPutImage,(Display* a,Drawable b,GC c,XImage* d,int e,int f,int g,int h,unsigned int i,unsigned int j,Bool k),(a,b,c,d,e,f,g,h,i,j,k),return)
+SDL_X11_SYM(XImage*,XShmCreateImage,(Display* a,Visual* b,unsigned int c,int d,char* e,XShmSegmentInfo* f,unsigned int g,unsigned int h),(a,b,c,d,e,f,g,h),return)
+SDL_X11_SYM(Bool,XShmQueryExtension,(Display* a),(a),return)
+#endif
+
+/*
+ * Not required...these only exist in code in headers on some 64-bit platforms,
+ *  and are removed via macros elsewhere, so it's safe for them to be missing.
+ */
+#ifdef LONG64
+SDL_X11_MODULE(IO_32BIT)
+SDL_X11_SYM(int,_XData32,(Display *dpy,register _Xconst long *data,unsigned len),(dpy,data,len),return)
+SDL_X11_SYM(void,_XRead32,(Display *dpy,register long *data,long len),(dpy,data,len),)
+#endif
+
+/*
+ * libX11 1.4.99.1 added _XGetRequest, and macros use it behind the scenes.
+ */
+SDL_X11_MODULE(XGETREQUEST)
+SDL_X11_SYM(void *,_XGetRequest,(Display* a,CARD8 b,size_t c),(a,b,c),return)
+
+/*
+ * These only show up on some variants of Unix.
+ */
+#if defined(__osf__)
+SDL_X11_MODULE(OSF_ENTRY_POINTS)
+SDL_X11_SYM(void,_SmtBufferOverflow,(Display *dpy,register smtDisplayPtr p),(dpy,p),)
+SDL_X11_SYM(void,_SmtIpError,(Display *dpy,register smtDisplayPtr p, int i),(dpy,p,i),)
+SDL_X11_SYM(int,ipAllocateData,(ChannelPtr a, IPCard b, IPDataPtr * c),(a,b,c),return)
+SDL_X11_SYM(int,ipUnallocateAndSendData,(ChannelPtr a, IPCard b),(a,b),return)
+#endif
+
+/* Xrandr support. */
+#if SDL_VIDEO_DRIVER_X11_XRANDR
+SDL_X11_MODULE(XRANDR)
+SDL_X11_SYM(Status,XRRQueryVersion,(Display *dpy,int *major_versionp,int *minor_versionp),(dpy,major_versionp,minor_versionp),return)
+SDL_X11_SYM(XRRScreenConfiguration *,XRRGetScreenInfo,(Display *dpy,Drawable draw),(dpy,draw),return)
+SDL_X11_SYM(SizeID,XRRConfigCurrentConfiguration,(XRRScreenConfiguration *config,Rotation *rotation),(config,rotation),return)
+SDL_X11_SYM(XRRScreenSize *,XRRConfigSizes,(XRRScreenConfiguration *config, int *nsizes),(config,nsizes),return)
+SDL_X11_SYM(Status,XRRSetScreenConfig,(Display *dpy, XRRScreenConfiguration *config, Drawable draw, int size_index, Rotation rotation, Time timestamp),(dpy,config,draw,size_index,rotation,timestamp),return)
+SDL_X11_SYM(void,XRRFreeScreenConfigInfo,(XRRScreenConfiguration *config),(config),)
+#endif
+
+/* end of SDL_x11sym.h ... */
+
diff --git a/sources/packages/l/sdl/sdl/create-1.2.15-x11-XData32-patch/create.patch.sh b/sources/packages/l/sdl/sdl/create-1.2.15-x11-XData32-patch/create.patch.sh
new file mode 100755
index 000000000..d76b07356
--- /dev/null
+++ b/sources/packages/l/sdl/sdl/create-1.2.15-x11-XData32-patch/create.patch.sh
@@ -0,0 +1,15 @@
+#!/bin/sh
+
+VERSION=1.2.15
+
+tar --files-from=file.list -xzvf ../SDL-$VERSION.tar.gz
+mv SDL-$VERSION SDL-$VERSION-orig
+
+cp -rf ./SDL-$VERSION-new ./SDL-$VERSION
+
+diff -b --unified -Nr  SDL-$VERSION-orig  SDL-$VERSION > SDL-$VERSION-x11-XData32.patch
+
+mv SDL-$VERSION-x11-XData32.patch ../patches
+
+rm -rf ./SDL-$VERSION
+rm -rf ./SDL-$VERSION-orig
diff --git a/sources/packages/l/sdl/sdl/create-1.2.15-x11-XData32-patch/file.list b/sources/packages/l/sdl/sdl/create-1.2.15-x11-XData32-patch/file.list
new file mode 100644
index 000000000..08556f29f
--- /dev/null
+++ b/sources/packages/l/sdl/sdl/create-1.2.15-x11-XData32-patch/file.list
@@ -0,0 +1 @@
+SDL-1.2.15/src/video/x11/SDL_x11sym.h
diff --git a/sources/packages/l/sdl/sdl/create-1.2.15-x11-events-patch/SDL-1.2.15-new/src/video/x11/SDL_x11events.c b/sources/packages/l/sdl/sdl/create-1.2.15-x11-events-patch/SDL-1.2.15-new/src/video/x11/SDL_x11events.c
new file mode 100644
index 000000000..cfdbb157f
--- /dev/null
+++ b/sources/packages/l/sdl/sdl/create-1.2.15-x11-events-patch/SDL-1.2.15-new/src/video/x11/SDL_x11events.c
@@ -0,0 +1,1432 @@
+/*
+    SDL - Simple DirectMedia Layer
+    Copyright (C) 1997-2012 Sam Lantinga
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+    Sam Lantinga
+    slouken@libsdl.org
+*/
+#include "SDL_config.h"
+
+/* Handle the event stream, converting X11 events into SDL events */
+
+#include <setjmp.h>
+#include <X11/Xlib.h>
+#include <X11/Xutil.h>
+#include <X11/keysym.h>
+#ifdef __SVR4
+#include <X11/Sunkeysym.h>
+#endif
+#include <sys/types.h>
+#include <sys/time.h>
+#include <unistd.h>
+
+#include "SDL_timer.h"
+#include "SDL_syswm.h"
+#include "../SDL_sysvideo.h"
+#include "../../events/SDL_sysevents.h"
+#include "../../events/SDL_events_c.h"
+#include "SDL_x11video.h"
+#include "SDL_x11dga_c.h"
+#include "SDL_x11modes_c.h"
+#include "SDL_x11image_c.h"
+#include "SDL_x11gamma_c.h"
+#include "SDL_x11wm_c.h"
+#include "SDL_x11mouse_c.h"
+#include "SDL_x11events_c.h"
+
+
+/* Define this if you want to debug X11 events */
+/*#define DEBUG_XEVENTS*/
+
+/* The translation tables from an X11 keysym to a SDL keysym */
+static SDLKey ODD_keymap[256];
+static SDLKey MISC_keymap[256];
+SDLKey X11_TranslateKeycode(Display *display, KeyCode kc);
+
+
+#ifdef X_HAVE_UTF8_STRING
+Uint32 Utf8ToUcs4(const Uint8 *utf8)
+{
+	Uint32 c;
+	int i = 1;
+	int noOctets = 0;
+	int firstOctetMask = 0;
+	unsigned char firstOctet = utf8[0];
+	if (firstOctet < 0x80) {
+		/*
+		  Characters in the range:
+		    00000000 to 01111111 (ASCII Range)
+		  are stored in one octet:
+		    0xxxxxxx (The same as its ASCII representation)
+		  The least 6 significant bits of the first octet is the most 6 significant nonzero bits
+		  of the UCS4 representation.
+		*/
+		noOctets = 1;
+		firstOctetMask = 0x7F;  /* 0(1111111) - The most significant bit is ignored */
+	} else if ((firstOctet & 0xE0) /* get the most 3 significant bits by AND'ing with 11100000 */
+	              == 0xC0 ) {  /* see if those 3 bits are 110. If so, the char is in this range */
+		/*
+		  Characters in the range:
+		    00000000 10000000 to 00000111 11111111
+		  are stored in two octets:
+		    110xxxxx 10xxxxxx
+		  The least 5 significant bits of the first octet is the most 5 significant nonzero bits
+		  of the UCS4 representation.
+		*/
+		noOctets = 2;
+		firstOctetMask = 0x1F;  /* 000(11111) - The most 3 significant bits are ignored */
+	} else if ((firstOctet & 0xF0) /* get the most 4 significant bits by AND'ing with 11110000 */
+	              == 0xE0) {  /* see if those 4 bits are 1110. If so, the char is in this range */
+		/*
+		  Characters in the range:
+		    00001000 00000000 to 11111111 11111111
+		  are stored in three octets:
+		    1110xxxx 10xxxxxx 10xxxxxx
+		  The least 4 significant bits of the first octet is the most 4 significant nonzero bits
+		  of the UCS4 representation.
+		*/
+		noOctets = 3;
+		firstOctetMask = 0x0F; /* 0000(1111) - The most 4 significant bits are ignored */
+	} else if ((firstOctet & 0xF8) /* get the most 5 significant bits by AND'ing with 11111000 */
+	              == 0xF0) {  /* see if those 5 bits are 11110. If so, the char is in this range */
+		/*
+		  Characters in the range:
+		    00000001 00000000 00000000 to 00011111 11111111 11111111
+		  are stored in four octets:
+		    11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
+		  The least 3 significant bits of the first octet is the most 3 significant nonzero bits
+		  of the UCS4 representation.
+		*/
+		noOctets = 4;
+		firstOctetMask = 0x07; /* 11110(111) - The most 5 significant bits are ignored */
+	} else if ((firstOctet & 0xFC) /* get the most 6 significant bits by AND'ing with 11111100 */
+	              == 0xF8) { /* see if those 6 bits are 111110. If so, the char is in this range */
+		/*
+		  Characters in the range:
+		    00000000 00100000 00000000 00000000 to
+		    00000011 11111111 11111111 11111111
+		  are stored in five octets:
+		    111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
+		  The least 2 significant bits of the first octet is the most 2 significant nonzero bits
+		  of the UCS4 representation.
+		*/
+		noOctets = 5;
+		firstOctetMask = 0x03; /* 111110(11) - The most 6 significant bits are ignored */
+	} else if ((firstOctet & 0xFE) /* get the most 7 significant bits by AND'ing with 11111110 */
+	              == 0xFC) { /* see if those 7 bits are 1111110. If so, the char is in this range */
+		/*
+		  Characters in the range:
+		    00000100 00000000 00000000 00000000 to
+		    01111111 11111111 11111111 11111111
+		  are stored in six octets:
+		    1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
+		  The least significant bit of the first octet is the most significant nonzero bit
+		  of the UCS4 representation.
+		*/
+		noOctets = 6;
+		firstOctetMask = 0x01; /* 1111110(1) - The most 7 significant bits are ignored */
+	} else
+		return 0;  /* The given chunk is not a valid UTF-8 encoded Unicode character */
+	
+	/*
+	  The least noOctets significant bits of the first octet is the most 2 significant nonzero bits
+	  of the UCS4 representation.
+	  The first 6 bits of the UCS4 representation is the least 8-noOctets-1 significant bits of
+	  firstOctet if the character is not ASCII. If so, it's the least 7 significant bits of firstOctet.
+	  This done by AND'ing firstOctet with its mask to trim the bits used for identifying the
+	  number of continuing octets (if any) and leave only the free bits (the x's)
+	  Sample:
+	  1-octet:    0xxxxxxx  &  01111111 = 0xxxxxxx
+	  2-octets:  110xxxxx  &  00011111 = 000xxxxx
+	*/
+	c = firstOctet & firstOctetMask;
+	
+	/* Now, start filling c.ucs4 with the bits from the continuing octets from utf8. */
+	for (i = 1; i < noOctets; i++) {
+		/* A valid continuing octet is of the form 10xxxxxx */
+		if ((utf8[i] & 0xC0) /* get the most 2 significant bits by AND'ing with 11000000 */
+		    != 0x80) /* see if those 2 bits are 10. If not, the is a malformed sequence. */
+			/*The given chunk is a partial sequence at the end of a string that could
+			   begin a valid character */
+			return 0;
+		
+		/* Make room for the next 6-bits */
+		c <<= 6;
+		
+		/*
+		  Take only the least 6 significance bits of the current octet (utf8[i]) and fill the created room
+		  of c.ucs4 with them.
+		  This done by AND'ing utf8[i] with 00111111 and the OR'ing the result with c.ucs4.
+		*/
+		c |= utf8[i] & 0x3F;
+	}
+	return c;
+}
+
+/* Given a UTF-8 encoded string pointed to by utf8 of length length in
+   bytes, returns the corresponding UTF-16 encoded string in the
+   buffer pointed to by utf16.  The maximum number of UTF-16 encoding
+   units (i.e., Unit16s) allowed in the buffer is specified in
+   utf16_max_length.  The return value is the number of UTF-16
+   encoding units placed in the output buffer pointed to by utf16.
+
+   In case of an error, -1 is returned, leaving some unusable partial
+   results in the output buffer.
+
+   The caller must estimate the size of utf16 buffer by itself before
+   calling this function.  Insufficient output buffer is considered as
+   an error, and once an error occured, this function doesn't give any
+   clue how large the result will be.
+
+   The error cases include following:
+
+   - Invalid byte sequences were in the input UTF-8 bytes.  The caller
+     has no way to know what point in the input buffer was the
+     errornous byte.
+
+   - The input contained a character (a valid UTF-8 byte sequence)
+     whose scalar value exceeded the range that UTF-16 can represent
+     (i.e., characters whose Unicode scalar value above 0x110000).
+
+   - The output buffer has no enough space to hold entire utf16 data.
+
+   Please note:
+
+   - '\0'-termination is not assumed both on the input UTF-8 string
+     and on the output UTF-16 string; any legal zero byte in the input
+     UTF-8 string will be converted to a 16-bit zero in output.  As a
+     side effect, the last UTF-16 encoding unit stored in the output
+     buffer will have a non-zero value if the input UTF-8 was not
+     '\0'-terminated.
+
+   - UTF-8 aliases are *not* considered as an error.  They are
+     converted to UTF-16.  For example, 0xC0 0xA0, 0xE0 0x80 0xA0, 
+     and 0xF0 0x80 0x80 0xA0 are all mapped to a single UTF-16
+     encoding unit 0x0020.
+
+   - Three byte UTF-8 sequences whose value corresponds to a surrogate
+     code or other reserved scalar value are not considered as an
+     error either.  They may cause an invalid UTF-16 data (e.g., those
+     containing unpaired surrogates).
+
+*/
+
+static int Utf8ToUtf16(const Uint8 *utf8, const int utf8_length, Uint16 *utf16, const int utf16_max_length) {
+
+    /* p moves over the output buffer.  max_ptr points to the next to the last slot of the buffer.  */
+    Uint16 *p = utf16;
+    Uint16 const *const max_ptr = utf16 + utf16_max_length;
+
+    /* end_of_input points to the last byte of input as opposed to the next to the last byte.  */
+    Uint8 const *const end_of_input = utf8 + utf8_length - 1;
+
+    while (utf8 <= end_of_input) {
+	Uint8 const c = *utf8;
+	if (p >= max_ptr) {
+	    /* No more output space.  */
+	    return -1;
+	}
+	if (c < 0x80) {
+	    /* One byte ASCII.  */
+	    *p++ = c;
+	    utf8 += 1;
+	} else if (c < 0xC0) {
+	    /* Follower byte without preceeding leader bytes.  */
+	    return -1;
+	} else if (c < 0xE0) {
+	    /* Two byte sequence.  We need one follower byte.  */
+	    if (end_of_input - utf8 < 1 || (((utf8[1] ^ 0x80)) & 0xC0)) {
+		return -1;
+	    }
+	    *p++ = (Uint16)(0xCF80 + (c << 6) + utf8[1]);
+	    utf8 += 2;
+	} else if (c < 0xF0) {
+	    /* Three byte sequence.  We need two follower byte.  */
+	    if (end_of_input - utf8 < 2 || (((utf8[1] ^ 0x80) | (utf8[2] ^ 0x80)) & 0xC0)) {
+		return -1;
+	    }
+	    *p++ = (Uint16)(0xDF80 + (c << 12) + (utf8[1] << 6) + utf8[2]);
+	    utf8 += 3;
+	} else if (c < 0xF8) {
+	    int plane;
+	    /* Four byte sequence.  We need three follower bytes.  */
+	    if (end_of_input - utf8 < 3 || (((utf8[1] ^ 0x80) | (utf8[2] ^0x80) | (utf8[3] ^ 0x80)) & 0xC0)) {
+		return -1;
+	    }
+	    plane = (-0xC8 + (c << 2) + (utf8[1] >> 4));
+	    if (plane == 0) {
+		/* This four byte sequence is an alias that
+                   corresponds to a Unicode scalar value in BMP.
+		   It fits in an UTF-16 encoding unit.  */
+		*p++ = (Uint16)(0xDF80 + (utf8[1] << 12) + (utf8[2] << 6) + utf8[3]);
+	    } else if (plane <= 16) {
+		/* This is a legal four byte sequence that corresponds to a surrogate pair.  */
+		if (p + 1 >= max_ptr) {
+		    /* No enough space on the output buffer for the pair.  */
+		    return -1;
+		}
+		*p++ = (Uint16)(0xE5B8 + (c << 8) + (utf8[1] << 2) + (utf8[2] >> 4));
+		*p++ = (Uint16)(0xDB80 + ((utf8[2] & 0x0F) << 6) + utf8[3]);
+	    } else {
+		/* This four byte sequence is out of UTF-16 code space.  */
+		return -1;
+	    }
+	    utf8 += 4;
+	} else {
+	    /* Longer sequence or unused byte.  */
+	    return -1;
+	}
+    }
+    return p - utf16;
+}
+
+#endif
+
+/* Check to see if this is a repeated key.
+   (idea shamelessly lifted from GII -- thanks guys! :)
+ */
+static int X11_KeyRepeat(Display *display, XEvent *event)
+{
+	XEvent peekevent;
+	int repeated;
+
+	repeated = 0;
+	if ( XPending(display) ) {
+		XPeekEvent(display, &peekevent);
+		if ( (peekevent.type == KeyPress) &&
+		     (peekevent.xkey.keycode == event->xkey.keycode) &&
+		     ((peekevent.xkey.time-event->xkey.time) < 2) ) {
+			repeated = 1;
+			XNextEvent(display, &peekevent);
+		}
+	}
+	return(repeated);
+}
+
+/* Note:  The X server buffers and accumulates mouse motion events, so
+   the motion event generated by the warp may not appear exactly as we
+   expect it to.  We work around this (and improve performance) by only
+   warping the pointer when it reaches the edge, and then wait for it.
+*/
+#define MOUSE_FUDGE_FACTOR	8
+
+static __inline__ int X11_WarpedMotion(_THIS, XEvent *xevent)
+{
+	int w, h, i;
+	int deltax, deltay;
+	int posted;
+
+	w = SDL_VideoSurface->w;
+	h = SDL_VideoSurface->h;
+	deltax = xevent->xmotion.x - mouse_last.x;
+	deltay = xevent->xmotion.y - mouse_last.y;
+#ifdef DEBUG_MOTION
+  printf("Warped mouse motion: %d,%d\n", deltax, deltay);
+#endif
+	mouse_last.x = xevent->xmotion.x;
+	mouse_last.y = xevent->xmotion.y;
+	posted = SDL_PrivateMouseMotion(0, 1, deltax, deltay);
+
+	if ( (xevent->xmotion.x < MOUSE_FUDGE_FACTOR) ||
+	     (xevent->xmotion.x > (w-MOUSE_FUDGE_FACTOR)) ||
+	     (xevent->xmotion.y < MOUSE_FUDGE_FACTOR) ||
+	     (xevent->xmotion.y > (h-MOUSE_FUDGE_FACTOR)) ) {
+		/* Get the events that have accumulated */
+		while ( XCheckTypedEvent(SDL_Display, MotionNotify, xevent) ) {
+			deltax = xevent->xmotion.x - mouse_last.x;
+			deltay = xevent->xmotion.y - mouse_last.y;
+#ifdef DEBUG_MOTION
+  printf("Extra mouse motion: %d,%d\n", deltax, deltay);
+#endif
+			mouse_last.x = xevent->xmotion.x;
+			mouse_last.y = xevent->xmotion.y;
+			posted += SDL_PrivateMouseMotion(0, 1, deltax, deltay);
+		}
+		mouse_last.x = w/2;
+		mouse_last.y = h/2;
+		XWarpPointer(SDL_Display, None, SDL_Window, 0, 0, 0, 0,
+					mouse_last.x, mouse_last.y);
+		for ( i=0; i<10; ++i ) {
+        		XMaskEvent(SDL_Display, PointerMotionMask, xevent);
+			if ( (xevent->xmotion.x >
+			          (mouse_last.x-MOUSE_FUDGE_FACTOR)) &&
+			     (xevent->xmotion.x <
+			          (mouse_last.x+MOUSE_FUDGE_FACTOR)) &&
+			     (xevent->xmotion.y >
+			          (mouse_last.y-MOUSE_FUDGE_FACTOR)) &&
+			     (xevent->xmotion.y <
+			          (mouse_last.y+MOUSE_FUDGE_FACTOR)) ) {
+				break;
+			}
+#ifdef DEBUG_XEVENTS
+  printf("Lost mouse motion: %d,%d\n", xevent->xmotion.x, xevent->xmotion.y);
+#endif
+		}
+#ifdef DEBUG_XEVENTS
+		if ( i == 10 ) {
+			printf("Warning: didn't detect mouse warp motion\n");
+		}
+#endif
+	}
+	return(posted);
+}
+
+static int X11_DispatchEvent(_THIS)
+{
+	int posted;
+	XEvent xevent;
+	int orig_event_type;
+	KeyCode orig_keycode;
+
+	SDL_memset(&xevent, '\0', sizeof (XEvent));  /* valgrind fix. --ryan. */
+	XNextEvent(SDL_Display, &xevent);
+
+	/* Discard KeyRelease and KeyPress events generated by auto-repeat.
+	   We need to do it before passing event to XFilterEvent.  Otherwise,
+	   KeyRelease aware IMs are confused...  */
+	if ( xevent.type == KeyRelease
+	     && X11_KeyRepeat(SDL_Display, &xevent) ) {
+		return 0;
+	}
+
+#ifdef X_HAVE_UTF8_STRING
+	/* If we are translating with IM, we need to pass all events
+	   to XFilterEvent, and discard those filtered events immediately.  */
+	orig_event_type = xevent.type;
+	if (orig_event_type == KeyPress || orig_event_type == KeyRelease) {
+	     orig_keycode = xevent.xkey.keycode;
+	} else {
+	     orig_keycode = 0;
+	}
+	if ( SDL_TranslateUNICODE
+	     && SDL_IM != NULL
+	     && XFilterEvent(&xevent, None) ) {
+	        if (orig_keycode) {
+	            SDL_keysym keysym;
+	            static XComposeStatus state;
+	            char keybuf[32];
+
+	            keysym.scancode = xevent.xkey.keycode;
+	            keysym.sym = X11_TranslateKeycode(SDL_Display, xevent.xkey.keycode);
+	            keysym.mod = KMOD_NONE;
+	            keysym.unicode = 0;
+	            if (orig_event_type == KeyPress && XLookupString(&xevent.xkey, keybuf, sizeof(keybuf), NULL, &state))
+	                keysym.unicode = (Uint8)keybuf[0];
+
+	            SDL_PrivateKeyboard(orig_event_type == KeyPress ? SDL_PRESSED : SDL_RELEASED, &keysym);
+	        }
+		return 0;
+	}
+#endif
+
+	posted = 0;
+	switch (xevent.type) {
+
+	    /* Gaining mouse coverage? */
+	    case EnterNotify: {
+#ifdef DEBUG_XEVENTS
+printf("EnterNotify! (%d,%d)\n", xevent.xcrossing.x, xevent.xcrossing.y);
+if ( xevent.xcrossing.mode == NotifyGrab )
+printf("Mode: NotifyGrab\n");
+if ( xevent.xcrossing.mode == NotifyUngrab )
+printf("Mode: NotifyUngrab\n");
+#endif
+		if ( (xevent.xcrossing.mode != NotifyGrab) &&
+		     (xevent.xcrossing.mode != NotifyUngrab) ) {
+			if ( this->input_grab == SDL_GRAB_OFF ) {
+				posted = SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS);
+			}
+			posted = SDL_PrivateMouseMotion(0, 0,
+					xevent.xcrossing.x,
+					xevent.xcrossing.y);
+		}
+	    }
+	    break;
+
+	    /* Losing mouse coverage? */
+	    case LeaveNotify: {
+#ifdef DEBUG_XEVENTS
+printf("LeaveNotify! (%d,%d)\n", xevent.xcrossing.x, xevent.xcrossing.y);
+if ( xevent.xcrossing.mode == NotifyGrab )
+printf("Mode: NotifyGrab\n");
+if ( xevent.xcrossing.mode == NotifyUngrab )
+printf("Mode: NotifyUngrab\n");
+#endif
+		if ( (xevent.xcrossing.mode != NotifyGrab) &&
+		     (xevent.xcrossing.mode != NotifyUngrab) &&
+		     (xevent.xcrossing.detail != NotifyInferior) ) {
+               		if ( this->input_grab == SDL_GRAB_OFF ) {
+				posted = SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS);
+			} else {
+				posted = SDL_PrivateMouseMotion(0, 0,
+						xevent.xcrossing.x,
+						xevent.xcrossing.y);
+			}
+		}
+	    }
+	    break;
+
+	    /* Gaining input focus? */
+	    case FocusIn: {
+#ifdef DEBUG_XEVENTS
+printf("FocusIn!\n");
+#endif
+		posted = SDL_PrivateAppActive(1, SDL_APPINPUTFOCUS);
+
+#ifdef X_HAVE_UTF8_STRING
+		if ( SDL_IC != NULL ) {
+			XSetICFocus(SDL_IC);
+		}
+#endif
+		/* Queue entry into fullscreen mode */
+		switch_waiting = 0x01 | SDL_FULLSCREEN;
+		switch_time = SDL_GetTicks() + 1500;
+	    }
+	    break;
+
+	    /* Losing input focus? */
+	    case FocusOut: {
+#ifdef DEBUG_XEVENTS
+printf("FocusOut!\n");
+#endif
+		posted = SDL_PrivateAppActive(0, SDL_APPINPUTFOCUS);
+
+#ifdef X_HAVE_UTF8_STRING
+		if ( SDL_IC != NULL ) {
+			XUnsetICFocus(SDL_IC);
+		}
+#endif
+		/* Queue leaving fullscreen mode */
+		switch_waiting = 0x01;
+		switch_time = SDL_GetTicks() + 200;
+	    }
+	    break;
+
+#ifdef X_HAVE_UTF8_STRING
+	    /* Some IM requires MappingNotify to be passed to
+	       XRefreshKeyboardMapping by the app.  */
+	    case MappingNotify: {
+		XRefreshKeyboardMapping(&xevent.xmapping);
+	    }
+	    break;
+#endif /* X_HAVE_UTF8_STRING */
+
+	    /* Generated upon EnterWindow and FocusIn */
+	    case KeymapNotify: {
+#ifdef DEBUG_XEVENTS
+printf("KeymapNotify!\n");
+#endif
+		X11_SetKeyboardState(SDL_Display,  xevent.xkeymap.key_vector);
+	    }
+	    break;
+
+	    /* Mouse motion? */
+	    case MotionNotify: {
+		if ( SDL_VideoSurface ) {
+			if ( mouse_relative ) {
+				if ( using_dga & DGA_MOUSE ) {
+#ifdef DEBUG_MOTION
+  printf("DGA motion: %d,%d\n", xevent.xmotion.x_root, xevent.xmotion.y_root);
+#endif
+					posted = SDL_PrivateMouseMotion(0, 1,
+							xevent.xmotion.x_root,
+							xevent.xmotion.y_root);
+				} else {
+					posted = X11_WarpedMotion(this,&xevent);
+				}
+			} else {
+#ifdef DEBUG_MOTION
+  printf("X11 motion: %d,%d\n", xevent.xmotion.x, xevent.xmotion.y);
+#endif
+				posted = SDL_PrivateMouseMotion(0, 0,
+						xevent.xmotion.x,
+						xevent.xmotion.y);
+			}
+		}
+	    }
+	    break;
+
+	    /* Mouse button press? */
+	    case ButtonPress: {
+		posted = SDL_PrivateMouseButton(SDL_PRESSED, 
+					xevent.xbutton.button, 0, 0);
+	    }
+	    break;
+
+	    /* Mouse button release? */
+	    case ButtonRelease: {
+		posted = SDL_PrivateMouseButton(SDL_RELEASED, 
+					xevent.xbutton.button, 0, 0);
+	    }
+	    break;
+
+	    /* Key press? */
+	    case KeyPress: {
+		SDL_keysym keysym;
+		KeyCode keycode = xevent.xkey.keycode;
+
+#ifdef DEBUG_XEVENTS
+printf("KeyPress (X11 keycode = 0x%X)\n", xevent.xkey.keycode);
+#endif
+		/* If we're not doing translation, we're done! */
+		if ( !SDL_TranslateUNICODE ) {
+			/* Get the translated SDL virtual keysym and put it on the queue.*/
+			keysym.scancode = keycode;
+			keysym.sym = X11_TranslateKeycode(SDL_Display, keycode);
+			keysym.mod = KMOD_NONE;
+			keysym.unicode = 0;
+			posted = SDL_PrivateKeyboard(SDL_PRESSED, &keysym);
+			break;
+		}
+
+		/* Look up the translated value for the key event */
+#ifdef X_HAVE_UTF8_STRING
+		if ( SDL_IC != NULL ) {
+			Status status;
+			KeySym xkeysym;
+			int i;
+			/* A UTF-8 character can be at most 6 bytes */
+			/* ... It's true, but Xutf8LookupString can
+			   return more than one characters.  Moreover,
+			   the spec. put no upper bound, so we should
+			   be ready for longer strings.  */
+			char keybuf[32];
+			char *keydata = keybuf;
+			int count;
+			Uint16 utf16buf[32];
+			Uint16 *utf16data = utf16buf;
+			int utf16size;
+			int utf16length;
+
+			count = Xutf8LookupString(SDL_IC, &xevent.xkey, keydata, sizeof(keybuf), &xkeysym, &status);
+			if (XBufferOverflow == status) {
+			  /* The IM has just generated somewhat long
+			     string.  We need a longer buffer in this
+			     case.  */
+			  keydata = SDL_malloc(count);
+			  if ( keydata == NULL ) {
+			    SDL_OutOfMemory();
+			    break;
+			  }
+			  count = Xutf8LookupString(SDL_IC, &xevent.xkey, keydata, count, &xkeysym, &status);
+			}
+
+			switch (status) {
+
+			case XBufferOverflow: {
+			  /* Oops!  We have allocated the bytes as
+			     requested by Xutf8LookupString, so the
+			     length of the buffer must be
+			     sufficient.  This case should never
+			     happen! */
+			  SDL_SetError("Xutf8LookupString indicated a double buffer overflow!");
+			  break;
+			}
+
+			case XLookupChars:
+			case XLookupBoth: {
+			  if (0 == count) {
+			    break;
+			  }
+
+			  /* We got a converted string from IM.  Make
+			     sure to deliver all characters to the
+			     application as SDL events.  Note that
+			     an SDL event can only carry one UTF-16
+			     encoding unit, and a surrogate pair is
+			     delivered as two SDL events.  I guess
+			     this behaviour is probably _imported_
+			     from Windows or MacOS.  To do so, we need
+			     to convert the UTF-8 data into UTF-16
+			     data (not UCS4/UTF-32!).  We need an
+			     estimate of the number of UTF-16 encoding
+			     units here.  The worst case is pure ASCII
+			     string.  Assume so. */
+			  /* In 1.3 SDL may have a text event instead, that
+			     carries the whole UTF-8 string with it. */
+			  utf16size = count * sizeof(Uint16);
+			  if (utf16size > sizeof(utf16buf)) {
+			    utf16data = (Uint16 *) SDL_malloc(utf16size);
+			    if (utf16data == NULL) {
+			      SDL_OutOfMemory();
+			      break;
+			    }
+			  }
+			  utf16length = Utf8ToUtf16((Uint8 *)keydata, count, utf16data, utf16size);
+			  if (utf16length < 0) {
+			    /* The keydata contained an invalid byte
+			       sequence.  It should be a bug of the IM
+			       or Xlib... */
+			    SDL_SetError("Oops! Xutf8LookupString returned an invalid UTF-8 sequence!");
+			    break;
+			  }
+
+			  /* Deliver all UTF-16 encoding units.  At
+			     this moment, SDL event queue has a
+			     fixed size (128 events), and an SDL
+			     event can hold just one UTF-16 encoding
+			     unit.  So, if we receive more than 128
+			     UTF-16 encoding units from a commit,
+			     exceeded characters will be lost.  */
+			  for (i = 0; i < utf16length - 1; i++) {
+			    keysym.scancode = 0;
+			    keysym.sym = SDLK_UNKNOWN;
+			    keysym.mod = KMOD_NONE;
+			    keysym.unicode = utf16data[i];
+			    posted = SDL_PrivateKeyboard(SDL_PRESSED, &keysym);
+			  }
+			  /* The keysym for the last character carries the
+			     scancode and symbol that corresponds to the X11
+			     keycode.  */
+			  if (utf16length > 0) {			       
+			    keysym.scancode = keycode;
+			    keysym.sym = (keycode ? X11_TranslateKeycode(SDL_Display, keycode) : 0);
+			    keysym.mod = KMOD_NONE;
+			    keysym.unicode = utf16data[utf16length - 1];
+			    posted = SDL_PrivateKeyboard(SDL_PRESSED, &keysym);
+			  }
+			  break;
+			}
+
+			case XLookupKeySym: {
+			  /* I'm not sure whether it is possible that
+			     a zero keycode makes XLookupKeySym
+			     status.  What I'm sure is that a
+			     combination of a zero scan code and a non
+			     zero sym makes SDL_PrivateKeyboard
+			     strange state...  So, just discard it.
+			     If this doesn't work, I'm receiving bug
+			     reports, and I can know under what
+			     condition this case happens.  */
+			  if (keycode) {
+			    keysym.scancode = keycode;
+			    keysym.sym = X11_TranslateKeycode(SDL_Display, keycode);
+			    keysym.mod = KMOD_NONE;
+			    keysym.unicode = 0;
+			    posted = SDL_PrivateKeyboard(SDL_PRESSED, &keysym);
+			  }
+			  break;
+			}
+
+			case XLookupNone: {
+			  /* IM has eaten the event.  */
+			  break;
+			}
+
+			default:
+			  /* An unknown status from Xutf8LookupString.  */
+			  SDL_SetError("Oops! Xutf8LookupStringreturned an unknown status");
+			}
+
+			/* Release dynamic buffers if allocated.  */
+			if (keydata != NULL && keybuf != keydata) {
+			  SDL_free(keydata);
+			}
+			if (utf16data != NULL && utf16buf != utf16data) {
+			  SDL_free(utf16data);
+			}
+		}
+		else
+#endif
+		{
+			static XComposeStatus state;
+			char keybuf[32];
+
+			keysym.scancode = keycode;
+			keysym.sym = X11_TranslateKeycode(SDL_Display, keycode);
+			keysym.mod = KMOD_NONE;
+			keysym.unicode = 0;
+			if ( XLookupString(&xevent.xkey,
+			                    keybuf, sizeof(keybuf),
+			                    NULL, &state) ) {
+				/*
+				* FIXME: XLookupString() may yield more than one
+				* character, so we need a mechanism to allow for
+				* this (perhaps null keypress events with a
+				* unicode value)
+				*/
+				keysym.unicode = (Uint8)keybuf[0];
+			}
+
+			posted = SDL_PrivateKeyboard(SDL_PRESSED, &keysym);
+		}
+	    }
+	    break;
+
+	    /* Key release? */
+	    case KeyRelease: {
+		SDL_keysym keysym;
+		KeyCode keycode = xevent.xkey.keycode;
+
+		if (keycode == 0) {
+		  /* There should be no KeyRelease for keycode == 0,
+		     since it is a notification from IM but a real
+		     keystroke.  */
+		  /* We need to emit some diagnostic message here.  */
+		  break;
+		}
+
+#ifdef DEBUG_XEVENTS
+printf("KeyRelease (X11 keycode = 0x%X)\n", xevent.xkey.keycode);
+#endif
+
+		/* Get the translated SDL virtual keysym */
+		keysym.scancode = keycode;
+		keysym.sym = X11_TranslateKeycode(SDL_Display, keycode);
+		keysym.mod = KMOD_NONE;
+		keysym.unicode = 0;
+
+		posted = SDL_PrivateKeyboard(SDL_RELEASED, &keysym);
+	    }
+	    break;
+
+	    /* Have we been iconified? */
+	    case UnmapNotify: {
+#ifdef DEBUG_XEVENTS
+printf("UnmapNotify!\n");
+#endif
+		/* If we're active, make ourselves inactive */
+		if ( SDL_GetAppState() & SDL_APPACTIVE ) {
+			/* Swap out the gamma before we go inactive */
+			X11_SwapVidModeGamma(this);
+
+			/* Send an internal deactivate event */
+			posted = SDL_PrivateAppActive(0,
+					SDL_APPACTIVE|SDL_APPINPUTFOCUS);
+		}
+	    }
+	    break;
+
+	    /* Have we been restored? */
+	    case MapNotify: {
+#ifdef DEBUG_XEVENTS
+printf("MapNotify!\n");
+#endif
+		/* If we're not active, make ourselves active */
+		if ( !(SDL_GetAppState() & SDL_APPACTIVE) ) {
+			/* Send an internal activate event */
+			posted = SDL_PrivateAppActive(1, SDL_APPACTIVE);
+
+			/* Now that we're active, swap the gamma back */
+			X11_SwapVidModeGamma(this);
+		}
+
+		if ( SDL_VideoSurface &&
+		     (SDL_VideoSurface->flags & SDL_FULLSCREEN) ) {
+			X11_EnterFullScreen(this);
+		} else {
+			X11_GrabInputNoLock(this, this->input_grab);
+		}
+		X11_CheckMouseModeNoLock(this);
+
+		if ( SDL_VideoSurface ) {
+			X11_RefreshDisplay(this);
+		}
+	    }
+	    break;
+
+	    /* Have we been resized or moved? */
+	    case ConfigureNotify: {
+#ifdef DEBUG_XEVENTS
+printf("ConfigureNotify! (resize: %dx%d)\n", xevent.xconfigure.width, xevent.xconfigure.height);
+#endif
+		if ( SDL_VideoSurface ) {
+		    if ((xevent.xconfigure.width != SDL_VideoSurface->w) ||
+		        (xevent.xconfigure.height != SDL_VideoSurface->h)) {
+			/* FIXME: Find a better fix for the bug with KDE 1.2 */
+			if ( ! ((xevent.xconfigure.width == 32) &&
+			        (xevent.xconfigure.height == 32)) ) {
+				SDL_PrivateResize(xevent.xconfigure.width,
+				                  xevent.xconfigure.height);
+			}
+		    } else {
+			/* OpenGL windows need to know about the change */
+			if ( SDL_VideoSurface->flags & SDL_OPENGL ) {
+				SDL_PrivateExpose();
+			}
+		    }
+		}
+	    }
+	    break;
+
+	    /* Have we been requested to quit (or another client message?) */
+	    case ClientMessage: {
+		if ( (xevent.xclient.format == 32) &&
+		     (xevent.xclient.data.l[0] == WM_DELETE_WINDOW) )
+		{
+			posted = SDL_PrivateQuit();
+		} else
+		if ( SDL_ProcessEvents[SDL_SYSWMEVENT] == SDL_ENABLE ) {
+			SDL_SysWMmsg wmmsg;
+
+			SDL_VERSION(&wmmsg.version);
+			wmmsg.subsystem = SDL_SYSWM_X11;
+			wmmsg.event.xevent = xevent;
+			posted = SDL_PrivateSysWMEvent(&wmmsg);
+		}
+	    }
+	    break;
+
+	    /* Do we need to refresh ourselves? */
+	    case Expose: {
+#ifdef DEBUG_XEVENTS
+printf("Expose (count = %d)\n", xevent.xexpose.count);
+#endif
+		if ( SDL_VideoSurface && (xevent.xexpose.count == 0) ) {
+			X11_RefreshDisplay(this);
+		}
+	    }
+	    break;
+
+	    default: {
+#ifdef DEBUG_XEVENTS
+printf("Unhandled event %d\n", xevent.type);
+#endif
+		/* Only post the event if we're watching for it */
+		if ( SDL_ProcessEvents[SDL_SYSWMEVENT] == SDL_ENABLE ) {
+			SDL_SysWMmsg wmmsg;
+
+			SDL_VERSION(&wmmsg.version);
+			wmmsg.subsystem = SDL_SYSWM_X11;
+			wmmsg.event.xevent = xevent;
+			posted = SDL_PrivateSysWMEvent(&wmmsg);
+		}
+	    }
+	    break;
+	}
+	return(posted);
+}
+
+/* Ack!  XPending() actually performs a blocking read if no events available */
+int X11_Pending(Display *display)
+{
+	/* Flush the display connection and look to see if events are queued */
+	XFlush(display);
+	if ( XEventsQueued(display, QueuedAlready) ) {
+		return(1);
+	}
+
+	/* More drastic measures are required -- see if X is ready to talk */
+	{
+		static struct timeval zero_time;	/* static == 0 */
+		int x11_fd;
+		fd_set fdset;
+
+		x11_fd = ConnectionNumber(display);
+		FD_ZERO(&fdset);
+		FD_SET(x11_fd, &fdset);
+		if ( select(x11_fd+1, &fdset, NULL, NULL, &zero_time) == 1 ) {
+			return(XPending(display));
+		}
+	}
+
+	/* Oh well, nothing is ready .. */
+	return(0);
+}
+
+void X11_PumpEvents(_THIS)
+{
+	int pending;
+
+	/* Update activity every five seconds to prevent screensaver. --ryan. */
+	if (!allow_screensaver) {
+		static Uint32 screensaverTicks;
+		Uint32 nowTicks = SDL_GetTicks();
+		if ((nowTicks - screensaverTicks) > 5000) {
+			XResetScreenSaver(SDL_Display);
+			screensaverTicks = nowTicks;
+		}
+	}
+
+	/* Keep processing pending events */
+	pending = 0;
+	while ( X11_Pending(SDL_Display) ) {
+		X11_DispatchEvent(this);
+		++pending;
+	}
+	if ( switch_waiting ) {
+		Uint32 now;
+
+		now  = SDL_GetTicks();
+		if ( pending || !SDL_VideoSurface ) {
+			/* Try again later... */
+			if ( switch_waiting & SDL_FULLSCREEN ) {
+				switch_time = now + 1500;
+			} else {
+				switch_time = now + 200;
+			}
+		} else if ( (int)(switch_time-now) <= 0 ) {
+			Uint32 go_fullscreen;
+
+			go_fullscreen = switch_waiting & SDL_FULLSCREEN;
+			switch_waiting = 0;
+			if ( SDL_VideoSurface->flags & SDL_FULLSCREEN ) {
+				if ( go_fullscreen ) {
+					X11_EnterFullScreen(this);
+				} else {
+					X11_LeaveFullScreen(this);
+				}
+			}
+			/* Handle focus in/out when grabbed */
+			if ( go_fullscreen ) {
+				X11_GrabInputNoLock(this, this->input_grab);
+			} else {
+				X11_GrabInputNoLock(this, SDL_GRAB_OFF);
+			}
+			X11_CheckMouseModeNoLock(this);
+		}
+	}
+}
+
+void X11_InitKeymap(void)
+{
+	int i;
+
+	/* Odd keys used in international keyboards */
+	for ( i=0; i<SDL_arraysize(ODD_keymap); ++i )
+		ODD_keymap[i] = SDLK_UNKNOWN;
+
+ 	/* Some of these might be mappable to an existing SDLK_ code */
+ 	ODD_keymap[XK_dead_grave&0xFF] = SDLK_COMPOSE;
+ 	ODD_keymap[XK_dead_acute&0xFF] = SDLK_COMPOSE;
+ 	ODD_keymap[XK_dead_tilde&0xFF] = SDLK_COMPOSE;
+ 	ODD_keymap[XK_dead_macron&0xFF] = SDLK_COMPOSE;
+ 	ODD_keymap[XK_dead_breve&0xFF] = SDLK_COMPOSE;
+ 	ODD_keymap[XK_dead_abovedot&0xFF] = SDLK_COMPOSE;
+ 	ODD_keymap[XK_dead_diaeresis&0xFF] = SDLK_COMPOSE;
+ 	ODD_keymap[XK_dead_abovering&0xFF] = SDLK_COMPOSE;
+ 	ODD_keymap[XK_dead_doubleacute&0xFF] = SDLK_COMPOSE;
+ 	ODD_keymap[XK_dead_caron&0xFF] = SDLK_COMPOSE;
+ 	ODD_keymap[XK_dead_cedilla&0xFF] = SDLK_COMPOSE;
+ 	ODD_keymap[XK_dead_ogonek&0xFF] = SDLK_COMPOSE;
+ 	ODD_keymap[XK_dead_iota&0xFF] = SDLK_COMPOSE;
+ 	ODD_keymap[XK_dead_voiced_sound&0xFF] = SDLK_COMPOSE;
+ 	ODD_keymap[XK_dead_semivoiced_sound&0xFF] = SDLK_COMPOSE;
+ 	ODD_keymap[XK_dead_belowdot&0xFF] = SDLK_COMPOSE;
+#ifdef XK_dead_hook
+ 	ODD_keymap[XK_dead_hook&0xFF] = SDLK_COMPOSE;
+#endif
+#ifdef XK_dead_horn
+ 	ODD_keymap[XK_dead_horn&0xFF] = SDLK_COMPOSE;
+#endif
+
+#ifdef XK_dead_circumflex
+	/* These X keysyms have 0xFE as the high byte */
+	ODD_keymap[XK_dead_circumflex&0xFF] = SDLK_CARET;
+#endif
+#ifdef XK_ISO_Level3_Shift
+	ODD_keymap[XK_ISO_Level3_Shift&0xFF] = SDLK_MODE; /* "Alt Gr" key */
+#endif
+
+	/* Map the miscellaneous keys */
+	for ( i=0; i<SDL_arraysize(MISC_keymap); ++i )
+		MISC_keymap[i] = SDLK_UNKNOWN;
+
+	/* These X keysyms have 0xFF as the high byte */
+	MISC_keymap[XK_BackSpace&0xFF] = SDLK_BACKSPACE;
+	MISC_keymap[XK_Tab&0xFF] = SDLK_TAB;
+	MISC_keymap[XK_Clear&0xFF] = SDLK_CLEAR;
+	MISC_keymap[XK_Return&0xFF] = SDLK_RETURN;
+	MISC_keymap[XK_Pause&0xFF] = SDLK_PAUSE;
+	MISC_keymap[XK_Escape&0xFF] = SDLK_ESCAPE;
+	MISC_keymap[XK_Delete&0xFF] = SDLK_DELETE;
+
+	MISC_keymap[XK_KP_0&0xFF] = SDLK_KP0;		/* Keypad 0-9 */
+	MISC_keymap[XK_KP_1&0xFF] = SDLK_KP1;
+	MISC_keymap[XK_KP_2&0xFF] = SDLK_KP2;
+	MISC_keymap[XK_KP_3&0xFF] = SDLK_KP3;
+	MISC_keymap[XK_KP_4&0xFF] = SDLK_KP4;
+	MISC_keymap[XK_KP_5&0xFF] = SDLK_KP5;
+	MISC_keymap[XK_KP_6&0xFF] = SDLK_KP6;
+	MISC_keymap[XK_KP_7&0xFF] = SDLK_KP7;
+	MISC_keymap[XK_KP_8&0xFF] = SDLK_KP8;
+	MISC_keymap[XK_KP_9&0xFF] = SDLK_KP9;
+	MISC_keymap[XK_KP_Insert&0xFF] = SDLK_KP0;
+	MISC_keymap[XK_KP_End&0xFF] = SDLK_KP1;	
+	MISC_keymap[XK_KP_Down&0xFF] = SDLK_KP2;
+	MISC_keymap[XK_KP_Page_Down&0xFF] = SDLK_KP3;
+	MISC_keymap[XK_KP_Left&0xFF] = SDLK_KP4;
+	MISC_keymap[XK_KP_Begin&0xFF] = SDLK_KP5;
+	MISC_keymap[XK_KP_Right&0xFF] = SDLK_KP6;
+	MISC_keymap[XK_KP_Home&0xFF] = SDLK_KP7;
+	MISC_keymap[XK_KP_Up&0xFF] = SDLK_KP8;
+	MISC_keymap[XK_KP_Page_Up&0xFF] = SDLK_KP9;
+	MISC_keymap[XK_KP_Delete&0xFF] = SDLK_KP_PERIOD;
+	MISC_keymap[XK_KP_Decimal&0xFF] = SDLK_KP_PERIOD;
+	MISC_keymap[XK_KP_Divide&0xFF] = SDLK_KP_DIVIDE;
+	MISC_keymap[XK_KP_Multiply&0xFF] = SDLK_KP_MULTIPLY;
+	MISC_keymap[XK_KP_Subtract&0xFF] = SDLK_KP_MINUS;
+	MISC_keymap[XK_KP_Add&0xFF] = SDLK_KP_PLUS;
+	MISC_keymap[XK_KP_Enter&0xFF] = SDLK_KP_ENTER;
+	MISC_keymap[XK_KP_Equal&0xFF] = SDLK_KP_EQUALS;
+
+	MISC_keymap[XK_Up&0xFF] = SDLK_UP;
+	MISC_keymap[XK_Down&0xFF] = SDLK_DOWN;
+	MISC_keymap[XK_Right&0xFF] = SDLK_RIGHT;
+	MISC_keymap[XK_Left&0xFF] = SDLK_LEFT;
+	MISC_keymap[XK_Insert&0xFF] = SDLK_INSERT;
+	MISC_keymap[XK_Home&0xFF] = SDLK_HOME;
+	MISC_keymap[XK_End&0xFF] = SDLK_END;
+	MISC_keymap[XK_Page_Up&0xFF] = SDLK_PAGEUP;
+	MISC_keymap[XK_Page_Down&0xFF] = SDLK_PAGEDOWN;
+
+	MISC_keymap[XK_F1&0xFF] = SDLK_F1;
+	MISC_keymap[XK_F2&0xFF] = SDLK_F2;
+	MISC_keymap[XK_F3&0xFF] = SDLK_F3;
+	MISC_keymap[XK_F4&0xFF] = SDLK_F4;
+	MISC_keymap[XK_F5&0xFF] = SDLK_F5;
+	MISC_keymap[XK_F6&0xFF] = SDLK_F6;
+	MISC_keymap[XK_F7&0xFF] = SDLK_F7;
+	MISC_keymap[XK_F8&0xFF] = SDLK_F8;
+	MISC_keymap[XK_F9&0xFF] = SDLK_F9;
+	MISC_keymap[XK_F10&0xFF] = SDLK_F10;
+	MISC_keymap[XK_F11&0xFF] = SDLK_F11;
+	MISC_keymap[XK_F12&0xFF] = SDLK_F12;
+	MISC_keymap[XK_F13&0xFF] = SDLK_F13;
+	MISC_keymap[XK_F14&0xFF] = SDLK_F14;
+	MISC_keymap[XK_F15&0xFF] = SDLK_F15;
+
+	MISC_keymap[XK_Num_Lock&0xFF] = SDLK_NUMLOCK;
+	MISC_keymap[XK_Caps_Lock&0xFF] = SDLK_CAPSLOCK;
+	MISC_keymap[XK_Scroll_Lock&0xFF] = SDLK_SCROLLOCK;
+	MISC_keymap[XK_Shift_R&0xFF] = SDLK_RSHIFT;
+	MISC_keymap[XK_Shift_L&0xFF] = SDLK_LSHIFT;
+	MISC_keymap[XK_Control_R&0xFF] = SDLK_RCTRL;
+	MISC_keymap[XK_Control_L&0xFF] = SDLK_LCTRL;
+	MISC_keymap[XK_Alt_R&0xFF] = SDLK_RALT;
+	MISC_keymap[XK_Alt_L&0xFF] = SDLK_LALT;
+	MISC_keymap[XK_Meta_R&0xFF] = SDLK_RMETA;
+	MISC_keymap[XK_Meta_L&0xFF] = SDLK_LMETA;
+	MISC_keymap[XK_Super_L&0xFF] = SDLK_LSUPER; /* Left "Windows" */
+	MISC_keymap[XK_Super_R&0xFF] = SDLK_RSUPER; /* Right "Windows */
+	MISC_keymap[XK_Mode_switch&0xFF] = SDLK_MODE; /* "Alt Gr" key */
+	MISC_keymap[XK_Multi_key&0xFF] = SDLK_COMPOSE; /* Multi-key compose */
+
+	MISC_keymap[XK_Help&0xFF] = SDLK_HELP;
+	MISC_keymap[XK_Print&0xFF] = SDLK_PRINT;
+	MISC_keymap[XK_Sys_Req&0xFF] = SDLK_SYSREQ;
+	MISC_keymap[XK_Break&0xFF] = SDLK_BREAK;
+	MISC_keymap[XK_Menu&0xFF] = SDLK_MENU;
+	MISC_keymap[XK_Hyper_R&0xFF] = SDLK_MENU;   /* Windows "Menu" key */
+}
+
+/* Get the translated SDL virtual keysym */
+SDLKey X11_TranslateKeycode(Display *display, KeyCode kc)
+{
+	KeySym xsym;
+	SDLKey key;
+
+	xsym = XKeycodeToKeysym(display, kc, 0);
+#ifdef DEBUG_KEYS
+	fprintf(stderr, "Translating key code %d -> 0x%.4x\n", kc, xsym);
+#endif
+	key = SDLK_UNKNOWN;
+	if ( xsym ) {
+		switch (xsym>>8) {
+		    case 0x1005FF:
+#ifdef SunXK_F36
+			if ( xsym == SunXK_F36 )
+				key = SDLK_F11;
+#endif
+#ifdef SunXK_F37
+			if ( xsym == SunXK_F37 )
+				key = SDLK_F12;
+#endif
+			break;
+		    case 0x00:	/* Latin 1 */
+			key = (SDLKey)(xsym & 0xFF);
+			break;
+		    case 0x01:	/* Latin 2 */
+		    case 0x02:	/* Latin 3 */
+		    case 0x03:	/* Latin 4 */
+		    case 0x04:	/* Katakana */
+		    case 0x05:	/* Arabic */
+		    case 0x06:	/* Cyrillic */
+		    case 0x07:	/* Greek */
+		    case 0x08:	/* Technical */
+		    case 0x0A:	/* Publishing */
+		    case 0x0C:	/* Hebrew */
+		    case 0x0D:	/* Thai */
+			/* These are wrong, but it's better than nothing */
+			key = (SDLKey)(xsym & 0xFF);
+			break;
+		    case 0xFE:
+			key = ODD_keymap[xsym&0xFF];
+			break;
+		    case 0xFF:
+			key = MISC_keymap[xsym&0xFF];
+			break;
+		    default:
+			/*
+			fprintf(stderr, "X11: Unhandled xsym, sym = 0x%04x\n",
+					(unsigned int)xsym);
+			*/
+			break;
+		}
+	} else {
+		/* X11 doesn't know how to translate the key! */
+		switch (kc) {
+		    /* Caution:
+		       These keycodes are from the Microsoft Keyboard
+		     */
+		    case 115:
+			key = SDLK_LSUPER;
+			break;
+		    case 116:
+			key = SDLK_RSUPER;
+			break;
+		    case 117:
+			key = SDLK_MENU;
+			break;
+		    default:
+			/*
+			 * no point in an error message; happens for
+			 * several keys when we get a keymap notify
+			 */
+			break;
+		}
+	}
+	return key;
+}
+
+/* X11 modifier masks for various keys */
+static unsigned meta_l_mask, meta_r_mask, alt_l_mask, alt_r_mask;
+static unsigned num_mask, mode_switch_mask;
+
+static void get_modifier_masks(Display *display)
+{
+	static unsigned got_masks;
+	int i, j;
+	XModifierKeymap *xmods;
+	unsigned n;
+
+	if(got_masks)
+		return;
+
+	xmods = XGetModifierMapping(display);
+	n = xmods->max_keypermod;
+	for(i = 3; i < 8; i++) {
+		for(j = 0; j < n; j++) {
+			KeyCode kc = xmods->modifiermap[i * n + j];
+			KeySym ks = XKeycodeToKeysym(display, kc, 0);
+			unsigned mask = 1 << i;
+			switch(ks) {
+			case XK_Num_Lock:
+				num_mask = mask; break;
+			case XK_Alt_L:
+				alt_l_mask = mask; break;
+			case XK_Alt_R:
+				alt_r_mask = mask; break;
+			case XK_Meta_L:
+				meta_l_mask = mask; break;
+			case XK_Meta_R:
+				meta_r_mask = mask; break;
+			case XK_Mode_switch:
+				mode_switch_mask = mask; break;
+			}
+		}
+	}
+	XFreeModifiermap(xmods);
+	got_masks = 1;
+}
+
+
+/*
+ * This function is semi-official; it is not officially exported and should
+ * not be considered part of the SDL API, but may be used by client code
+ * that *really* needs it (including legacy code).
+ * It is slow, though, and should be avoided if possible.
+ *
+ * Note that it isn't completely accurate either; in particular, multi-key
+ * sequences (dead accents, compose key sequences) will not work since the
+ * state has been irrevocably lost.
+ */
+extern DECLSPEC Uint16 SDLCALL X11_KeyToUnicode(SDLKey, SDLMod);
+
+Uint16 X11_KeyToUnicode(SDLKey keysym, SDLMod modifiers)
+{
+	static int warning = 0;
+	struct SDL_VideoDevice *this = current_video;
+	char keybuf[32];
+	int i;
+	KeySym xsym = 0;
+	XKeyEvent xkey;
+	Uint16 unicode;
+
+	if ( warning ) {
+		warning = 0;
+		fprintf(stderr, "WARNING: Application is using X11_KeyToUnicode().\n");
+		fprintf(stderr, "This is not an official SDL function, please report this as a bug.\n");
+	}
+
+	if ( !this || !SDL_Display ) {
+		return 0;
+	}
+
+	SDL_memset(&xkey, 0, sizeof(xkey));
+	xkey.display = SDL_Display;
+
+	xsym = keysym;		/* last resort if not found */
+	for (i = 0; i < 256; ++i) {
+		if ( MISC_keymap[i] == keysym ) {
+			xsym = 0xFF00 | i;
+			break;
+		} else if ( ODD_keymap[i] == keysym ) {
+			xsym = 0xFE00 | i;
+			break;
+		}
+	}
+
+	xkey.keycode = XKeysymToKeycode(xkey.display, xsym);
+
+	get_modifier_masks(SDL_Display);
+	if(modifiers & KMOD_SHIFT)
+		xkey.state |= ShiftMask;
+	if(modifiers & KMOD_CAPS)
+		xkey.state |= LockMask;
+	if(modifiers & KMOD_CTRL)
+		xkey.state |= ControlMask;
+	if(modifiers & KMOD_MODE)
+		xkey.state |= mode_switch_mask;
+	if(modifiers & KMOD_LALT)
+		xkey.state |= alt_l_mask;
+	if(modifiers & KMOD_RALT)
+		xkey.state |= alt_r_mask;
+	if(modifiers & KMOD_LMETA)
+		xkey.state |= meta_l_mask;
+	if(modifiers & KMOD_RMETA)
+		xkey.state |= meta_r_mask;
+	if(modifiers & KMOD_NUM)
+		xkey.state |= num_mask;
+
+	unicode = 0;
+	if ( XLookupString(&xkey, keybuf, sizeof(keybuf), NULL, NULL) )
+		unicode = (unsigned char)keybuf[0];
+	return(unicode);
+}
+
+
+/*
+ * Called when focus is regained, to read the keyboard state and generate
+ * synthetic keypress/release events.
+ * key_vec is a bit vector of keycodes (256 bits)
+ */
+void X11_SetKeyboardState(Display *display, const char *key_vec)
+{
+	char keys_return[32];
+	int i;
+	Uint8 *kstate = SDL_GetKeyState(NULL);
+	SDLMod modstate;
+	Window junk_window;
+	int x, y;
+	unsigned int mask;
+
+	/* The first time the window is mapped, we initialize key state */
+	if ( ! key_vec ) {
+		XQueryKeymap(display, keys_return);
+		key_vec = keys_return;
+	}
+
+	/* Get the keyboard modifier state */
+	modstate = 0;
+	get_modifier_masks(display);
+	if ( XQueryPointer(display, DefaultRootWindow(display),
+		&junk_window, &junk_window, &x, &y, &x, &y, &mask) ) {
+		if ( mask & LockMask ) {
+			modstate |= KMOD_CAPS;
+		}
+		if ( mask & mode_switch_mask ) {
+			modstate |= KMOD_MODE;
+		}
+		if ( mask & num_mask ) {
+			modstate |= KMOD_NUM;
+		}
+	}
+
+	/* Zero the new keyboard state and generate it */
+	SDL_memset(kstate, 0, SDLK_LAST);
+	/*
+	 * An obvious optimisation is to check entire longwords at a time in
+	 * both loops, but we can't be sure the arrays are aligned so it's not
+	 * worth the extra complexity
+	 */
+	for ( i = 0; i < 32; i++ ) {
+		int j;
+		if ( !key_vec[i] )
+			continue;
+		for ( j = 0; j < 8; j++ ) {
+			if ( key_vec[i] & (1 << j) ) {
+				SDLKey key;
+				KeyCode kc = (i << 3 | j);
+				key = X11_TranslateKeycode(display, kc);
+				if ( key == SDLK_UNKNOWN ) {
+					continue;
+				}
+				kstate[key] = SDL_PRESSED;
+				switch (key) {
+				    case SDLK_LSHIFT:
+					modstate |= KMOD_LSHIFT;
+					break;
+				    case SDLK_RSHIFT:
+					modstate |= KMOD_RSHIFT;
+					break;
+				    case SDLK_LCTRL:
+					modstate |= KMOD_LCTRL;
+					break;
+				    case SDLK_RCTRL:
+					modstate |= KMOD_RCTRL;
+					break;
+				    case SDLK_LALT:
+					modstate |= KMOD_LALT;
+					break;
+				    case SDLK_RALT:
+					modstate |= KMOD_RALT;
+					break;
+				    case SDLK_LMETA:
+					modstate |= KMOD_LMETA;
+					break;
+				    case SDLK_RMETA:
+					modstate |= KMOD_RMETA;
+					break;
+				    default:
+					break;
+				}
+			}
+		}
+	}
+
+	/* Hack - set toggle key state */
+	if ( modstate & KMOD_CAPS ) {
+		kstate[SDLK_CAPSLOCK] = SDL_PRESSED;
+	} else {
+		kstate[SDLK_CAPSLOCK] = SDL_RELEASED;
+	}
+	if ( modstate & KMOD_NUM ) {
+		kstate[SDLK_NUMLOCK] = SDL_PRESSED;
+	} else {
+		kstate[SDLK_NUMLOCK] = SDL_RELEASED;
+	}
+
+	/* Set the final modifier state */
+	SDL_SetModState(modstate);
+}
+
+void X11_InitOSKeymap(_THIS)
+{
+	X11_InitKeymap();
+}
+
diff --git a/sources/packages/l/sdl/sdl/create-1.2.15-x11-events-patch/SDL-1.2.15-new/src/video/x11/SDL_x11events_c.h b/sources/packages/l/sdl/sdl/create-1.2.15-x11-events-patch/SDL-1.2.15-new/src/video/x11/SDL_x11events_c.h
new file mode 100644
index 000000000..d58b69260
--- /dev/null
+++ b/sources/packages/l/sdl/sdl/create-1.2.15-x11-events-patch/SDL-1.2.15-new/src/video/x11/SDL_x11events_c.h
@@ -0,0 +1,30 @@
+/*
+    SDL - Simple DirectMedia Layer
+    Copyright (C) 1997-2012 Sam Lantinga
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+    Sam Lantinga
+    slouken@libsdl.org
+*/
+#include "SDL_config.h"
+
+#include "SDL_x11video.h"
+
+/* Functions to be exported */
+extern void X11_InitOSKeymap(_THIS);
+extern void X11_PumpEvents(_THIS);
+extern void X11_SetKeyboardState(Display *display, const char *key_vec);
+
diff --git a/sources/packages/l/sdl/sdl/create-1.2.15-x11-events-patch/SDL-1.2.15-new/src/video/x11/SDL_x11video.c b/sources/packages/l/sdl/sdl/create-1.2.15-x11-events-patch/SDL-1.2.15-new/src/video/x11/SDL_x11video.c
new file mode 100644
index 000000000..670a2d844
--- /dev/null
+++ b/sources/packages/l/sdl/sdl/create-1.2.15-x11-events-patch/SDL-1.2.15-new/src/video/x11/SDL_x11video.c
@@ -0,0 +1,1569 @@
+/*
+    SDL - Simple DirectMedia Layer
+    Copyright (C) 1997-2012 Sam Lantinga
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+    Sam Lantinga
+    slouken@libsdl.org
+*/
+#include "SDL_config.h"
+
+/* X11 based SDL video driver implementation.
+   Note:  This implementation does not currently need X11 thread locking,
+          since the event thread uses a separate X connection and any
+          additional locking necessary is handled internally.  However,
+          if full locking is neccessary, take a look at XInitThreads().
+*/
+
+#include <unistd.h>
+#include <sys/ioctl.h>
+#ifdef MTRR_SUPPORT
+#include <asm/mtrr.h>
+#include <sys/fcntl.h>
+#endif
+
+#include "SDL_endian.h"
+#include "SDL_timer.h"
+#include "SDL_thread.h"
+#include "SDL_video.h"
+#include "SDL_mouse.h"
+#include "../SDL_sysvideo.h"
+#include "../SDL_pixels_c.h"
+#include "../../events/SDL_events_c.h"
+#include "SDL_x11video.h"
+#include "SDL_x11wm_c.h"
+#include "SDL_x11mouse_c.h"
+#include "SDL_x11events_c.h"
+#include "SDL_x11modes_c.h"
+#include "SDL_x11image_c.h"
+#include "SDL_x11yuv_c.h"
+#include "SDL_x11gl_c.h"
+#include "SDL_x11gamma_c.h"
+#include "../blank_cursor.h"
+
+#ifdef X_HAVE_UTF8_STRING
+#include <locale.h>
+#endif
+
+/* Initialization/Query functions */
+static int X11_VideoInit(_THIS, SDL_PixelFormat *vformat);
+static SDL_Surface *X11_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags);
+static int X11_ToggleFullScreen(_THIS, int on);
+static void X11_UpdateMouse(_THIS);
+static int X11_SetColors(_THIS, int firstcolor, int ncolors,
+			 SDL_Color *colors);
+static int X11_SetGammaRamp(_THIS, Uint16 *ramp);
+static void X11_VideoQuit(_THIS);
+
+
+/* X11 driver bootstrap functions */
+
+static int X11_Available(void)
+{
+	Display *display = NULL;
+	if ( SDL_X11_LoadSymbols() ) {
+		display = XOpenDisplay(NULL);
+		if ( display != NULL ) {
+			XCloseDisplay(display);
+		}
+		SDL_X11_UnloadSymbols();
+	}
+	return(display != NULL);
+}
+
+static void X11_DeleteDevice(SDL_VideoDevice *device)
+{
+	if ( device ) {
+		if ( device->hidden ) {
+			SDL_free(device->hidden);
+		}
+		if ( device->gl_data ) {
+			SDL_free(device->gl_data);
+		}
+		SDL_free(device);
+		SDL_X11_UnloadSymbols();
+	}
+}
+
+static SDL_VideoDevice *X11_CreateDevice(int devindex)
+{
+	SDL_VideoDevice *device = NULL;
+
+	if ( SDL_X11_LoadSymbols() ) {
+		/* Initialize all variables that we clean on shutdown */
+		device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
+		if ( device ) {
+			SDL_memset(device, 0, (sizeof *device));
+			device->hidden = (struct SDL_PrivateVideoData *)
+					SDL_malloc((sizeof *device->hidden));
+			device->gl_data = (struct SDL_PrivateGLData *)
+					SDL_malloc((sizeof *device->gl_data));
+		}
+		if ( (device == NULL) || (device->hidden == NULL) ||
+		                         (device->gl_data == NULL) ) {
+			SDL_OutOfMemory();
+			X11_DeleteDevice(device); /* calls SDL_X11_UnloadSymbols(). */
+			return(0);
+		}
+		SDL_memset(device->hidden, 0, (sizeof *device->hidden));
+		SDL_memset(device->gl_data, 0, (sizeof *device->gl_data));
+
+#if SDL_VIDEO_OPENGL_GLX
+		device->gl_data->swap_interval = -1;
+#endif
+
+		/* Set the driver flags */
+		device->handles_any_size = 1;
+
+		/* Set the function pointers */
+		device->VideoInit = X11_VideoInit;
+		device->ListModes = X11_ListModes;
+		device->SetVideoMode = X11_SetVideoMode;
+		device->ToggleFullScreen = X11_ToggleFullScreen;
+		device->UpdateMouse = X11_UpdateMouse;
+#if SDL_VIDEO_DRIVER_X11_XV
+		device->CreateYUVOverlay = X11_CreateYUVOverlay;
+#endif
+		device->SetColors = X11_SetColors;
+		device->UpdateRects = NULL;
+		device->VideoQuit = X11_VideoQuit;
+		device->AllocHWSurface = X11_AllocHWSurface;
+		device->CheckHWBlit = NULL;
+		device->FillHWRect = NULL;
+		device->SetHWColorKey = NULL;
+		device->SetHWAlpha = NULL;
+		device->LockHWSurface = X11_LockHWSurface;
+		device->UnlockHWSurface = X11_UnlockHWSurface;
+		device->FlipHWSurface = X11_FlipHWSurface;
+		device->FreeHWSurface = X11_FreeHWSurface;
+		device->SetGamma = X11_SetVidModeGamma;
+		device->GetGamma = X11_GetVidModeGamma;
+		device->SetGammaRamp = X11_SetGammaRamp;
+		device->GetGammaRamp = NULL;
+#if SDL_VIDEO_OPENGL_GLX
+		device->GL_LoadLibrary = X11_GL_LoadLibrary;
+		device->GL_GetProcAddress = X11_GL_GetProcAddress;
+		device->GL_GetAttribute = X11_GL_GetAttribute;
+		device->GL_MakeCurrent = X11_GL_MakeCurrent;
+		device->GL_SwapBuffers = X11_GL_SwapBuffers;
+#endif
+		device->SetCaption = X11_SetCaption;
+		device->SetIcon = X11_SetIcon;
+		device->IconifyWindow = X11_IconifyWindow;
+		device->GrabInput = X11_GrabInput;
+		device->GetWMInfo = X11_GetWMInfo;
+		device->FreeWMCursor = X11_FreeWMCursor;
+		device->CreateWMCursor = X11_CreateWMCursor;
+		device->ShowWMCursor = X11_ShowWMCursor;
+		device->WarpWMCursor = X11_WarpWMCursor;
+		device->CheckMouseMode = X11_CheckMouseMode;
+		device->InitOSKeymap = X11_InitOSKeymap;
+		device->PumpEvents = X11_PumpEvents;
+
+		device->free = X11_DeleteDevice;
+	}
+
+	return device;
+}
+
+VideoBootStrap X11_bootstrap = {
+	"x11", "X Window System",
+	X11_Available, X11_CreateDevice
+};
+
+/* Normal X11 error handler routine */
+static int (*X_handler)(Display *, XErrorEvent *) = NULL;
+static int x_errhandler(Display *d, XErrorEvent *e)
+{
+#if SDL_VIDEO_DRIVER_X11_VIDMODE
+	extern int vm_error;
+#endif
+#if SDL_VIDEO_DRIVER_X11_DGAMOUSE
+	extern int dga_error;
+#endif
+
+#if SDL_VIDEO_DRIVER_X11_VIDMODE
+	/* VidMode errors are non-fatal. :) */
+	/* Are the errors offset by one from the error base?
+	   e.g. the error base is 143, the code is 148, and the
+	        actual error is XF86VidModeExtensionDisabled (4) ?
+	 */
+        if ( (vm_error >= 0) &&
+	     (((e->error_code == BadRequest)&&(e->request_code == vm_error)) ||
+	      ((e->error_code > vm_error) &&
+	       (e->error_code <= (vm_error+XF86VidModeNumberErrors)))) ) {
+#ifdef X11_DEBUG
+{ char errmsg[1024];
+  XGetErrorText(d, e->error_code, errmsg, sizeof(errmsg));
+printf("VidMode error: %s\n", errmsg);
+}
+#endif
+        	return(0);
+        }
+#endif /* SDL_VIDEO_DRIVER_X11_VIDMODE */
+
+#if SDL_VIDEO_DRIVER_X11_DGAMOUSE
+	/* DGA errors can be non-fatal. :) */
+        if ( (dga_error >= 0) &&
+	     ((e->error_code > dga_error) &&
+	      (e->error_code <= (dga_error+XF86DGANumberErrors))) ) {
+#ifdef X11_DEBUG
+{ char errmsg[1024];
+  XGetErrorText(d, e->error_code, errmsg, sizeof(errmsg));
+printf("DGA error: %s\n", errmsg);
+}
+#endif
+        	return(0);
+        }
+#endif /* SDL_VIDEO_DRIVER_X11_DGAMOUSE */
+
+	return(X_handler(d,e));
+}
+
+/* X11 I/O error handler routine */
+static int (*XIO_handler)(Display *) = NULL;
+static int xio_errhandler(Display *d)
+{
+	/* Ack!  Lost X11 connection! */
+
+	/* We will crash if we try to clean up our display */
+	if ( SDL_VideoSurface && current_video->hidden->Ximage ) {
+		SDL_VideoSurface->pixels = NULL;
+	}
+	current_video->hidden->X11_Display = NULL;
+
+	/* Continue with the standard X11 error handler */
+	return(XIO_handler(d));
+}
+
+static int (*Xext_handler)(Display *, _Xconst char *, _Xconst char *) = NULL;
+static int xext_errhandler(Display *d, _Xconst char *ext, _Xconst char *reason)
+{
+#ifdef X11_DEBUG
+	printf("Xext error inside SDL (may be harmless):\n");
+	printf("  Extension \"%s\" %s on display \"%s\".\n",
+	       ext, reason, XDisplayString(d));
+#endif
+
+	if (SDL_strcmp(reason, "missing") == 0) {
+		/*
+		 * Since the query itself, elsewhere, can handle a missing extension
+		 *  and the default behaviour in Xlib is to write to stderr, which
+		 *  generates unnecessary bug reports, we just ignore these.
+		 */
+		return 0;
+	}
+
+	/* Everything else goes to the default handler... */
+	return Xext_handler(d, ext, reason);
+}
+
+/* Find out what class name we should use */
+static char *get_classname(char *classname, int maxlen)
+{
+	char *spot;
+#if defined(__LINUX__) || defined(__FREEBSD__)
+	char procfile[1024];
+	char linkfile[1024];
+	int linksize;
+#endif
+
+	/* First allow environment variable override */
+	spot = SDL_getenv("SDL_VIDEO_X11_WMCLASS");
+	if ( spot ) {
+		SDL_strlcpy(classname, spot, maxlen);
+		return classname;
+	}
+
+	/* Next look at the application's executable name */
+#if defined(__LINUX__) || defined(__FREEBSD__)
+#if defined(__LINUX__)
+	SDL_snprintf(procfile, SDL_arraysize(procfile), "/proc/%d/exe", getpid());
+#elif defined(__FREEBSD__)
+	SDL_snprintf(procfile, SDL_arraysize(procfile), "/proc/%d/file", getpid());
+#else
+#error Where can we find the executable name?
+#endif
+	linksize = readlink(procfile, linkfile, sizeof(linkfile)-1);
+	if ( linksize > 0 ) {
+		linkfile[linksize] = '\0';
+		spot = SDL_strrchr(linkfile, '/');
+		if ( spot ) {
+			SDL_strlcpy(classname, spot+1, maxlen);
+		} else {
+			SDL_strlcpy(classname, linkfile, maxlen);
+		}
+		return classname;
+	}
+#endif /* __LINUX__ */
+
+	/* Finally use the default we've used forever */
+	SDL_strlcpy(classname, "SDL_App", maxlen);
+	return classname;
+}
+
+/* Create auxiliary (toplevel) windows with the current visual */
+static void create_aux_windows(_THIS)
+{
+    int x = 0, y = 0;
+    char classname[1024];
+    XSetWindowAttributes xattr;
+    XWMHints *hints;
+    unsigned long app_event_mask;
+    int def_vis = (SDL_Visual == DefaultVisual(SDL_Display, SDL_Screen));
+
+    /* Look up some useful Atoms */
+    WM_DELETE_WINDOW = XInternAtom(SDL_Display, "WM_DELETE_WINDOW", False);
+
+    /* Don't create any extra windows if we are being managed */
+    if ( SDL_windowid ) {
+	FSwindow = 0;
+	WMwindow = SDL_strtol(SDL_windowid, NULL, 0);
+        return;
+    }
+
+    if(FSwindow)
+	XDestroyWindow(SDL_Display, FSwindow);
+
+#if SDL_VIDEO_DRIVER_X11_XINERAMA
+    if ( use_xinerama ) {
+        x = xinerama_info.x_org;
+        y = xinerama_info.y_org;
+    }
+#endif
+    xattr.override_redirect = True;
+    xattr.background_pixel = def_vis ? BlackPixel(SDL_Display, SDL_Screen) : 0;
+    xattr.border_pixel = 0;
+    xattr.colormap = SDL_XColorMap;
+
+    FSwindow = XCreateWindow(SDL_Display, SDL_Root,
+                             x, y, 32, 32, 0,
+			     this->hidden->depth, InputOutput, SDL_Visual,
+			     CWOverrideRedirect | CWBackPixel | CWBorderPixel
+			     | CWColormap,
+			     &xattr);
+
+    XSelectInput(SDL_Display, FSwindow, StructureNotifyMask);
+
+    /* Tell KDE to keep the fullscreen window on top */
+    {
+	XEvent ev;
+	long mask;
+
+	SDL_memset(&ev, 0, sizeof(ev));
+	ev.xclient.type = ClientMessage;
+	ev.xclient.window = SDL_Root;
+	ev.xclient.message_type = XInternAtom(SDL_Display,
+					      "KWM_KEEP_ON_TOP", False);
+	ev.xclient.format = 32;
+	ev.xclient.data.l[0] = FSwindow;
+	ev.xclient.data.l[1] = CurrentTime;
+	mask = SubstructureRedirectMask;
+	XSendEvent(SDL_Display, SDL_Root, False, mask, &ev);
+    }
+
+    hints = NULL;
+    if(WMwindow) {
+	/* All window attributes must survive the recreation */
+	hints = XGetWMHints(SDL_Display, WMwindow);
+	XDestroyWindow(SDL_Display, WMwindow);
+    }
+
+    /* Create the window for windowed management */
+    /* (reusing the xattr structure above) */
+    WMwindow = XCreateWindow(SDL_Display, SDL_Root,
+                             x, y, 32, 32, 0,
+			     this->hidden->depth, InputOutput, SDL_Visual,
+			     CWBackPixel | CWBorderPixel | CWColormap,
+			     &xattr);
+
+    /* Set the input hints so we get keyboard input */
+    if(!hints) {
+	hints = XAllocWMHints();
+	hints->input = True;
+	hints->flags = InputHint;
+    }
+    XSetWMHints(SDL_Display, WMwindow, hints);
+    XFree(hints);
+    X11_SetCaptionNoLock(this, this->wm_title, this->wm_icon);
+
+    app_event_mask = FocusChangeMask | KeyPressMask | KeyReleaseMask
+	| PropertyChangeMask | StructureNotifyMask | KeymapStateMask;
+    XSelectInput(SDL_Display, WMwindow, app_event_mask);
+
+    /* Set the class hints so we can get an icon (AfterStep) */
+    get_classname(classname, sizeof(classname));
+    {
+	XClassHint *classhints;
+	classhints = XAllocClassHint();
+	if(classhints != NULL) {
+	    classhints->res_name = classname;
+	    classhints->res_class = classname;
+	    XSetClassHint(SDL_Display, WMwindow, classhints);
+	    XFree(classhints);
+	}
+    }
+
+	{
+		pid_t pid = getpid();
+		char hostname[256];
+
+		if (pid > 0 && gethostname(hostname, sizeof(hostname)) > -1) {
+			Atom _NET_WM_PID = XInternAtom(SDL_Display, "_NET_WM_PID", False);
+			Atom WM_CLIENT_MACHINE = XInternAtom(SDL_Display, "WM_CLIENT_MACHINE", False);
+			
+			hostname[sizeof(hostname)-1] = '\0';
+			XChangeProperty(SDL_Display, WMwindow, _NET_WM_PID, XA_CARDINAL, 32,
+					PropModeReplace, (unsigned char *)&pid, 1);
+			XChangeProperty(SDL_Display, WMwindow, WM_CLIENT_MACHINE, XA_STRING, 8,
+					PropModeReplace, (unsigned char *)hostname, SDL_strlen(hostname));
+		}
+	}
+
+	/* Setup the communication with the IM server */
+	/* create_aux_windows may be called several times against the same
+	   Display.  We should reuse the SDL_IM if one has been opened for
+	   the Display, so we should not simply reset SDL_IM here.  */
+
+	#ifdef X_HAVE_UTF8_STRING
+	if (SDL_X11_HAVE_UTF8) {
+		/* Discard obsolete resources if any.  */
+		if (SDL_IM != NULL && SDL_Display != XDisplayOfIM(SDL_IM)) {
+			/* Just a double check. I don't think this
+		           code is ever executed. */
+			SDL_SetError("display has changed while an IM is kept");
+			if (SDL_IC) {
+				XUnsetICFocus(SDL_IC);
+				XDestroyIC(SDL_IC);
+				SDL_IC = NULL;
+			}
+			XCloseIM(SDL_IM);
+			SDL_IM = NULL;
+		}
+
+		/* Open an input method.  */
+		if (SDL_IM == NULL) {
+			char *old_locale = NULL, *old_modifiers = NULL;
+			const char *p;
+			size_t n;
+			/* I'm not comfortable to do locale setup
+			   here.  However, we need C library locale
+			   (and xlib modifiers) to be set based on the
+			   user's preference to use XIM, and many
+			   existing game programs doesn't take care of
+			   users' locale preferences, so someone other
+			   than the game program should do it.
+			   Moreover, ones say that some game programs
+			   heavily rely on the C locale behaviour,
+			   e.g., strcol()'s, and we can't change the C
+			   library locale.  Given the situation, I
+			   couldn't find better place to do the
+			   job... */
+
+			/* Save the current (application program's)
+			   locale settings.  */
+			p = setlocale(LC_ALL, NULL);
+			if ( p ) {
+				n = SDL_strlen(p)+1;
+				old_locale = SDL_stack_alloc(char, n);
+				if ( old_locale ) {
+					SDL_strlcpy(old_locale, p, n);
+				}
+			}
+			p = XSetLocaleModifiers(NULL);
+			if ( p ) {
+				n = SDL_strlen(p)+1;
+				old_modifiers = SDL_stack_alloc(char, n);
+				if ( old_modifiers ) {
+					SDL_strlcpy(old_modifiers, p, n);
+				}
+			}
+
+			/* Fetch the user's preferences and open the
+			   input method with them.  */
+			setlocale(LC_ALL, "");
+			XSetLocaleModifiers("");
+			SDL_IM = XOpenIM(SDL_Display, NULL, classname, classname);
+
+			/* Restore the application's locale settings
+			   so that we don't break the application's
+			   expected behaviour.  */
+			if ( old_locale ) {
+				/* We need to restore the C library
+				   locale first, since the
+				   interpretation of the X modifier
+				   may depend on it.  */
+				setlocale(LC_ALL, old_locale);
+				SDL_stack_free(old_locale);
+			}
+			if ( old_modifiers ) {
+				XSetLocaleModifiers(old_modifiers);
+				SDL_stack_free(old_modifiers);
+			}
+		}
+
+		/* Create a new input context for the new window just created.  */
+		if (SDL_IM == NULL) {
+			SDL_SetError("no input method could be opened");
+		} else {
+			if (SDL_IC != NULL) {
+				/* Discard the old IC before creating new one.  */
+			    XUnsetICFocus(SDL_IC);
+			    XDestroyIC(SDL_IC);
+			}
+			/* Theoretically we should check the current IM supports
+			   PreeditNothing+StatusNothing style (i.e., root window method)
+			   before creating the IC.  However, it is the bottom line method,
+			   and we supports any other options.  If the IM didn't support
+			   root window method, the following call fails, and SDL falls
+			   back to pre-XIM keyboard handling.  */
+			SDL_IC = pXCreateIC(SDL_IM,
+					XNClientWindow, WMwindow,
+					XNFocusWindow, WMwindow,
+					XNInputStyle, XIMPreeditNothing | XIMStatusNothing,
+					XNResourceName, classname,
+					XNResourceClass, classname,
+					NULL);
+
+			if (SDL_IC == NULL) {
+				SDL_SetError("no input context could be created");
+				XCloseIM(SDL_IM);
+				SDL_IM = NULL;
+			} else {
+				/* We need to receive X events that an IM wants and to pass
+				   them to the IM through XFilterEvent. The set of events may
+				   vary depending on the IM implementation and the options
+				   specified through various routes. Although unlikely, the
+				   xlib specification allows IM to change the event requirement
+				   with its own circumstances, it is safe to call SelectInput
+				   whenever we re-create an IC.  */
+				unsigned long mask = 0;
+				char *ret = pXGetICValues(SDL_IC, XNFilterEvents, &mask, NULL);
+				if (ret != NULL) {
+					XUnsetICFocus(SDL_IC);
+					XDestroyIC(SDL_IC);
+					SDL_IC = NULL;
+					SDL_SetError("no input context could be created");
+					XCloseIM(SDL_IM);
+					SDL_IM = NULL;
+				} else {
+					XSelectInput(SDL_Display, WMwindow, app_event_mask | mask);
+					XSetICFocus(SDL_IC);
+				}
+			}
+		}
+	}
+	#endif
+
+	/* Allow the window to be deleted by the window manager */
+	XSetWMProtocols(SDL_Display, WMwindow, &WM_DELETE_WINDOW, 1);
+}
+
+static int X11_VideoInit(_THIS, SDL_PixelFormat *vformat)
+{
+	const char *env;
+	char *display;
+	int i;
+
+	/* Open the X11 display */
+	display = NULL;		/* Get it from DISPLAY environment variable */
+
+	if ( (SDL_strncmp(XDisplayName(display), ":", 1) == 0) ||
+	     (SDL_strncmp(XDisplayName(display), "unix:", 5) == 0) ) {
+		local_X11 = 1;
+	} else {
+		local_X11 = 0;
+	}
+	SDL_Display = XOpenDisplay(display);
+#if defined(__osf__) && defined(SDL_VIDEO_DRIVER_X11_DYNAMIC)
+	/* On Tru64 if linking without -lX11, it fails and you get following message.
+	 * Xlib: connection to ":0.0" refused by server
+	 * Xlib: XDM authorization key matches an existing client!
+	 *
+	 * It succeeds if retrying 1 second later
+	 * or if running xhost +localhost on shell.
+	 *
+	 */
+	if ( SDL_Display == NULL ) {
+		SDL_Delay(1000);
+		SDL_Display = XOpenDisplay(display);
+	}
+#endif
+	if ( SDL_Display == NULL ) {
+		SDL_SetError("Couldn't open X11 display");
+		return(-1);
+	}
+#ifdef X11_DEBUG
+	XSynchronize(SDL_Display, True);
+#endif
+
+	/* Create an alternate X display for graphics updates -- allows us
+	   to do graphics updates in a separate thread from event handling.
+	   Thread-safe X11 doesn't seem to exist.
+	 */
+	GFX_Display = XOpenDisplay(display);
+	if ( GFX_Display == NULL ) {
+		XCloseDisplay(SDL_Display);
+		SDL_Display = NULL;
+		SDL_SetError("Couldn't open X11 display");
+		return(-1);
+	}
+
+	/* Set the normal X error handler */
+	X_handler = XSetErrorHandler(x_errhandler);
+
+	/* Set the error handler if we lose the X display */
+	XIO_handler = XSetIOErrorHandler(xio_errhandler);
+
+	/* Set the X extension error handler */
+	Xext_handler = XSetExtensionErrorHandler(xext_errhandler);
+
+	/* use default screen (from $DISPLAY) */
+	SDL_Screen = DefaultScreen(SDL_Display);
+
+#ifndef NO_SHARED_MEMORY
+	/* Check for MIT shared memory extension */
+	use_mitshm = 0;
+	if ( local_X11 ) {
+		use_mitshm = XShmQueryExtension(SDL_Display);
+	}
+#endif /* NO_SHARED_MEMORY */
+
+	/* Get the available video modes */
+	if(X11_GetVideoModes(this) < 0) {
+		XCloseDisplay(GFX_Display);
+		GFX_Display = NULL;
+		XCloseDisplay(SDL_Display);
+		SDL_Display = NULL;
+	    return -1;
+	}
+
+	/* Determine the current screen size */
+	this->info.current_w = DisplayWidth(SDL_Display, SDL_Screen);
+	this->info.current_h = DisplayHeight(SDL_Display, SDL_Screen);
+
+	/* Determine the default screen depth:
+	   Use the default visual (or at least one with the same depth) */
+	SDL_DisplayColormap = DefaultColormap(SDL_Display, SDL_Screen);
+	for(i = 0; i < this->hidden->nvisuals; i++)
+	    if(this->hidden->visuals[i].depth == DefaultDepth(SDL_Display,
+							      SDL_Screen))
+		break;
+	if(i == this->hidden->nvisuals) {
+	    /* default visual was useless, take the deepest one instead */
+	    i = 0;
+	}
+	SDL_Visual = this->hidden->visuals[i].visual;
+	if ( SDL_Visual == DefaultVisual(SDL_Display, SDL_Screen) ) {
+	    SDL_XColorMap = SDL_DisplayColormap;
+	} else {
+	    SDL_XColorMap = XCreateColormap(SDL_Display, SDL_Root,
+					    SDL_Visual, AllocNone);
+	}
+	this->hidden->depth = this->hidden->visuals[i].depth;
+	vformat->BitsPerPixel = this->hidden->visuals[i].bpp;
+	if ( vformat->BitsPerPixel > 8 ) {
+		vformat->Rmask = SDL_Visual->red_mask;
+	  	vformat->Gmask = SDL_Visual->green_mask;
+	  	vformat->Bmask = SDL_Visual->blue_mask;
+	}
+	if ( this->hidden->depth == 32 ) {
+		vformat->Amask = (0xFFFFFFFF & ~(vformat->Rmask|vformat->Gmask|vformat->Bmask));
+	}
+	X11_SaveVidModeGamma(this);
+
+	/* Allow environment override of screensaver disable. */
+	env = SDL_getenv("SDL_VIDEO_ALLOW_SCREENSAVER");
+	if ( env ) {
+		allow_screensaver = SDL_atoi(env);
+	} else {
+#ifdef SDL_VIDEO_DISABLE_SCREENSAVER
+		allow_screensaver = 0;
+#else
+		allow_screensaver = 1;
+#endif
+	}
+
+	/* See if we have been passed a window to use */
+	SDL_windowid = SDL_getenv("SDL_WINDOWID");
+
+	/* Create the fullscreen and managed windows */
+	create_aux_windows(this);
+
+	/* Create the blank cursor */
+	SDL_BlankCursor = this->CreateWMCursor(this, blank_cdata, blank_cmask,
+					BLANK_CWIDTH, BLANK_CHEIGHT,
+						BLANK_CHOTX, BLANK_CHOTY);
+
+	/* Fill in some window manager capabilities */
+	this->info.wm_available = 1;
+
+	/* We're done! */
+	XFlush(SDL_Display);
+	return(0);
+}
+
+static void X11_DestroyWindow(_THIS, SDL_Surface *screen)
+{
+	/* Clean up OpenGL */
+	if ( screen ) {
+		screen->flags &= ~(SDL_OPENGL|SDL_OPENGLBLIT);
+	}
+	X11_GL_Shutdown(this);
+
+	if ( ! SDL_windowid ) {
+		/* Hide the managed window */
+		if ( WMwindow ) {
+			XUnmapWindow(SDL_Display, WMwindow);
+		}
+		if ( screen && (screen->flags & SDL_FULLSCREEN) ) {
+			screen->flags &= ~SDL_FULLSCREEN;
+			X11_LeaveFullScreen(this);
+		}
+
+		/* Destroy the output window */
+		if ( SDL_Window ) {
+			XDestroyWindow(SDL_Display, SDL_Window);
+		}
+
+		/* Free the colormap entries */
+		if ( SDL_XPixels ) {
+			int numcolors;
+			unsigned long pixel;
+			numcolors = SDL_Visual->map_entries;
+			for ( pixel=0; pixel<numcolors; ++pixel ) {
+				while ( SDL_XPixels[pixel] > 0 ) {
+					XFreeColors(GFX_Display,
+						SDL_DisplayColormap,&pixel,1,0);
+					--SDL_XPixels[pixel];
+				}
+			}
+			SDL_free(SDL_XPixels);
+			SDL_XPixels = NULL;
+		} 
+
+		/* Free the graphics context */
+		if ( SDL_GC ) {
+			XFreeGC(SDL_Display, SDL_GC);
+			SDL_GC = 0;
+		}
+	}
+}
+
+static SDL_bool X11_WindowPosition(_THIS, int *x, int *y, int w, int h)
+{
+	const char *window = SDL_getenv("SDL_VIDEO_WINDOW_POS");
+	const char *center = SDL_getenv("SDL_VIDEO_CENTERED");
+	if ( window ) {
+		if ( SDL_sscanf(window, "%d,%d", x, y) == 2 ) {
+			return SDL_TRUE;
+		}
+		if ( SDL_strcmp(window, "center") == 0 ) {
+			center = window;
+		}
+	}
+	if ( center ) {
+		*x = (DisplayWidth(SDL_Display, SDL_Screen) - w)/2;
+		*y = (DisplayHeight(SDL_Display, SDL_Screen) - h)/2;
+		return SDL_TRUE;
+	}
+	return SDL_FALSE;
+}
+
+static void X11_SetSizeHints(_THIS, int w, int h, Uint32 flags)
+{
+	XSizeHints *hints;
+
+	hints = XAllocSizeHints();
+	if ( hints ) {
+		if (!(flags & SDL_RESIZABLE)) {
+			hints->min_width = hints->max_width = w;
+			hints->min_height = hints->max_height = h;
+			hints->flags = PMaxSize | PMinSize;
+		}
+		if ( flags & SDL_FULLSCREEN ) {
+			hints->x = 0;
+			hints->y = 0;
+			hints->flags |= USPosition;
+		} else
+		/* Center it, if desired */
+		if ( X11_WindowPosition(this, &hints->x, &hints->y, w, h) ) {
+			hints->flags |= USPosition;
+
+			/* Hints must be set before moving the window, otherwise an
+			   unwanted ConfigureNotify event will be issued */
+			XSetWMNormalHints(SDL_Display, WMwindow, hints);
+
+			XMoveWindow(SDL_Display, WMwindow, hints->x, hints->y);
+
+			/* Flush the resize event so we don't catch it later */
+			XSync(SDL_Display, True);
+		}
+		XSetWMNormalHints(SDL_Display, WMwindow, hints);
+		XFree(hints);
+	}
+
+	/* Respect the window caption style */
+	if ( flags & SDL_NOFRAME ) {
+		SDL_bool set;
+		Atom WM_HINTS;
+
+		/* We haven't modified the window manager hints yet */
+		set = SDL_FALSE;
+
+		/* First try to set MWM hints */
+		WM_HINTS = XInternAtom(SDL_Display, "_MOTIF_WM_HINTS", True);
+		if ( WM_HINTS != None ) {
+			/* Hints used by Motif compliant window managers */
+			struct {
+				unsigned long flags;
+				unsigned long functions;
+				unsigned long decorations;
+				long input_mode;
+				unsigned long status;
+			} MWMHints = { (1L << 1), 0, 0, 0, 0 };
+
+			XChangeProperty(SDL_Display, WMwindow,
+			                WM_HINTS, WM_HINTS, 32,
+			                PropModeReplace,
+					(unsigned char *)&MWMHints,
+					sizeof(MWMHints)/sizeof(long));
+			set = SDL_TRUE;
+		}
+		/* Now try to set KWM hints */
+		WM_HINTS = XInternAtom(SDL_Display, "KWM_WIN_DECORATION", True);
+		if ( WM_HINTS != None ) {
+			long KWMHints = 0;
+
+			XChangeProperty(SDL_Display, WMwindow,
+			                WM_HINTS, WM_HINTS, 32,
+			                PropModeReplace,
+					(unsigned char *)&KWMHints,
+					sizeof(KWMHints)/sizeof(long));
+			set = SDL_TRUE;
+		}
+		/* Now try to set GNOME hints */
+		WM_HINTS = XInternAtom(SDL_Display, "_WIN_HINTS", True);
+		if ( WM_HINTS != None ) {
+			long GNOMEHints = 0;
+
+			XChangeProperty(SDL_Display, WMwindow,
+			                WM_HINTS, WM_HINTS, 32,
+			                PropModeReplace,
+					(unsigned char *)&GNOMEHints,
+					sizeof(GNOMEHints)/sizeof(long));
+			set = SDL_TRUE;
+		}
+		/* Finally set the transient hints if necessary */
+		if ( ! set ) {
+			XSetTransientForHint(SDL_Display, WMwindow, SDL_Root);
+		}
+	} else {
+		SDL_bool set;
+		Atom WM_HINTS;
+
+		/* We haven't modified the window manager hints yet */
+		set = SDL_FALSE;
+
+		/* First try to unset MWM hints */
+		WM_HINTS = XInternAtom(SDL_Display, "_MOTIF_WM_HINTS", True);
+		if ( WM_HINTS != None ) {
+			XDeleteProperty(SDL_Display, WMwindow, WM_HINTS);
+			set = SDL_TRUE;
+		}
+		/* Now try to unset KWM hints */
+		WM_HINTS = XInternAtom(SDL_Display, "KWM_WIN_DECORATION", True);
+		if ( WM_HINTS != None ) {
+			XDeleteProperty(SDL_Display, WMwindow, WM_HINTS);
+			set = SDL_TRUE;
+		}
+		/* Now try to unset GNOME hints */
+		WM_HINTS = XInternAtom(SDL_Display, "_WIN_HINTS", True);
+		if ( WM_HINTS != None ) {
+			XDeleteProperty(SDL_Display, WMwindow, WM_HINTS);
+			set = SDL_TRUE;
+		}
+		/* Finally unset the transient hints if necessary */
+		if ( ! set ) {
+			XDeleteProperty(SDL_Display, WMwindow, XA_WM_TRANSIENT_FOR);
+		}
+	}
+}
+
+static int X11_CreateWindow(_THIS, SDL_Surface *screen,
+			    int w, int h, int bpp, Uint32 flags)
+{
+	int i, depth;
+	Visual *vis;
+	int vis_change;
+	Uint32 Amask;
+
+	/* If a window is already present, destroy it and start fresh */
+	if ( SDL_Window ) {
+		X11_DestroyWindow(this, screen);
+		switch_waiting = 0; /* Prevent jump back to now-meaningless state. */
+	}
+
+	/* See if we have been given a window id */
+	if ( SDL_windowid ) {
+		SDL_Window = SDL_strtol(SDL_windowid, NULL, 0);
+	} else {
+		SDL_Window = 0;
+	}
+
+	/* find out which visual we are going to use */
+	if ( flags & SDL_OPENGL ) {
+		XVisualInfo *vi;
+
+		vi = X11_GL_GetVisual(this);
+		if( !vi ) {
+			return -1;
+		}
+		vis = vi->visual;
+		depth = vi->depth;
+	} else if ( SDL_windowid ) {
+		XWindowAttributes a;
+
+		XGetWindowAttributes(SDL_Display, SDL_Window, &a);
+		vis = a.visual;
+		depth = a.depth;
+	} else {
+		for ( i = 0; i < this->hidden->nvisuals; i++ ) {
+			if ( this->hidden->visuals[i].bpp == bpp )
+				break;
+		}
+		if ( i == this->hidden->nvisuals ) {
+			SDL_SetError("No matching visual for requested depth");
+			return -1;	/* should never happen */
+		}
+		vis = this->hidden->visuals[i].visual;
+		depth = this->hidden->visuals[i].depth;
+	}
+#ifdef X11_DEBUG
+        printf("Choosing %s visual at %d bpp - %d colormap entries\n", vis->class == PseudoColor ? "PseudoColor" : (vis->class == TrueColor ? "TrueColor" : (vis->class == DirectColor ? "DirectColor" : "Unknown")), depth, vis->map_entries);
+#endif
+	vis_change = (vis != SDL_Visual);
+	SDL_Visual = vis;
+	this->hidden->depth = depth;
+
+	/* Allocate the new pixel format for this video mode */
+	if ( this->hidden->depth == 32 ) {
+		Amask = (0xFFFFFFFF & ~(vis->red_mask|vis->green_mask|vis->blue_mask));
+	} else {
+		Amask = 0;
+	}
+	if ( ! SDL_ReallocFormat(screen, bpp,
+			vis->red_mask, vis->green_mask, vis->blue_mask, Amask) ) {
+		return -1;
+	}
+
+	/* Create the appropriate colormap */
+	if ( SDL_XColorMap != SDL_DisplayColormap ) {
+		XFreeColormap(SDL_Display, SDL_XColorMap);
+	}
+	if ( SDL_Visual->class == PseudoColor ) {
+	    int ncolors;
+
+	    /* Allocate the pixel flags */
+	    ncolors = SDL_Visual->map_entries;
+	    SDL_XPixels = SDL_malloc(ncolors * sizeof(int));
+	    if(SDL_XPixels == NULL) {
+		SDL_OutOfMemory();
+		return -1;
+	    }
+	    SDL_memset(SDL_XPixels, 0, ncolors * sizeof(*SDL_XPixels));
+
+	    /* always allocate a private colormap on non-default visuals */
+	    if ( SDL_Visual != DefaultVisual(SDL_Display, SDL_Screen) ) {
+		flags |= SDL_HWPALETTE;
+	    }
+	    if ( flags & SDL_HWPALETTE ) {
+		screen->flags |= SDL_HWPALETTE;
+		SDL_XColorMap = XCreateColormap(SDL_Display, SDL_Root,
+		                                SDL_Visual, AllocAll);
+	    } else {
+		SDL_XColorMap = SDL_DisplayColormap;
+	    }
+	} else if ( SDL_Visual->class == DirectColor ) {
+
+	    /* Create a colormap which we can manipulate for gamma */
+	    SDL_XColorMap = XCreateColormap(SDL_Display, SDL_Root,
+		                            SDL_Visual, AllocAll);
+            XSync(SDL_Display, False);
+
+	    /* Initialize the colormap to the identity mapping */
+	    SDL_GetGammaRamp(0, 0, 0);
+	    this->screen = screen;
+	    X11_SetGammaRamp(this, this->gamma);
+	    this->screen = NULL;
+	} else {
+	    /* Create a read-only colormap for our window */
+	    SDL_XColorMap = XCreateColormap(SDL_Display, SDL_Root,
+	                                    SDL_Visual, AllocNone);
+	}
+
+	/* Recreate the auxiliary windows, if needed (required for GL) */
+	if ( vis_change )
+	    create_aux_windows(this);
+
+	if(screen->flags & SDL_HWPALETTE) {
+	    /* Since the full-screen window might have got a nonzero background
+	       colour (0 is white on some displays), we should reset the
+	       background to 0 here since that is what the user expects
+	       with a private colormap */
+	    XSetWindowBackground(SDL_Display, FSwindow, 0);
+	    XClearWindow(SDL_Display, FSwindow);
+	}
+
+	/* resize the (possibly new) window manager window */
+	if( !SDL_windowid ) {
+	        X11_SetSizeHints(this, w, h, flags);
+		window_w = w;
+		window_h = h;
+		XResizeWindow(SDL_Display, WMwindow, w, h);
+	}
+
+	/* Create (or use) the X11 display window */
+	if ( !SDL_windowid ) {
+		if ( flags & SDL_OPENGL ) {
+			if ( X11_GL_CreateWindow(this, w, h) < 0 ) {
+				return(-1);
+			}
+		} else {
+			XSetWindowAttributes swa;
+
+			swa.background_pixel = 0;
+			swa.border_pixel = 0;
+			swa.colormap = SDL_XColorMap;
+			SDL_Window = XCreateWindow(SDL_Display, WMwindow,
+		                           	0, 0, w, h, 0, depth,
+		                           	InputOutput, SDL_Visual,
+		                           	CWBackPixel | CWBorderPixel
+		                           	| CWColormap, &swa);
+		}
+		/* Only manage our input if we own the window */
+		XSelectInput(SDL_Display, SDL_Window,
+					( EnterWindowMask | LeaveWindowMask
+					| ButtonPressMask | ButtonReleaseMask
+					| PointerMotionMask | ExposureMask ));
+	}
+	/* Create the graphics context here, once we have a window */
+	if ( flags & SDL_OPENGL ) {
+		if ( X11_GL_CreateContext(this) < 0 ) {
+			return(-1);
+		} else {
+			screen->flags |= SDL_OPENGL;
+		}
+	} else {
+		XGCValues gcv;
+
+		gcv.graphics_exposures = False;
+		SDL_GC = XCreateGC(SDL_Display, SDL_Window,
+		                   GCGraphicsExposures, &gcv);
+		if ( ! SDL_GC ) {
+			SDL_SetError("Couldn't create graphics context");
+			return(-1);
+		}
+	}
+
+	/* Set our colormaps when not setting a GL mode */
+	if ( ! (flags & SDL_OPENGL) ) {
+		XSetWindowColormap(SDL_Display, SDL_Window, SDL_XColorMap);
+		if( !SDL_windowid ) {
+		    XSetWindowColormap(SDL_Display, FSwindow, SDL_XColorMap);
+		    XSetWindowColormap(SDL_Display, WMwindow, SDL_XColorMap);
+		}
+	}
+
+#if 1 /* This is an experiment - are the graphics faster now? - nope. */
+	if ( SDL_getenv("SDL_VIDEO_X11_BACKINGSTORE") )
+#endif
+	/* Cache the window in the server, when possible */
+	{
+		Screen *xscreen;
+		XSetWindowAttributes a;
+
+		xscreen = ScreenOfDisplay(SDL_Display, SDL_Screen);
+		a.backing_store = DoesBackingStore(xscreen);
+		if ( a.backing_store != NotUseful ) {
+			XChangeWindowAttributes(SDL_Display, SDL_Window,
+			                        CWBackingStore, &a);
+		}
+	}
+
+	/* Map them both and go fullscreen, if requested */
+	if ( ! SDL_windowid ) {
+		XMapWindow(SDL_Display, SDL_Window);
+		XMapWindow(SDL_Display, WMwindow);
+		X11_WaitMapped(this, WMwindow);
+		if ( flags & SDL_FULLSCREEN ) {
+			screen->flags |= SDL_FULLSCREEN;
+			X11_EnterFullScreen(this);
+		} else {
+			screen->flags &= ~SDL_FULLSCREEN;
+		}
+	}
+	
+	return(0);
+}
+
+static int X11_ResizeWindow(_THIS,
+			SDL_Surface *screen, int w, int h, Uint32 flags)
+{
+	if ( ! SDL_windowid ) {
+		/* Resize the window manager window */
+		X11_SetSizeHints(this, w, h, flags);
+		window_w = w;
+		window_h = h;
+		XResizeWindow(SDL_Display, WMwindow, w, h);
+
+		/* Resize the fullscreen and display windows */
+		if ( flags & SDL_FULLSCREEN ) {
+			if ( screen->flags & SDL_FULLSCREEN ) {
+				X11_ResizeFullScreen(this);
+			} else {
+				screen->flags |= SDL_FULLSCREEN;
+				X11_EnterFullScreen(this);
+			}
+		} else {
+			if ( screen->flags & SDL_FULLSCREEN ) {
+				screen->flags &= ~SDL_FULLSCREEN;
+				X11_LeaveFullScreen(this);
+			}
+		}
+		XResizeWindow(SDL_Display, SDL_Window, w, h);
+	}
+	return(0);
+}
+
+SDL_Surface *X11_SetVideoMode(_THIS, SDL_Surface *current,
+				int width, int height, int bpp, Uint32 flags)
+{
+	Uint32 saved_flags;
+
+	/* Lock the event thread, in multi-threading environments */
+	SDL_Lock_EventThread();
+
+	/* Check the combination of flags we were passed */
+	if ( flags & SDL_FULLSCREEN ) {
+		/* Clear fullscreen flag if not supported */
+		if ( SDL_windowid ) {
+			flags &= ~SDL_FULLSCREEN;
+		}
+	}
+
+	/* Flush any delayed updates */
+	XSync(GFX_Display, False);
+
+	/* Set up the X11 window */
+	saved_flags = current->flags;
+	if ( (SDL_Window) && ((saved_flags&SDL_OPENGL) == (flags&SDL_OPENGL))
+	      && (bpp == current->format->BitsPerPixel)
+          && ((saved_flags&SDL_NOFRAME) == (flags&SDL_NOFRAME)) ) {
+		if (X11_ResizeWindow(this, current, width, height, flags) < 0) {
+			current = NULL;
+			goto done;
+		}
+	} else {
+		if (X11_CreateWindow(this,current,width,height,bpp,flags) < 0) {
+			current = NULL;
+			goto done;
+		}
+	}
+
+	/* Update the internal keyboard state */
+	X11_SetKeyboardState(SDL_Display, NULL);
+
+	/* When the window is first mapped, ignore non-modifier keys */
+	if ( !current->w && !current->h ) {
+		Uint8 *keys = SDL_GetKeyState(NULL);
+		int i;
+		for ( i = 0; i < SDLK_LAST; ++i ) {
+			switch (i) {
+			    case SDLK_NUMLOCK:
+			    case SDLK_CAPSLOCK:
+			    case SDLK_LCTRL:
+			    case SDLK_RCTRL:
+			    case SDLK_LSHIFT:
+			    case SDLK_RSHIFT:
+			    case SDLK_LALT:
+			    case SDLK_RALT:
+			    case SDLK_LMETA:
+			    case SDLK_RMETA:
+			    case SDLK_MODE:
+				break;
+			    default:
+				keys[i] = SDL_RELEASED;
+				break;
+			}
+		}
+	}
+
+	/* Set up the new mode framebuffer */
+	if ( ((current->w != width) || (current->h != height)) ||
+             ((saved_flags&SDL_OPENGL) != (flags&SDL_OPENGL)) ) {
+		current->w = width;
+		current->h = height;
+		current->pitch = SDL_CalculatePitch(current);
+		if (X11_ResizeImage(this, current, flags) < 0) {
+			current = NULL;
+			goto done;
+		}
+	}
+
+	/* Clear these flags and set them only if they are in the new set. */
+	current->flags &= ~(SDL_RESIZABLE|SDL_NOFRAME);
+	current->flags |= (flags&(SDL_RESIZABLE|SDL_NOFRAME));
+
+  done:
+	/* Release the event thread */
+	XSync(SDL_Display, False);
+	SDL_Unlock_EventThread();
+
+	/* We're done! */
+	return(current);
+}
+
+static int X11_ToggleFullScreen(_THIS, int on)
+{
+	Uint32 event_thread;
+
+	/* Don't switch if we don't own the window */
+	if ( SDL_windowid ) {
+		return(0);
+	}
+
+	/* Don't lock if we are the event thread */
+	event_thread = SDL_EventThreadID();
+	if ( event_thread && (SDL_ThreadID() == event_thread) ) {
+		event_thread = 0;
+	}
+	if ( event_thread ) {
+		SDL_Lock_EventThread();
+	}
+	if ( on ) {
+		this->screen->flags |= SDL_FULLSCREEN;
+		X11_EnterFullScreen(this);
+	} else {
+		this->screen->flags &= ~SDL_FULLSCREEN;
+		X11_LeaveFullScreen(this);
+	}
+	X11_RefreshDisplay(this);
+	if ( event_thread ) {
+		SDL_Unlock_EventThread();
+	}
+	SDL_ResetKeyboard();
+	return(1);
+}
+
+/* Update the current mouse state and position */
+static void X11_UpdateMouse(_THIS)
+{
+	Window u1; int u2;
+	Window current_win;
+	int x, y;
+	unsigned int mask;
+
+	/* Lock the event thread, in multi-threading environments */
+	SDL_Lock_EventThread();
+	if ( XQueryPointer(SDL_Display, SDL_Window, &u1, &current_win,
+	                   &u2, &u2, &x, &y, &mask) ) {
+		if ( (x >= 0) && (x < SDL_VideoSurface->w) &&
+		     (y >= 0) && (y < SDL_VideoSurface->h) ) {
+			SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS);
+			SDL_PrivateMouseMotion(0, 0, x, y);
+		} else {
+			SDL_PrivateAppActive(0, SDL_APPMOUSEFOCUS);
+		}
+	}
+	SDL_Unlock_EventThread();
+}
+
+/* simple colour distance metric. Supposed to be better than a plain
+   Euclidian distance anyway. */
+#define COLOUR_FACTOR 3
+#define LIGHT_FACTOR 1
+#define COLOUR_DIST(r1, g1, b1, r2, g2, b2)				\
+	(COLOUR_FACTOR * (abs(r1 - r2) + abs(g1 - g2) + abs(b1 - b2))	\
+	 + LIGHT_FACTOR * abs(r1 + g1 + b1 - (r2 + g2 + b2)))
+
+static void allocate_nearest(_THIS, SDL_Color *colors,
+			     SDL_Color *want, int nwant)
+{
+	/*
+	 * There is no way to know which ones to choose from, so we retrieve
+	 * the entire colormap and try the nearest possible, until we find one
+	 * that is shared.
+	 */
+	XColor all[256];
+	int i;
+	for(i = 0; i < 256; i++)
+		all[i].pixel = i;
+	/* 
+	 * XQueryColors sets the flags in the XColor struct, so we use
+	 * that to keep track of which colours are available
+	 */
+	XQueryColors(GFX_Display, SDL_XColorMap, all, 256);
+
+	for(i = 0; i < nwant; i++) {
+		XColor *c;
+		int j;
+		int best = 0;
+		int mindist = 0x7fffffff;
+		int ri = want[i].r;
+		int gi = want[i].g;
+		int bi = want[i].b;
+		for(j = 0; j < 256; j++) {
+			int rj, gj, bj, d2;
+			if(!all[j].flags)
+				continue;	/* unavailable colour cell */
+			rj = all[j].red >> 8;
+			gj = all[j].green >> 8;
+			bj = all[j].blue >> 8;
+			d2 = COLOUR_DIST(ri, gi, bi, rj, gj, bj);
+			if(d2 < mindist) {
+				mindist = d2;
+				best = j;
+			}
+		}
+		if(SDL_XPixels[best])
+			continue; /* already allocated, waste no more time */
+		c = all + best;
+		if(XAllocColor(GFX_Display, SDL_XColorMap, c)) {
+			/* got it */
+			colors[c->pixel].r = c->red >> 8;
+			colors[c->pixel].g = c->green >> 8;
+			colors[c->pixel].b = c->blue >> 8;
+			++SDL_XPixels[c->pixel];
+		} else {
+			/* 
+			 * The colour couldn't be allocated, probably being
+			 * owned as a r/w cell by another client. Flag it as
+			 * unavailable and try again. The termination of the
+			 * loop is guaranteed since at least black and white
+			 * are always there.
+			 */
+			c->flags = 0;
+			i--;
+		}
+	}
+}
+
+int X11_SetColors(_THIS, int firstcolor, int ncolors, SDL_Color *colors)
+{
+	int nrej = 0;
+
+	/* Check to make sure we have a colormap allocated */
+	if ( SDL_XPixels == NULL ) {
+		return(0);
+	}
+	if ( (this->screen->flags & SDL_HWPALETTE) == SDL_HWPALETTE ) {
+	        /* private writable colormap: just set the colours we need */
+	        XColor  *xcmap;
+		int i;
+	        xcmap = SDL_stack_alloc(XColor, ncolors);
+		if(xcmap == NULL)
+		        return 0;
+		for ( i=0; i<ncolors; ++i ) {
+			xcmap[i].pixel = i + firstcolor;
+			xcmap[i].red   = (colors[i].r<<8)|colors[i].r;
+			xcmap[i].green = (colors[i].g<<8)|colors[i].g;
+			xcmap[i].blue  = (colors[i].b<<8)|colors[i].b;
+			xcmap[i].flags = (DoRed|DoGreen|DoBlue);
+		}
+		XStoreColors(GFX_Display, SDL_XColorMap, xcmap, ncolors);
+		XSync(GFX_Display, False);
+		SDL_stack_free(xcmap);
+	} else {
+	        /*
+		 * Shared colormap: We only allocate read-only cells, which
+		 * increases the likelyhood of colour sharing with other
+		 * clients. The pixel values will almost certainly be
+		 * different from the requested ones, so the user has to
+		 * walk the colormap and see which index got what colour.
+		 *
+		 * We can work directly with the logical palette since it
+		 * has already been set when we get here.
+		 */
+		SDL_Color *want, *reject;
+	        unsigned long *freelist;
+		int i;
+		int nfree = 0;
+		int nc = this->screen->format->palette->ncolors;
+	        colors = this->screen->format->palette->colors;
+		freelist = SDL_stack_alloc(unsigned long, nc);
+		/* make sure multiple allocations of the same cell are freed */
+	        for(i = 0; i < ncolors; i++) {
+		        int pixel = firstcolor + i;
+		        while(SDL_XPixels[pixel]) {
+			        freelist[nfree++] = pixel;
+				--SDL_XPixels[pixel];
+			}
+		}
+		XFreeColors(GFX_Display, SDL_XColorMap, freelist, nfree, 0);
+		SDL_stack_free(freelist);
+
+		want = SDL_stack_alloc(SDL_Color, ncolors);
+		reject = SDL_stack_alloc(SDL_Color, ncolors);
+		SDL_memcpy(want, colors + firstcolor, ncolors * sizeof(SDL_Color));
+		/* make sure the user isn't fooled by her own wishes
+		   (black is safe, always available in the default colormap) */
+		SDL_memset(colors + firstcolor, 0, ncolors * sizeof(SDL_Color));
+
+		/* now try to allocate the colours */
+		for(i = 0; i < ncolors; i++) {
+		        XColor col;
+			col.red = want[i].r << 8;
+			col.green = want[i].g << 8;
+			col.blue = want[i].b << 8;
+			col.flags = DoRed | DoGreen | DoBlue;
+			if(XAllocColor(GFX_Display, SDL_XColorMap, &col)) {
+			        /* We got the colour, or at least the nearest
+				   the hardware could get. */
+			        colors[col.pixel].r = col.red >> 8;
+				colors[col.pixel].g = col.green >> 8;
+				colors[col.pixel].b = col.blue >> 8;
+				++SDL_XPixels[col.pixel];
+			} else {
+				/*
+				 * no more free cells, add it to the list
+				 * of rejected colours
+				 */
+				reject[nrej++] = want[i];
+			}
+		}
+		if(nrej)
+			allocate_nearest(this, colors, reject, nrej);
+		SDL_stack_free(reject);
+		SDL_stack_free(want);
+	}
+	return nrej == 0;
+}
+
+int X11_SetGammaRamp(_THIS, Uint16 *ramp)
+{
+	int i, ncolors;
+	XColor xcmap[256];
+
+	/* See if actually setting the gamma is supported */
+	if ( SDL_Visual->class != DirectColor ) {
+	    SDL_SetError("Gamma correction not supported on this visual");
+	    return(-1);
+	}
+
+	/* Calculate the appropriate palette for the given gamma ramp */
+	ncolors = SDL_Visual->map_entries;
+	for ( i=0; i<ncolors; ++i ) {
+		Uint8 c = (256 * i / ncolors);
+		xcmap[i].pixel = SDL_MapRGB(this->screen->format, c, c, c);
+		xcmap[i].red   = ramp[0*256+c];
+		xcmap[i].green = ramp[1*256+c];
+		xcmap[i].blue  = ramp[2*256+c];
+		xcmap[i].flags = (DoRed|DoGreen|DoBlue);
+	}
+	XStoreColors(GFX_Display, SDL_XColorMap, xcmap, ncolors);
+	XSync(GFX_Display, False);
+	return(0);
+}
+
+/* Note:  If we are terminated, this could be called in the middle of
+   another SDL video routine -- notably UpdateRects.
+*/
+void X11_VideoQuit(_THIS)
+{
+	/* Shutdown everything that's still up */
+	/* The event thread should be done, so we can touch SDL_Display */
+	if ( SDL_Display != NULL ) {
+		/* Flush any delayed updates */
+		XSync(GFX_Display, False);
+
+		/* Close the connection with the IM server */
+		#ifdef X_HAVE_UTF8_STRING
+		if (SDL_IC != NULL) {
+			XUnsetICFocus(SDL_IC);
+			XDestroyIC(SDL_IC);
+			SDL_IC = NULL;
+		}
+		if (SDL_IM != NULL) {
+			XCloseIM(SDL_IM);
+			SDL_IM = NULL;
+		}
+		#endif
+
+		/* Start shutting down the windows */
+		X11_DestroyImage(this, this->screen);
+		X11_DestroyWindow(this, this->screen);
+		X11_FreeVideoModes(this);
+		if ( SDL_XColorMap != SDL_DisplayColormap ) {
+			XFreeColormap(SDL_Display, SDL_XColorMap);
+		}
+		if ( SDL_iconcolors ) {
+			unsigned long pixel;
+			Colormap dcmap = DefaultColormap(SDL_Display,
+							 SDL_Screen);
+			for(pixel = 0; pixel < 256; ++pixel) {
+				while(SDL_iconcolors[pixel] > 0) {
+					XFreeColors(GFX_Display,
+						    dcmap, &pixel, 1, 0);
+					--SDL_iconcolors[pixel];
+				}
+			}
+			SDL_free(SDL_iconcolors);
+			SDL_iconcolors = NULL;
+		} 
+
+		/* Restore gamma settings if they've changed */
+		if ( SDL_GetAppState() & SDL_APPACTIVE ) {
+			X11_SwapVidModeGamma(this);
+		}
+
+		/* Free that blank cursor */
+		if ( SDL_BlankCursor != NULL ) {
+			this->FreeWMCursor(this, SDL_BlankCursor);
+			SDL_BlankCursor = NULL;
+		}
+
+		/* Close the X11 graphics connection */
+		if ( GFX_Display != NULL ) {
+			XCloseDisplay(GFX_Display);
+			GFX_Display = NULL;
+		}
+
+		/* Close the X11 display connection */
+		XCloseDisplay(SDL_Display);
+		SDL_Display = NULL;
+
+		/* Reset the X11 error handlers */
+		if ( XIO_handler ) {
+			XSetIOErrorHandler(XIO_handler);
+		}
+		if ( X_handler ) {
+			XSetErrorHandler(X_handler);
+		}
+
+		/* Unload GL library after X11 shuts down */
+		X11_GL_UnloadLibrary(this);
+	}
+	if ( this->screen && (this->screen->flags & SDL_HWSURFACE) ) {
+		/* Direct screen access, no memory buffer */
+		this->screen->pixels = NULL;
+	}
+
+#if SDL_VIDEO_DRIVER_X11_XME
+    XiGMiscDestroy();
+#endif
+}
+
diff --git a/sources/packages/l/sdl/sdl/create-1.2.15-x11-events-patch/create.patch.sh b/sources/packages/l/sdl/sdl/create-1.2.15-x11-events-patch/create.patch.sh
new file mode 100755
index 000000000..8aaa98738
--- /dev/null
+++ b/sources/packages/l/sdl/sdl/create-1.2.15-x11-events-patch/create.patch.sh
@@ -0,0 +1,15 @@
+#!/bin/sh
+
+VERSION=1.2.15
+
+tar --files-from=file.list -xzvf ../SDL-$VERSION.tar.gz
+mv SDL-$VERSION SDL-$VERSION-orig
+
+cp -rf ./SDL-$VERSION-new ./SDL-$VERSION
+
+diff -b --unified -Nr  SDL-$VERSION-orig  SDL-$VERSION > SDL-$VERSION-x11-events.patch
+
+mv SDL-$VERSION-x11-events.patch ../patches
+
+rm -rf ./SDL-$VERSION
+rm -rf ./SDL-$VERSION-orig
diff --git a/sources/packages/l/sdl/sdl/create-1.2.15-x11-events-patch/file.list b/sources/packages/l/sdl/sdl/create-1.2.15-x11-events-patch/file.list
new file mode 100644
index 000000000..024825990
--- /dev/null
+++ b/sources/packages/l/sdl/sdl/create-1.2.15-x11-events-patch/file.list
@@ -0,0 +1,3 @@
+SDL-1.2.15/src/video/x11/SDL_x11events.c
+SDL-1.2.15/src/video/x11/SDL_x11events_c.h
+SDL-1.2.15/src/video/x11/SDL_x11video.c
diff --git a/sources/packages/l/sdl/sdl/create-1.2.15-x11-grab-patch/SDL-1.2.15-new/src/video/x11/SDL_x11wm.c b/sources/packages/l/sdl/sdl/create-1.2.15-x11-grab-patch/SDL-1.2.15-new/src/video/x11/SDL_x11wm.c
new file mode 100644
index 000000000..fe0f6a54a
--- /dev/null
+++ b/sources/packages/l/sdl/sdl/create-1.2.15-x11-grab-patch/SDL-1.2.15-new/src/video/x11/SDL_x11wm.c
@@ -0,0 +1,435 @@
+/*
+    SDL - Simple DirectMedia Layer
+    Copyright (C) 1997-2012 Sam Lantinga
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+    Sam Lantinga
+    slouken@libsdl.org
+*/
+#include "SDL_config.h"
+
+#include <X11/Xlib.h>
+#include <X11/Xutil.h>
+
+#include "SDL_version.h"
+#include "SDL_timer.h"
+#include "SDL_video.h"
+#include "SDL_syswm.h"
+#include "../SDL_pixels_c.h"
+#include "../../events/SDL_events_c.h"
+#include "SDL_x11modes_c.h"
+#include "SDL_x11wm_c.h"
+
+static Uint8 reverse_byte(Uint8 x)
+{
+	x = (x & 0xaa) >> 1 | (x & 0x55) << 1;
+	x = (x & 0xcc) >> 2 | (x & 0x33) << 2;
+	x = (x & 0xf0) >> 4 | (x & 0x0f) << 4;
+	return x;
+}
+
+void X11_SetIcon(_THIS, SDL_Surface *icon, Uint8 *mask)
+{
+	SDL_Surface *sicon;
+	XWMHints *wmhints;
+	XImage *icon_image;
+	Pixmap icon_pixmap;
+	Pixmap mask_pixmap;
+	Window icon_window = None;
+	GC gc;
+	XGCValues GCvalues;
+	int i, dbpp;
+	SDL_Rect bounds;
+	Uint8 *LSBmask;
+	Visual *dvis;
+	char *p;
+	int masksize;
+
+	SDL_Lock_EventThread();
+
+	/* The icon must use the default visual, depth and colormap of the
+	   screen, so it might need a conversion */
+	dvis = DefaultVisual(SDL_Display, SDL_Screen);
+	dbpp = DefaultDepth(SDL_Display, SDL_Screen);
+	for(i = 0; i < this->hidden->nvisuals; i++) {
+		if(this->hidden->visuals[i].visual == dvis) {
+			dbpp = this->hidden->visuals[i].bpp;
+			break;
+		}
+	}
+
+	/* The Visual struct is supposed to be opaque but we cheat a little */
+	sicon = SDL_CreateRGBSurface(SDL_SWSURFACE, icon->w, icon->h,
+				     dbpp,
+				     dvis->red_mask, dvis->green_mask,
+				     dvis->blue_mask, 0);
+	if ( sicon == NULL )
+		goto done;
+
+	if(dbpp == 8) {
+		/* Default visual is 8bit; we need to allocate colours from
+		   the default colormap */
+		SDL_Color want[256], got[256];
+		int nwant;
+		Colormap dcmap;
+		int missing;
+		dcmap = DefaultColormap(SDL_Display, SDL_Screen);
+		if(icon->format->palette) {
+			/* The icon has a palette as well - we just have to
+			   find those colours */
+			nwant = icon->format->palette->ncolors;
+			SDL_memcpy(want, icon->format->palette->colors,
+			       nwant * sizeof want[0]);
+		} else {
+			/* try the standard 6x6x6 cube for lack of better
+			   ideas */
+			int r, g, b, i;
+			for(r = i = 0; r < 256; r += 0x33)
+				for(g = 0; g < 256; g += 0x33)
+					for(b = 0; b < 256; b += 0x33, i++) {
+						want[i].r = r;
+						want[i].g = g;
+						want[i].b = b;
+					}
+			nwant = 216;
+		}
+		if(SDL_iconcolors) {
+			/* free already allocated colours first */
+			unsigned long freelist[512];
+			int nfree = 0;
+			for(i = 0; i < 256; i++) {
+				while(SDL_iconcolors[i]) {
+					freelist[nfree++] = i;
+					SDL_iconcolors[i]--;
+				}
+			}
+			XFreeColors(GFX_Display, dcmap, freelist, nfree, 0);
+		}
+		if(!SDL_iconcolors)
+			SDL_iconcolors = SDL_malloc(256 * sizeof *SDL_iconcolors);
+		SDL_memset(SDL_iconcolors, 0, 256 * sizeof *SDL_iconcolors);
+
+		/* try to allocate the colours */
+		SDL_memset(got, 0, sizeof got);
+		missing = 0;
+		for(i = 0; i < nwant; i++) {
+			XColor c;
+			c.red = want[i].r << 8;
+			c.green = want[i].g << 8;
+			c.blue = want[i].b << 8;
+			c.flags = DoRed | DoGreen | DoBlue;
+			if(XAllocColor(GFX_Display, dcmap, &c)) {
+				/* got the colour */
+				SDL_iconcolors[c.pixel]++;
+				got[c.pixel] = want[i];
+			} else {
+				missing = 1;
+			}
+		}
+		if(missing) {
+			/* Some colours were apparently missing, so we just
+			   allocate all the rest as well */
+			XColor cols[256];
+			for(i = 0; i < 256; i++)
+				cols[i].pixel = i;
+			XQueryColors(GFX_Display, dcmap, cols, 256);
+			for(i = 0; i < 256; i++) {
+				got[i].r = cols[i].red >> 8;
+				got[i].g = cols[i].green >> 8;
+				got[i].b = cols[i].blue >> 8;
+				if(!SDL_iconcolors[i]) {
+					if(XAllocColor(GFX_Display, dcmap,
+							cols + i)) {
+						SDL_iconcolors[i] = 1;
+					} else {
+						/* index not available */
+						got[i].r = 0;
+						got[i].g = 0;
+						got[i].b = 0;
+					}
+				}
+			}
+		}
+
+		SDL_SetColors(sicon, got, 0, 256);
+	}
+
+	bounds.x = 0;
+	bounds.y = 0;
+	bounds.w = icon->w;
+	bounds.h = icon->h;
+	if ( SDL_LowerBlit(icon, &bounds, sicon, &bounds) < 0 )
+		goto done;
+
+	/* We need the mask as given, except in LSBfirst format instead of
+	   MSBfirst. Reverse the bits in each byte. */
+	masksize = ((sicon->w + 7) >> 3) * sicon->h;
+	LSBmask = SDL_malloc(masksize);
+	if ( LSBmask == NULL ) {
+		goto done;
+	}
+	SDL_memset(LSBmask, 0, masksize);
+	for(i = 0; i < masksize; i++)
+		LSBmask[i] = reverse_byte(mask[i]);
+	mask_pixmap = XCreatePixmapFromBitmapData(SDL_Display, WMwindow,
+						  (char *)LSBmask,
+						  sicon->w, sicon->h,
+						  1L, 0L, 1);
+
+	/* Transfer the image to an X11 pixmap */
+	icon_image = XCreateImage(SDL_Display,
+				  DefaultVisual(SDL_Display, SDL_Screen),
+				  DefaultDepth(SDL_Display, SDL_Screen),
+				  ZPixmap, 0, sicon->pixels,
+				  sicon->w, sicon->h,
+				  32, 0);
+	icon_image->byte_order = (SDL_BYTEORDER == SDL_BIG_ENDIAN)
+		                 ? MSBFirst : LSBFirst;
+	icon_pixmap = XCreatePixmap(SDL_Display, SDL_Root, sicon->w, sicon->h,
+				    DefaultDepth(SDL_Display, SDL_Screen));
+	gc = XCreateGC(SDL_Display, icon_pixmap, 0, &GCvalues);
+	XPutImage(SDL_Display, icon_pixmap, gc, icon_image,
+		  0, 0, 0, 0, sicon->w, sicon->h);
+	XFreeGC(SDL_Display, gc);
+	XDestroyImage(icon_image);
+	SDL_free(LSBmask);
+	sicon->pixels = NULL;
+
+	/* Some buggy window managers (some versions of Enlightenment, it
+	   seems) need an icon window *and* icon pixmap to work properly, while
+	   it screws up others. The default is only to use a pixmap. */
+	p = SDL_getenv("SDL_VIDEO_X11_ICONWIN");
+	if(p && *p) {
+		icon_window = XCreateSimpleWindow(SDL_Display, SDL_Root,
+						  0, 0, sicon->w, sicon->h, 0,
+						  CopyFromParent,
+						  CopyFromParent);
+		XSetWindowBackgroundPixmap(SDL_Display, icon_window,
+					   icon_pixmap);
+		XClearWindow(SDL_Display, icon_window);
+	}
+
+	/* Set the window icon to the icon pixmap (and icon window) */
+	wmhints = XAllocWMHints();
+	wmhints->flags = (IconPixmapHint | IconMaskHint | InputHint);
+	wmhints->icon_pixmap = icon_pixmap;
+	wmhints->icon_mask = mask_pixmap;
+	wmhints->input = True;
+	if(icon_window != None) {
+		wmhints->flags |= IconWindowHint;
+		wmhints->icon_window = icon_window;
+	}
+	XSetWMHints(SDL_Display, WMwindow, wmhints);
+	XFree(wmhints);
+	XSync(SDL_Display, False);
+
+  done:
+	SDL_Unlock_EventThread();
+	SDL_FreeSurface(sicon);
+}
+
+void X11_SetCaptionNoLock(_THIS, const char *title, const char *icon)
+{
+	XTextProperty titleprop, iconprop;
+	Status status;
+
+#ifdef X_HAVE_UTF8_STRING
+	Atom _NET_WM_NAME = 0;
+	Atom _NET_WM_ICON_NAME = 0;
+
+	/* Look up some useful Atoms */
+	if (SDL_X11_HAVE_UTF8) {
+		_NET_WM_NAME = XInternAtom(SDL_Display, "_NET_WM_NAME", False);
+		_NET_WM_ICON_NAME = XInternAtom(SDL_Display, "_NET_WM_ICON_NAME", False);
+	}
+#endif
+
+	if ( title != NULL ) {
+		char *title_locale = SDL_iconv_utf8_locale(title);
+		if ( !title_locale ) {
+			SDL_OutOfMemory();
+			return;
+		}
+		status = XStringListToTextProperty(&title_locale, 1, &titleprop);
+		SDL_free(title_locale);
+		if ( status ) {
+			XSetTextProperty(SDL_Display, WMwindow, &titleprop, XA_WM_NAME);
+			XFree(titleprop.value);
+		}
+#ifdef X_HAVE_UTF8_STRING
+		if (SDL_X11_HAVE_UTF8) {
+			status = Xutf8TextListToTextProperty(SDL_Display,
+					(char **)&title, 1, XUTF8StringStyle, &titleprop);
+			if ( status == Success ) {
+				XSetTextProperty(SDL_Display, WMwindow, &titleprop, _NET_WM_NAME);
+				XFree(titleprop.value);
+			}
+		}
+#endif
+	}
+	if ( icon != NULL ) {
+		char *icon_locale = SDL_iconv_utf8_locale(icon);
+		if ( !icon_locale ) {
+			SDL_OutOfMemory();
+			return;
+		}
+		status = XStringListToTextProperty(&icon_locale, 1, &iconprop);
+		SDL_free(icon_locale);
+		if ( status ) {
+			XSetTextProperty(SDL_Display, WMwindow, &iconprop, XA_WM_ICON_NAME);
+			XFree(iconprop.value);
+		}
+#ifdef X_HAVE_UTF8_STRING
+		if (SDL_X11_HAVE_UTF8) {
+			status = Xutf8TextListToTextProperty(SDL_Display,
+					(char **)&icon, 1, XUTF8StringStyle, &iconprop);
+			if ( status == Success ) {
+				XSetTextProperty(SDL_Display, WMwindow, &iconprop, _NET_WM_ICON_NAME);
+				XFree(iconprop.value);
+			}
+		}
+#endif
+	}
+	XSync(SDL_Display, False);
+}
+
+void X11_SetCaption(_THIS, const char *title, const char *icon)
+{
+	SDL_Lock_EventThread();
+	X11_SetCaptionNoLock(this, title, icon);
+	SDL_Unlock_EventThread();
+}
+
+/* Iconify the window */
+int X11_IconifyWindow(_THIS)
+{
+	int result;
+
+	SDL_Lock_EventThread();
+	result = XIconifyWindow(SDL_Display, WMwindow, SDL_Screen);
+	XSync(SDL_Display, False);
+	SDL_Unlock_EventThread();
+	return(result);
+}
+
+SDL_GrabMode X11_GrabInputNoLock(_THIS, SDL_GrabMode mode)
+{
+	int result;
+
+	if ( this->screen == NULL || SDL_Display == NULL ) {
+		return(SDL_GRAB_OFF);
+	}
+	if ( ! SDL_Window ) {
+		return(mode);	/* Will be set later on mode switch */
+	}
+	if ( mode == SDL_GRAB_OFF ) {
+		XUngrabPointer(SDL_Display, CurrentTime);
+		XUngrabKeyboard(SDL_Display, CurrentTime);
+	} else {
+		if ( this->screen->flags & SDL_FULLSCREEN ) {
+			/* Unbind the mouse from the fullscreen window */
+			XUngrabPointer(SDL_Display, CurrentTime);
+		}
+		/* Try to grab the mouse */
+#if 0 /* We'll wait here until we actually grab, otherwise behavior undefined */
+		for ( numtries = 0; numtries < 10; ++numtries ) {
+#else
+		for ( ; ; ) {
+#endif
+			result = XGrabPointer(SDL_Display, SDL_Window, True, 0,
+						GrabModeAsync, GrabModeAsync,
+						SDL_Window, None, CurrentTime);
+			if ( result == GrabSuccess || result == GrabNotViewable ) {
+				break;
+			}
+			SDL_Delay(100);
+		}
+		if ( result != GrabSuccess ) {
+			/* Uh, oh, what do we do here? */ ;
+			return(SDL_GRAB_OFF);
+		}
+		/* Now grab the keyboard */
+		XGrabKeyboard(SDL_Display, WMwindow, True,
+				GrabModeAsync, GrabModeAsync, CurrentTime);
+
+		/* Raise the window if we grab the mouse */
+		if ( !(this->screen->flags & SDL_FULLSCREEN) )
+			XRaiseWindow(SDL_Display, WMwindow);
+
+		/* Make sure we register input focus */
+		SDL_PrivateAppActive(1, SDL_APPINPUTFOCUS);
+		/* Since we grabbed the pointer, we have mouse focus, too. */
+		SDL_PrivateAppActive(1, SDL_APPMOUSEFOCUS);
+	}
+	XSync(SDL_Display, False);
+
+	return(mode);
+}
+
+SDL_GrabMode X11_GrabInput(_THIS, SDL_GrabMode mode)
+{
+	SDL_Lock_EventThread();
+	mode = X11_GrabInputNoLock(this, mode);
+	SDL_Unlock_EventThread();
+
+	return(mode);
+}
+
+/* If 'info' is the right version, this function fills it and returns 1.
+   Otherwise, in case of a version mismatch, it returns -1.
+*/
+static void lock_display(void)
+{
+	SDL_Lock_EventThread();
+}
+static void unlock_display(void)
+{
+	/* Make sure any X11 transactions are completed */
+	SDL_VideoDevice *this = current_video;
+	XSync(SDL_Display, False);
+	SDL_Unlock_EventThread();
+}
+
+#include <stdio.h>
+int X11_GetWMInfo(_THIS, SDL_SysWMinfo *info)
+{
+	if ( info->version.major <= SDL_MAJOR_VERSION ) {
+		info->subsystem = SDL_SYSWM_X11;
+		info->info.x11.display = SDL_Display;
+		info->info.x11.window = SDL_Window;
+		if ( SDL_VERSIONNUM(info->version.major,
+		                    info->version.minor,
+		                    info->version.patch) >= 1002 ) {
+			info->info.x11.fswindow = FSwindow;
+			info->info.x11.wmwindow = WMwindow;
+		}
+
+
+		if ( SDL_VERSIONNUM(info->version.major,
+		                    info->version.minor,
+		                    info->version.patch) >= 1212 ) {
+			info->info.x11.gfxdisplay = GFX_Display;
+		}
+
+		info->info.x11.lock_func = lock_display;
+		info->info.x11.unlock_func = unlock_display;
+		return(1);
+	} else {
+		SDL_SetError("Application not compiled with SDL %d.%d\n",
+					SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
+		return(-1);
+	}
+}
diff --git a/sources/packages/l/sdl/sdl/create-1.2.15-x11-grab-patch/create.patch.sh b/sources/packages/l/sdl/sdl/create-1.2.15-x11-grab-patch/create.patch.sh
new file mode 100755
index 000000000..8fff2f419
--- /dev/null
+++ b/sources/packages/l/sdl/sdl/create-1.2.15-x11-grab-patch/create.patch.sh
@@ -0,0 +1,15 @@
+#!/bin/sh
+
+VERSION=1.2.15
+
+tar --files-from=file.list -xzvf ../SDL-$VERSION.tar.gz
+mv SDL-$VERSION SDL-$VERSION-orig
+
+cp -rf ./SDL-$VERSION-new ./SDL-$VERSION
+
+diff -b --unified -Nr  SDL-$VERSION-orig  SDL-$VERSION > SDL-$VERSION-x11-grab.patch
+
+mv SDL-$VERSION-x11-grab.patch ../patches
+
+rm -rf ./SDL-$VERSION
+rm -rf ./SDL-$VERSION-orig
diff --git a/sources/packages/l/sdl/sdl/create-1.2.15-x11-grab-patch/file.list b/sources/packages/l/sdl/sdl/create-1.2.15-x11-grab-patch/file.list
new file mode 100644
index 000000000..d1a7cbabf
--- /dev/null
+++ b/sources/packages/l/sdl/sdl/create-1.2.15-x11-grab-patch/file.list
@@ -0,0 +1 @@
+SDL-1.2.15/src/video/x11/SDL_x11wm.c