Fixed line endings on WinRT source code
authorSam Lantinga <slouken@libsdl.org>
Sun, 09 Mar 2014 11:06:11 -0700
changeset 8582 c3e9a2b93517
parent 8581 c001dc3e258b
child 8583 fb2933ca805f
Fixed line endings on WinRT source code
include/SDL_config_winrt.h
include/SDL_egl.h
include/SDL_main.h
include/SDL_platform.h
include/SDL_system.h
include/begin_code.h
src/SDL_log.c
src/atomic/SDL_spinlock.c
src/audio/xaudio2/SDL_xaudio2.c
src/audio/xaudio2/SDL_xaudio2_winrthelpers.cpp
src/audio/xaudio2/SDL_xaudio2_winrthelpers.h
src/core/winrt/SDL_winrtapp_common.cpp
src/core/winrt/SDL_winrtapp_common.h
src/core/winrt/SDL_winrtapp_direct3d.cpp
src/core/winrt/SDL_winrtapp_direct3d.h
src/file/SDL_rwops.c
src/filesystem/winrt/SDL_sysfilesystem.cpp
src/joystick/SDL_gamecontroller.c
src/main/winrt/SDL_winrt_main_NonXAML.cpp
src/render/direct3d11/SDL_render_d3d11.cpp
src/thread/stdcpp/SDL_systhread.cpp
src/timer/windows/SDL_systimer.c
src/video/SDL_sysvideo.h
src/video/SDL_video.c
src/video/winrt/SDL_winrtevents.cpp
src/video/winrt/SDL_winrtevents_c.h
src/video/winrt/SDL_winrtkeyboard.cpp
src/video/winrt/SDL_winrtmouse.cpp
src/video/winrt/SDL_winrtopengles.cpp
src/video/winrt/SDL_winrtopengles.h
src/video/winrt/SDL_winrtpointerinput.cpp
src/video/winrt/SDL_winrtvideo.cpp
src/video/winrt/SDL_winrtvideo_cpp.h
test/loopwave.c
test/testthread.c
--- a/include/SDL_config_winrt.h	Tue Mar 04 19:49:11 2014 -0500
+++ b/include/SDL_config_winrt.h	Sun Mar 09 11:06:11 2014 -0700
@@ -166,9 +166,9 @@
 #define SDL_VIDEO_DRIVER_WINRT	1
 #define SDL_VIDEO_DRIVER_DUMMY  1
 
-/* Enable OpenGL ES 2.0 (via a modified ANGLE library) */
-#if WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP    /* TODO, WinRT: try adding OpenGL ES 2 support for Windows Phone 8 */
-#define SDL_VIDEO_OPENGL_ES2 1
+/* Enable OpenGL ES 2.0 (via a modified ANGLE library) */
+#if WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP    /* TODO, WinRT: try adding OpenGL ES 2 support for Windows Phone 8 */
+#define SDL_VIDEO_OPENGL_ES2 1
 #define SDL_VIDEO_OPENGL_EGL 1
 #endif
 
--- a/include/SDL_egl.h	Tue Mar 04 19:49:11 2014 -0500
+++ b/include/SDL_egl.h	Sun Mar 09 11:06:11 2014 -0700
@@ -393,8 +393,8 @@
 
 #if __WINRT__
 #include <Unknwn.h>
-typedef IUnknown * EGLNativeWindowType;
-typedef int EGLNativeDisplayType;
+typedef IUnknown * EGLNativeWindowType;
+typedef int EGLNativeDisplayType;
 typedef HBITMAP EGLNativePixmapType;
 #else
 typedef HDC     EGLNativeDisplayType;
--- a/include/SDL_main.h	Tue Mar 04 19:49:11 2014 -0500
+++ b/include/SDL_main.h	Sun Mar 09 11:06:11 2014 -0700
@@ -140,7 +140,7 @@
  *  \ret 0 on success, -1 on failure.  On failure, use SDL_GetError to retrieve more
  *      information on the failure.
  */
-extern DECLSPEC int SDLCALL SDL_WinRTRunApp(int (*mainFunction)(int, char **), void * xamlBackgroundPanel);
+extern DECLSPEC int SDLCALL SDL_WinRTRunApp(int (*mainFunction)(int, char **), void * xamlBackgroundPanel);
 
 #endif /* __WINRT__ */
 
--- a/include/SDL_platform.h	Tue Mar 04 19:49:11 2014 -0500
+++ b/include/SDL_platform.h	Sun Mar 09 11:06:11 2014 -0700
@@ -1,168 +1,168 @@
-/*
-  Simple DirectMedia Layer
-  Copyright (C) 1997-2013 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.
-*/
-
-/**
- *  \file SDL_platform.h
- *
- *  Try to get a standard set of platform defines.
- */
-
-#ifndef _SDL_platform_h
-#define _SDL_platform_h
-
-#if defined(_AIX)
-#undef __AIX__
-#define __AIX__     1
-#endif
-#if defined(__HAIKU__)
-#undef __HAIKU__
-#define __HAIKU__   1
-#endif
-#if defined(bsdi) || defined(__bsdi) || defined(__bsdi__)
-#undef __BSDI__
-#define __BSDI__    1
-#endif
-#if defined(_arch_dreamcast)
-#undef __DREAMCAST__
-#define __DREAMCAST__   1
-#endif
-#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
-#undef __FREEBSD__
-#define __FREEBSD__ 1
-#endif
-#if defined(hpux) || defined(__hpux) || defined(__hpux__)
-#undef __HPUX__
-#define __HPUX__    1
-#endif
-#if defined(sgi) || defined(__sgi) || defined(__sgi__) || defined(_SGI_SOURCE)
-#undef __IRIX__
-#define __IRIX__    1
-#endif
-#if defined(linux) || defined(__linux) || defined(__linux__)
-#undef __LINUX__
-#define __LINUX__   1
-#endif
-#if defined(ANDROID)
-#undef __ANDROID__
-#undef __LINUX__ /* do we need to do this? */
-#define __ANDROID__ 1
-#endif
-
-#if defined(__APPLE__)
-/* lets us know what version of Mac OS X we're compiling on */
-#include "AvailabilityMacros.h"
-#include "TargetConditionals.h"
-#if TARGET_OS_IPHONE
-/* if compiling for iPhone */
-#undef __IPHONEOS__
-#define __IPHONEOS__ 1
-#undef __MACOSX__
-#else
-/* if not compiling for iPhone */
-#undef __MACOSX__
-#define __MACOSX__  1
-#if MAC_OS_X_VERSION_MIN_REQUIRED < 1050
-# error SDL for Mac OS X only supports deploying on 10.5 and above.
-#endif /* MAC_OS_X_VERSION_MIN_REQUIRED < 1050 */
-#if MAC_OS_X_VERSION_MAX_ALLOWED < 1060
-# error SDL for Mac OS X must be built with a 10.6 SDK or above.
-#endif /* MAC_OS_X_VERSION_MAX_ALLOWED < 1060 */
-#endif /* TARGET_OS_IPHONE */
-#endif /* defined(__APPLE__) */
-
-#if defined(__NetBSD__)
-#undef __NETBSD__
-#define __NETBSD__  1
-#endif
-#if defined(__OpenBSD__)
-#undef __OPENBSD__
-#define __OPENBSD__ 1
-#endif
-#if defined(__OS2__)
-#undef __OS2__
-#define __OS2__     1
-#endif
-#if defined(osf) || defined(__osf) || defined(__osf__) || defined(_OSF_SOURCE)
-#undef __OSF__
-#define __OSF__     1
-#endif
-#if defined(__QNXNTO__)
-#undef __QNXNTO__
-#define __QNXNTO__  1
-#endif
-#if defined(riscos) || defined(__riscos) || defined(__riscos__)
-#undef __RISCOS__
-#define __RISCOS__  1
-#endif
-#if defined(__SVR4)
-#undef __SOLARIS__
-#define __SOLARIS__ 1
-#endif
-
-#if defined(WIN32) || defined(_WIN32) || defined(__CYGWIN__)
-/* Try to find out if we're compiling for WinRT or non-WinRT */
-#if defined(_MSC_VER) && (_MSC_VER >= 1700)	/* _MSC_VER==1700 for MSVC 2012 */
-#include <winapifamily.h>
-#endif /* _MSC_VER >= 1700 */
-/* Default to classic, Win32/Win64/Desktop compilation either if:
-     1. the version of Windows is explicity set to a 'Desktop' (non-Metro) app
-     2. the version of Windows cannot be determined via winapifamily.h
-   If neither is true, then see if we're compiling for WinRT.
- */
-#if ! defined(WINAPI_FAMILY_PARTITION) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
-#undef __WINDOWS__
-#define __WINDOWS__   1
-/* See if we're compiling for WinRT: */
-#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
-#undef __WINRT__
-#define __WINRT__ 1
-#endif /* ! defined(WINAPI_FAMILY_PARTITION) */
-#endif /* defined(WIN32) || defined(_WIN32) || defined(__CYGWIN__) */
-
-#if defined(__WINDOWS__)
-#undef __WIN32__
-#define __WIN32__ 1
-#endif
-#if defined(__PSP__)
-#undef __PSP__
-#define __PSP__ 1
-#endif
-
-#include "begin_code.h"
-/* Set up for C function definitions, even when using C++ */
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- *  \brief Gets the name of the platform.
- */
-extern DECLSPEC const char * SDLCALL SDL_GetPlatform (void);
-
-/* Ends C function definitions when using C++ */
-#ifdef __cplusplus
-}
-#endif
-#include "close_code.h"
-
-#endif /* _SDL_platform_h */
-
-/* vi: set ts=4 sw=4 expandtab: */
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2013 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.
+*/
+
+/**
+ *  \file SDL_platform.h
+ *
+ *  Try to get a standard set of platform defines.
+ */
+
+#ifndef _SDL_platform_h
+#define _SDL_platform_h
+
+#if defined(_AIX)
+#undef __AIX__
+#define __AIX__     1
+#endif
+#if defined(__HAIKU__)
+#undef __HAIKU__
+#define __HAIKU__   1
+#endif
+#if defined(bsdi) || defined(__bsdi) || defined(__bsdi__)
+#undef __BSDI__
+#define __BSDI__    1
+#endif
+#if defined(_arch_dreamcast)
+#undef __DREAMCAST__
+#define __DREAMCAST__   1
+#endif
+#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
+#undef __FREEBSD__
+#define __FREEBSD__ 1
+#endif
+#if defined(hpux) || defined(__hpux) || defined(__hpux__)
+#undef __HPUX__
+#define __HPUX__    1
+#endif
+#if defined(sgi) || defined(__sgi) || defined(__sgi__) || defined(_SGI_SOURCE)
+#undef __IRIX__
+#define __IRIX__    1
+#endif
+#if defined(linux) || defined(__linux) || defined(__linux__)
+#undef __LINUX__
+#define __LINUX__   1
+#endif
+#if defined(ANDROID)
+#undef __ANDROID__
+#undef __LINUX__ /* do we need to do this? */
+#define __ANDROID__ 1
+#endif
+
+#if defined(__APPLE__)
+/* lets us know what version of Mac OS X we're compiling on */
+#include "AvailabilityMacros.h"
+#include "TargetConditionals.h"
+#if TARGET_OS_IPHONE
+/* if compiling for iPhone */
+#undef __IPHONEOS__
+#define __IPHONEOS__ 1
+#undef __MACOSX__
+#else
+/* if not compiling for iPhone */
+#undef __MACOSX__
+#define __MACOSX__  1
+#if MAC_OS_X_VERSION_MIN_REQUIRED < 1050
+# error SDL for Mac OS X only supports deploying on 10.5 and above.
+#endif /* MAC_OS_X_VERSION_MIN_REQUIRED < 1050 */
+#if MAC_OS_X_VERSION_MAX_ALLOWED < 1060
+# error SDL for Mac OS X must be built with a 10.6 SDK or above.
+#endif /* MAC_OS_X_VERSION_MAX_ALLOWED < 1060 */
+#endif /* TARGET_OS_IPHONE */
+#endif /* defined(__APPLE__) */
+
+#if defined(__NetBSD__)
+#undef __NETBSD__
+#define __NETBSD__  1
+#endif
+#if defined(__OpenBSD__)
+#undef __OPENBSD__
+#define __OPENBSD__ 1
+#endif
+#if defined(__OS2__)
+#undef __OS2__
+#define __OS2__     1
+#endif
+#if defined(osf) || defined(__osf) || defined(__osf__) || defined(_OSF_SOURCE)
+#undef __OSF__
+#define __OSF__     1
+#endif
+#if defined(__QNXNTO__)
+#undef __QNXNTO__
+#define __QNXNTO__  1
+#endif
+#if defined(riscos) || defined(__riscos) || defined(__riscos__)
+#undef __RISCOS__
+#define __RISCOS__  1
+#endif
+#if defined(__SVR4)
+#undef __SOLARIS__
+#define __SOLARIS__ 1
+#endif
+
+#if defined(WIN32) || defined(_WIN32) || defined(__CYGWIN__)
+/* Try to find out if we're compiling for WinRT or non-WinRT */
+#if defined(_MSC_VER) && (_MSC_VER >= 1700)	/* _MSC_VER==1700 for MSVC 2012 */
+#include <winapifamily.h>
+#endif /* _MSC_VER >= 1700 */
+/* Default to classic, Win32/Win64/Desktop compilation either if:
+     1. the version of Windows is explicity set to a 'Desktop' (non-Metro) app
+     2. the version of Windows cannot be determined via winapifamily.h
+   If neither is true, then see if we're compiling for WinRT.
+ */
+#if ! defined(WINAPI_FAMILY_PARTITION) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
+#undef __WINDOWS__
+#define __WINDOWS__   1
+/* See if we're compiling for WinRT: */
+#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
+#undef __WINRT__
+#define __WINRT__ 1
+#endif /* ! defined(WINAPI_FAMILY_PARTITION) */
+#endif /* defined(WIN32) || defined(_WIN32) || defined(__CYGWIN__) */
+
+#if defined(__WINDOWS__)
+#undef __WIN32__
+#define __WIN32__ 1
+#endif
+#if defined(__PSP__)
+#undef __PSP__
+#define __PSP__ 1
+#endif
+
+#include "begin_code.h"
+/* Set up for C function definitions, even when using C++ */
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ *  \brief Gets the name of the platform.
+ */
+extern DECLSPEC const char * SDLCALL SDL_GetPlatform (void);
+
+/* Ends C function definitions when using C++ */
+#ifdef __cplusplus
+}
+#endif
+#include "close_code.h"
+
+#endif /* _SDL_platform_h */
+
+/* vi: set ts=4 sw=4 expandtab: */
--- a/include/SDL_system.h	Tue Mar 04 19:49:11 2014 -0500
+++ b/include/SDL_system.h	Sun Mar 09 11:06:11 2014 -0700
@@ -1,185 +1,185 @@
-/*
-  Simple DirectMedia Layer
-  Copyright (C) 1997-2013 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.
-*/
-
-/**
- *  \file SDL_system.h
- *
- *  Include file for platform specific SDL API functions
- */
-
-#ifndef _SDL_system_h
-#define _SDL_system_h
-
-#include "SDL_stdinc.h"
-#include "SDL_keyboard.h"
-#include "SDL_render.h"
-#include "SDL_video.h"
-
-#include "begin_code.h"
-/* Set up for C function definitions, even when using C++ */
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-/* Platform specific functions for Windows */
-#ifdef __WIN32__
-
-/* Returns the D3D9 adapter index that matches the specified display index.
-   This adapter index can be passed to IDirect3D9::CreateDevice and controls
-   on which monitor a full screen application will appear.
-*/
-extern DECLSPEC int SDLCALL SDL_Direct3D9GetAdapterIndex( int displayIndex );
-
-/* Returns the D3D device associated with a renderer, or NULL if it's not a D3D renderer.
-   Once you are done using the device, you should release it to avoid a resource leak.
- */
-typedef struct IDirect3DDevice9 IDirect3DDevice9;
-extern DECLSPEC IDirect3DDevice9* SDLCALL SDL_RenderGetD3D9Device(SDL_Renderer * renderer);
-
-#endif /* __WIN32__ */
-
-
-/* Platform specific functions for iOS */
-#if defined(__IPHONEOS__) && __IPHONEOS__
-
-extern DECLSPEC int SDLCALL SDL_iPhoneSetAnimationCallback(SDL_Window * window, int interval, void (*callback)(void*), void *callbackParam);
-extern DECLSPEC void SDLCALL SDL_iPhoneSetEventPump(SDL_bool enabled);
-
-#endif /* __IPHONEOS__ */
-
-
-/* Platform specific functions for Android */
-#if defined(__ANDROID__) && __ANDROID__
-
-/* Get the JNI environment for the current thread
-   This returns JNIEnv*, but the prototype is void* so we don't need jni.h
- */
-extern DECLSPEC void * SDLCALL SDL_AndroidGetJNIEnv();
-
-/* Get the SDL Activity object for the application
-   This returns jobject, but the prototype is void* so we don't need jni.h
-   The jobject returned by SDL_AndroidGetActivity is a local reference.
-   It is the caller's responsibility to properly release it
-   (using env->Push/PopLocalFrame or manually with env->DeleteLocalRef)
- */
-extern DECLSPEC void * SDLCALL SDL_AndroidGetActivity();
-
-/* See the official Android developer guide for more information:
-   http://developer.android.com/guide/topics/data/data-storage.html
-*/
-#define SDL_ANDROID_EXTERNAL_STORAGE_READ   0x01
-#define SDL_ANDROID_EXTERNAL_STORAGE_WRITE  0x02
-
-/* Get the path used for internal storage for this application.
-   This path is unique to your application and cannot be written to
-   by other applications.
- */
-extern DECLSPEC const char * SDLCALL SDL_AndroidGetInternalStoragePath();
-
-/* Get the current state of external storage, a bitmask of these values:
-    SDL_ANDROID_EXTERNAL_STORAGE_READ
-    SDL_ANDROID_EXTERNAL_STORAGE_WRITE
-   If external storage is currently unavailable, this will return 0.
-*/
-extern DECLSPEC int SDLCALL SDL_AndroidGetExternalStorageState();
-
-/* Get the path used for external storage for this application.
-   This path is unique to your application, but is public and can be
-   written to by other applications.
- */
-extern DECLSPEC const char * SDLCALL SDL_AndroidGetExternalStoragePath();
-
-#endif /* __ANDROID__ */
-
-/* Platform specific functions for WinRT */
-#if defined(__WINRT__) && __WINRT__
-
-/**
- *  \brief WinRT / Windows Phone path types
- */
-typedef enum
-{
-    /** \brief The installed app's root directory.
-        Files here are likely to be read-only. */
-    SDL_WINRT_PATH_INSTALLED_LOCATION,
-
-    /** \brief The app's local data store.  Files may be written here */
-    SDL_WINRT_PATH_LOCAL_FOLDER,
-
-    /** \brief The app's roaming data store.  Unsupported on Windows Phone.
-        Files written here may be copied to other machines via a network
-        connection.
-    */
-    SDL_WINRT_PATH_ROAMING_FOLDER,
-
-    /** \brief The app's temporary data store.  Unsupported on Windows Phone.
-        Files written here may be deleted at any time. */
-    SDL_WINRT_PATH_TEMP_FOLDER
-} SDL_WinRT_Path;
-
-
-/**
- *  \brief Retrieves a WinRT defined path on the local file system
- *
- *  \note Documentation on most app-specific path types on WinRT
- *      can be found on MSDN, at the URL:
- *      http://msdn.microsoft.com/en-us/library/windows/apps/hh464917.aspx
- *
- *  \param pathType The type of path to retrieve.
- *  \ret A UCS-2 string (16-bit, wide-char) containing the path, or NULL
- *      if the path is not available for any reason.  Not all paths are
- *      available on all versions of Windows.  This is especially true on
- *      Windows Phone.  Check the documentation for the given
- *      SDL_WinRT_Path for more information on which path types are
- *      supported where.
- */
-extern DECLSPEC const wchar_t * SDLCALL SDL_WinRTGetFSPathUNICODE(SDL_WinRT_Path pathType);
-
-/**
- *  \brief Retrieves a WinRT defined path on the local file system
- *
- *  \note Documentation on most app-specific path types on WinRT
- *      can be found on MSDN, at the URL:
- *      http://msdn.microsoft.com/en-us/library/windows/apps/hh464917.aspx
- *
- *  \param pathType The type of path to retrieve.
- *  \ret A UTF-8 string (8-bit, multi-byte) containing the path, or NULL
- *      if the path is not available for any reason.  Not all paths are
- *      available on all versions of Windows.  This is especially true on
- *      Windows Phone.  Check the documentation for the given
- *      SDL_WinRT_Path for more information on which path types are
- *      supported where.
- */
-extern DECLSPEC const char * SDLCALL SDL_WinRTGetFSPathUTF8(SDL_WinRT_Path pathType);
-
-#endif /* __WINRT__ */
-
-
-/* Ends C function definitions when using C++ */
-#ifdef __cplusplus
-}
-#endif
-#include "close_code.h"
-
-#endif /* _SDL_system_h */
-
-/* vi: set ts=4 sw=4 expandtab: */
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2013 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.
+*/
+
+/**
+ *  \file SDL_system.h
+ *
+ *  Include file for platform specific SDL API functions
+ */
+
+#ifndef _SDL_system_h
+#define _SDL_system_h
+
+#include "SDL_stdinc.h"
+#include "SDL_keyboard.h"
+#include "SDL_render.h"
+#include "SDL_video.h"
+
+#include "begin_code.h"
+/* Set up for C function definitions, even when using C++ */
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/* Platform specific functions for Windows */
+#ifdef __WIN32__
+
+/* Returns the D3D9 adapter index that matches the specified display index.
+   This adapter index can be passed to IDirect3D9::CreateDevice and controls
+   on which monitor a full screen application will appear.
+*/
+extern DECLSPEC int SDLCALL SDL_Direct3D9GetAdapterIndex( int displayIndex );
+
+/* Returns the D3D device associated with a renderer, or NULL if it's not a D3D renderer.
+   Once you are done using the device, you should release it to avoid a resource leak.
+ */
+typedef struct IDirect3DDevice9 IDirect3DDevice9;
+extern DECLSPEC IDirect3DDevice9* SDLCALL SDL_RenderGetD3D9Device(SDL_Renderer * renderer);
+
+#endif /* __WIN32__ */
+
+
+/* Platform specific functions for iOS */
+#if defined(__IPHONEOS__) && __IPHONEOS__
+
+extern DECLSPEC int SDLCALL SDL_iPhoneSetAnimationCallback(SDL_Window * window, int interval, void (*callback)(void*), void *callbackParam);
+extern DECLSPEC void SDLCALL SDL_iPhoneSetEventPump(SDL_bool enabled);
+
+#endif /* __IPHONEOS__ */
+
+
+/* Platform specific functions for Android */
+#if defined(__ANDROID__) && __ANDROID__
+
+/* Get the JNI environment for the current thread
+   This returns JNIEnv*, but the prototype is void* so we don't need jni.h
+ */
+extern DECLSPEC void * SDLCALL SDL_AndroidGetJNIEnv();
+
+/* Get the SDL Activity object for the application
+   This returns jobject, but the prototype is void* so we don't need jni.h
+   The jobject returned by SDL_AndroidGetActivity is a local reference.
+   It is the caller's responsibility to properly release it
+   (using env->Push/PopLocalFrame or manually with env->DeleteLocalRef)
+ */
+extern DECLSPEC void * SDLCALL SDL_AndroidGetActivity();
+
+/* See the official Android developer guide for more information:
+   http://developer.android.com/guide/topics/data/data-storage.html
+*/
+#define SDL_ANDROID_EXTERNAL_STORAGE_READ   0x01
+#define SDL_ANDROID_EXTERNAL_STORAGE_WRITE  0x02
+
+/* Get the path used for internal storage for this application.
+   This path is unique to your application and cannot be written to
+   by other applications.
+ */
+extern DECLSPEC const char * SDLCALL SDL_AndroidGetInternalStoragePath();
+
+/* Get the current state of external storage, a bitmask of these values:
+    SDL_ANDROID_EXTERNAL_STORAGE_READ
+    SDL_ANDROID_EXTERNAL_STORAGE_WRITE
+   If external storage is currently unavailable, this will return 0.
+*/
+extern DECLSPEC int SDLCALL SDL_AndroidGetExternalStorageState();
+
+/* Get the path used for external storage for this application.
+   This path is unique to your application, but is public and can be
+   written to by other applications.
+ */
+extern DECLSPEC const char * SDLCALL SDL_AndroidGetExternalStoragePath();
+
+#endif /* __ANDROID__ */
+
+/* Platform specific functions for WinRT */
+#if defined(__WINRT__) && __WINRT__
+
+/**
+ *  \brief WinRT / Windows Phone path types
+ */
+typedef enum
+{
+    /** \brief The installed app's root directory.
+        Files here are likely to be read-only. */
+    SDL_WINRT_PATH_INSTALLED_LOCATION,
+
+    /** \brief The app's local data store.  Files may be written here */
+    SDL_WINRT_PATH_LOCAL_FOLDER,
+
+    /** \brief The app's roaming data store.  Unsupported on Windows Phone.
+        Files written here may be copied to other machines via a network
+        connection.
+    */
+    SDL_WINRT_PATH_ROAMING_FOLDER,
+
+    /** \brief The app's temporary data store.  Unsupported on Windows Phone.
+        Files written here may be deleted at any time. */
+    SDL_WINRT_PATH_TEMP_FOLDER
+} SDL_WinRT_Path;
+
+
+/**
+ *  \brief Retrieves a WinRT defined path on the local file system
+ *
+ *  \note Documentation on most app-specific path types on WinRT
+ *      can be found on MSDN, at the URL:
+ *      http://msdn.microsoft.com/en-us/library/windows/apps/hh464917.aspx
+ *
+ *  \param pathType The type of path to retrieve.
+ *  \ret A UCS-2 string (16-bit, wide-char) containing the path, or NULL
+ *      if the path is not available for any reason.  Not all paths are
+ *      available on all versions of Windows.  This is especially true on
+ *      Windows Phone.  Check the documentation for the given
+ *      SDL_WinRT_Path for more information on which path types are
+ *      supported where.
+ */
+extern DECLSPEC const wchar_t * SDLCALL SDL_WinRTGetFSPathUNICODE(SDL_WinRT_Path pathType);
+
+/**
+ *  \brief Retrieves a WinRT defined path on the local file system
+ *
+ *  \note Documentation on most app-specific path types on WinRT
+ *      can be found on MSDN, at the URL:
+ *      http://msdn.microsoft.com/en-us/library/windows/apps/hh464917.aspx
+ *
+ *  \param pathType The type of path to retrieve.
+ *  \ret A UTF-8 string (8-bit, multi-byte) containing the path, or NULL
+ *      if the path is not available for any reason.  Not all paths are
+ *      available on all versions of Windows.  This is especially true on
+ *      Windows Phone.  Check the documentation for the given
+ *      SDL_WinRT_Path for more information on which path types are
+ *      supported where.
+ */
+extern DECLSPEC const char * SDLCALL SDL_WinRTGetFSPathUTF8(SDL_WinRT_Path pathType);
+
+#endif /* __WINRT__ */
+
+
+/* Ends C function definitions when using C++ */
+#ifdef __cplusplus
+}
+#endif
+#include "close_code.h"
+
+#endif /* _SDL_system_h */
+
+/* vi: set ts=4 sw=4 expandtab: */
--- a/include/begin_code.h	Tue Mar 04 19:49:11 2014 -0500
+++ b/include/begin_code.h	Sun Mar 09 11:06:11 2014 -0700
@@ -1,140 +1,140 @@
-/*
-  Simple DirectMedia Layer
-  Copyright (C) 1997-2013 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.
-*/
-
-/**
- *  \file begin_code.h
- *
- *  This file sets things up for C dynamic library function definitions,
- *  static inlined functions, and structures aligned at 4-byte alignment.
- *  If you don't like ugly C preprocessor code, don't look at this file. :)
- */
-
-/* This shouldn't be nested -- included it around code only. */
-#ifdef _begin_code_h
-#error Nested inclusion of begin_code.h
-#endif
-#define _begin_code_h
-
-#ifndef SDL_DEPRECATED
-#  if (__GNUC__ >= 4)  /* technically, this arrived in gcc 3.1, but oh well. */
-#    define SDL_DEPRECATED __attribute__((deprecated))
-#  else
-#    define SDL_DEPRECATED
-#  endif
-#endif
-
-/* Some compilers use a special export keyword */
-#ifndef DECLSPEC
-# if defined(__WIN32__) || defined(__WINRT__)
-#  ifdef __BORLANDC__
-#   ifdef BUILD_SDL
-#    define DECLSPEC
-#   else
-#    define DECLSPEC    __declspec(dllimport)
-#   endif
-#  else
-#   define DECLSPEC __declspec(dllexport)
-#  endif
-# else
-#  if defined(__GNUC__) && __GNUC__ >= 4
-#   define DECLSPEC __attribute__ ((visibility("default")))
-#  elif defined(__GNUC__) && __GNUC__ >= 2
-#   define DECLSPEC __declspec(dllexport)
-#  else
-#   define DECLSPEC
-#  endif
-# endif
-#endif
-
-/* By default SDL uses the C calling convention */
-#ifndef SDLCALL
-#if (defined(__WIN32__) || defined(__WINRT__)) && !defined(__GNUC__)
-#define SDLCALL __cdecl
-#else
-#define SDLCALL
-#endif
-#endif /* SDLCALL */
-
-/* Removed DECLSPEC on Symbian OS because SDL cannot be a DLL in EPOC */
-#ifdef __SYMBIAN32__
-#undef DECLSPEC
-#define DECLSPEC
-#endif /* __SYMBIAN32__ */
-
-/* Force structure packing at 4 byte alignment.
-   This is necessary if the header is included in code which has structure
-   packing set to an alternate value, say for loading structures from disk.
-   The packing is reset to the previous value in close_code.h
- */
-#if defined(_MSC_VER) || defined(__MWERKS__) || defined(__BORLANDC__)
-#ifdef _MSC_VER
-#pragma warning(disable: 4103)
-#endif
-#ifdef __BORLANDC__
-#pragma nopackwarning
-#endif
-#ifdef _M_X64
-/* Use 8-byte alignment on 64-bit architectures, so pointers are aligned */
-#pragma pack(push,8)
-#else
-#pragma pack(push,4)
-#endif
-#endif /* Compiler needs structure packing set */
-
-#ifndef SDL_INLINE
-#if defined(__GNUC__)
-#define SDL_INLINE __inline__
-#elif defined(_MSC_VER) || defined(__BORLANDC__) || \
-      defined(__DMC__) || defined(__SC__) || \
-      defined(__WATCOMC__) || defined(__LCC__) || \
-      defined(__DECC)
-#define SDL_INLINE __inline
-#ifndef __inline__
-#define __inline__ __inline
-#endif
-#else
-#define SDL_INLINE inline
-#ifndef __inline__
-#define __inline__ inline
-#endif
-#endif
-#endif /* SDL_INLINE not defined */
-
-#ifndef SDL_FORCE_INLINE
-#if defined(_MSC_VER)
-#define SDL_FORCE_INLINE __forceinline
-#elif ( (defined(__GNUC__) && (__GNUC__ >= 4)) || defined(__clang__) )
-#define SDL_FORCE_INLINE __attribute__((always_inline)) static __inline__
-#else
-#define SDL_FORCE_INLINE static SDL_INLINE
-#endif
-#endif /* SDL_FORCE_INLINE not defined */
-
-/* Apparently this is needed by several Windows compilers */
-#if !defined(__MACH__)
-#ifndef NULL
-#ifdef __cplusplus
-#define NULL 0
-#else
-#define NULL ((void *)0)
-#endif
-#endif /* NULL */
-#endif /* ! Mac OS X - breaks precompiled headers */
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2013 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.
+*/
+
+/**
+ *  \file begin_code.h
+ *
+ *  This file sets things up for C dynamic library function definitions,
+ *  static inlined functions, and structures aligned at 4-byte alignment.
+ *  If you don't like ugly C preprocessor code, don't look at this file. :)
+ */
+
+/* This shouldn't be nested -- included it around code only. */
+#ifdef _begin_code_h
+#error Nested inclusion of begin_code.h
+#endif
+#define _begin_code_h
+
+#ifndef SDL_DEPRECATED
+#  if (__GNUC__ >= 4)  /* technically, this arrived in gcc 3.1, but oh well. */
+#    define SDL_DEPRECATED __attribute__((deprecated))
+#  else
+#    define SDL_DEPRECATED
+#  endif
+#endif
+
+/* Some compilers use a special export keyword */
+#ifndef DECLSPEC
+# if defined(__WIN32__) || defined(__WINRT__)
+#  ifdef __BORLANDC__
+#   ifdef BUILD_SDL
+#    define DECLSPEC
+#   else
+#    define DECLSPEC    __declspec(dllimport)
+#   endif
+#  else
+#   define DECLSPEC __declspec(dllexport)
+#  endif
+# else
+#  if defined(__GNUC__) && __GNUC__ >= 4
+#   define DECLSPEC __attribute__ ((visibility("default")))
+#  elif defined(__GNUC__) && __GNUC__ >= 2
+#   define DECLSPEC __declspec(dllexport)
+#  else
+#   define DECLSPEC
+#  endif
+# endif
+#endif
+
+/* By default SDL uses the C calling convention */
+#ifndef SDLCALL
+#if (defined(__WIN32__) || defined(__WINRT__)) && !defined(__GNUC__)
+#define SDLCALL __cdecl
+#else
+#define SDLCALL
+#endif
+#endif /* SDLCALL */
+
+/* Removed DECLSPEC on Symbian OS because SDL cannot be a DLL in EPOC */
+#ifdef __SYMBIAN32__
+#undef DECLSPEC
+#define DECLSPEC
+#endif /* __SYMBIAN32__ */
+
+/* Force structure packing at 4 byte alignment.
+   This is necessary if the header is included in code which has structure
+   packing set to an alternate value, say for loading structures from disk.
+   The packing is reset to the previous value in close_code.h
+ */
+#if defined(_MSC_VER) || defined(__MWERKS__) || defined(__BORLANDC__)
+#ifdef _MSC_VER
+#pragma warning(disable: 4103)
+#endif
+#ifdef __BORLANDC__
+#pragma nopackwarning
+#endif
+#ifdef _M_X64
+/* Use 8-byte alignment on 64-bit architectures, so pointers are aligned */
+#pragma pack(push,8)
+#else
+#pragma pack(push,4)
+#endif
+#endif /* Compiler needs structure packing set */
+
+#ifndef SDL_INLINE
+#if defined(__GNUC__)
+#define SDL_INLINE __inline__
+#elif defined(_MSC_VER) || defined(__BORLANDC__) || \
+      defined(__DMC__) || defined(__SC__) || \
+      defined(__WATCOMC__) || defined(__LCC__) || \
+      defined(__DECC)
+#define SDL_INLINE __inline
+#ifndef __inline__
+#define __inline__ __inline
+#endif
+#else
+#define SDL_INLINE inline
+#ifndef __inline__
+#define __inline__ inline
+#endif
+#endif
+#endif /* SDL_INLINE not defined */
+
+#ifndef SDL_FORCE_INLINE
+#if defined(_MSC_VER)
+#define SDL_FORCE_INLINE __forceinline
+#elif ( (defined(__GNUC__) && (__GNUC__ >= 4)) || defined(__clang__) )
+#define SDL_FORCE_INLINE __attribute__((always_inline)) static __inline__
+#else
+#define SDL_FORCE_INLINE static SDL_INLINE
+#endif
+#endif /* SDL_FORCE_INLINE not defined */
+
+/* Apparently this is needed by several Windows compilers */
+#if !defined(__MACH__)
+#ifndef NULL
+#ifdef __cplusplus
+#define NULL 0
+#else
+#define NULL ((void *)0)
+#endif
+#endif /* NULL */
+#endif /* ! Mac OS X - breaks precompiled headers */
--- a/src/SDL_log.c	Tue Mar 04 19:49:11 2014 -0500
+++ b/src/SDL_log.c	Sun Mar 09 11:06:11 2014 -0700
@@ -1,439 +1,439 @@
-/*
-  Simple DirectMedia Layer
-  Copyright (C) 1997-2013 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 "SDL_config.h"
-
-#if defined(__WIN32__) || defined(__WINRT__)
-#include "core/windows/SDL_windows.h"
-#endif
-
-/* Simple log messages in SDL */
-
-#include "SDL_log.h"
-
-#if HAVE_STDIO_H
-#include <stdio.h>
-#endif
-
-#if defined(__ANDROID__)
-#include <android/log.h>
-#endif
-
-#define DEFAULT_PRIORITY                SDL_LOG_PRIORITY_CRITICAL
-#define DEFAULT_ASSERT_PRIORITY         SDL_LOG_PRIORITY_WARN
-#define DEFAULT_APPLICATION_PRIORITY    SDL_LOG_PRIORITY_INFO
-#define DEFAULT_TEST_PRIORITY           SDL_LOG_PRIORITY_VERBOSE
-
-/* Forward definition of error function */
-extern int SDL_SetError(const char *fmt, ...);
-
-typedef struct SDL_LogLevel
-{
-    int category;
-    SDL_LogPriority priority;
-    struct SDL_LogLevel *next;
-} SDL_LogLevel;
-
-/* The default log output function */
-static void SDL_LogOutput(void *userdata,
-                          int category, SDL_LogPriority priority,
-                          const char *message);
-
-static SDL_LogLevel *SDL_loglevels;
-static SDL_LogPriority SDL_default_priority = DEFAULT_PRIORITY;
-static SDL_LogPriority SDL_assert_priority = DEFAULT_ASSERT_PRIORITY;
-static SDL_LogPriority SDL_application_priority = DEFAULT_APPLICATION_PRIORITY;
-static SDL_LogPriority SDL_test_priority = DEFAULT_TEST_PRIORITY;
-static SDL_LogOutputFunction SDL_log_function = SDL_LogOutput;
-static void *SDL_log_userdata = NULL;
-
-static const char *SDL_priority_prefixes[SDL_NUM_LOG_PRIORITIES] = {
-    NULL,
-    "VERBOSE",
-    "DEBUG",
-    "INFO",
-    "WARN",
-    "ERROR",
-    "CRITICAL"
-};
-
-#ifdef __ANDROID__
-static const char *SDL_category_prefixes[SDL_LOG_CATEGORY_RESERVED1] = {
-    "APP",
-    "ERROR",
-    "SYSTEM",
-    "AUDIO",
-    "VIDEO",
-    "RENDER",
-    "INPUT"
-};
-
-static int SDL_android_priority[SDL_NUM_LOG_PRIORITIES] = {
-    ANDROID_LOG_UNKNOWN,
-    ANDROID_LOG_VERBOSE,
-    ANDROID_LOG_DEBUG,
-    ANDROID_LOG_INFO,
-    ANDROID_LOG_WARN,
-    ANDROID_LOG_ERROR,
-    ANDROID_LOG_FATAL
-};
-#endif /* __ANDROID__ */
-
-
-void
-SDL_LogSetAllPriority(SDL_LogPriority priority)
-{
-    SDL_LogLevel *entry;
-
-    for (entry = SDL_loglevels; entry; entry = entry->next) {
-        entry->priority = priority;
-    }
-    SDL_default_priority = priority;
-    SDL_assert_priority = priority;
-    SDL_application_priority = priority;
-}
-
-void
-SDL_LogSetPriority(int category, SDL_LogPriority priority)
-{
-    SDL_LogLevel *entry;
-
-    for (entry = SDL_loglevels; entry; entry = entry->next) {
-        if (entry->category == category) {
-            entry->priority = priority;
-            return;
-        }
-    }
-
-    /* Create a new entry */
-    entry = (SDL_LogLevel *)SDL_malloc(sizeof(*entry));
-    if (entry) {
-        entry->category = category;
-        entry->priority = priority;
-        entry->next = SDL_loglevels;
-        SDL_loglevels = entry;
-    }
-}
-
-SDL_LogPriority
-SDL_LogGetPriority(int category)
-{
-    SDL_LogLevel *entry;
-
-    for (entry = SDL_loglevels; entry; entry = entry->next) {
-        if (entry->category == category) {
-            return entry->priority;
-        }
-    }
-
-    if (category == SDL_LOG_CATEGORY_TEST) {
-        return SDL_test_priority;
-    } else if (category == SDL_LOG_CATEGORY_APPLICATION) {
-        return SDL_application_priority;
-    } else if (category == SDL_LOG_CATEGORY_ASSERT) {
-        return SDL_assert_priority;
-    } else {
-        return SDL_default_priority;
-    }
-}
-
-void
-SDL_LogResetPriorities(void)
-{
-    SDL_LogLevel *entry;
-
-    while (SDL_loglevels) {
-        entry = SDL_loglevels;
-        SDL_loglevels = entry->next;
-        SDL_free(entry);
-    }
-
-    SDL_default_priority = DEFAULT_PRIORITY;
-    SDL_assert_priority = DEFAULT_ASSERT_PRIORITY;
-    SDL_application_priority = DEFAULT_APPLICATION_PRIORITY;
-    SDL_test_priority = DEFAULT_TEST_PRIORITY;
-}
-
-void
-SDL_Log(const char *fmt, ...)
-{
-    va_list ap;
-
-    va_start(ap, fmt);
-    SDL_LogMessageV(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, fmt, ap);
-    va_end(ap);
-}
-
-void
-SDL_LogVerbose(int category, const char *fmt, ...)
-{
-    va_list ap;
-
-    va_start(ap, fmt);
-    SDL_LogMessageV(category, SDL_LOG_PRIORITY_VERBOSE, fmt, ap);
-    va_end(ap);
-}
-
-void
-SDL_LogDebug(int category, const char *fmt, ...)
-{
-    va_list ap;
-
-    va_start(ap, fmt);
-    SDL_LogMessageV(category, SDL_LOG_PRIORITY_DEBUG, fmt, ap);
-    va_end(ap);
-}
-
-void
-SDL_LogInfo(int category, const char *fmt, ...)
-{
-    va_list ap;
-
-    va_start(ap, fmt);
-    SDL_LogMessageV(category, SDL_LOG_PRIORITY_INFO, fmt, ap);
-    va_end(ap);
-}
-
-void
-SDL_LogWarn(int category, const char *fmt, ...)
-{
-    va_list ap;
-
-    va_start(ap, fmt);
-    SDL_LogMessageV(category, SDL_LOG_PRIORITY_WARN, fmt, ap);
-    va_end(ap);
-}
-
-void
-SDL_LogError(int category, const char *fmt, ...)
-{
-    va_list ap;
-
-    va_start(ap, fmt);
-    SDL_LogMessageV(category, SDL_LOG_PRIORITY_ERROR, fmt, ap);
-    va_end(ap);
-}
-
-void
-SDL_LogCritical(int category, const char *fmt, ...)
-{
-    va_list ap;
-
-    va_start(ap, fmt);
-    SDL_LogMessageV(category, SDL_LOG_PRIORITY_CRITICAL, fmt, ap);
-    va_end(ap);
-}
-
-void
-SDL_LogMessage(int category, SDL_LogPriority priority, const char *fmt, ...)
-{
-    va_list ap;
-
-    va_start(ap, fmt);
-    SDL_LogMessageV(category, priority, fmt, ap);
-    va_end(ap);
-}
-
-#ifdef __ANDROID__
-static const char *
-GetCategoryPrefix(int category)
-{
-    if (category < SDL_LOG_CATEGORY_RESERVED1) {
-        return SDL_category_prefixes[category];
-    }
-    if (category < SDL_LOG_CATEGORY_CUSTOM) {
-        return "RESERVED";
-    }
-    return "CUSTOM";
-}
-#endif /* __ANDROID__ */
-
-void
-SDL_LogMessageV(int category, SDL_LogPriority priority, const char *fmt, va_list ap)
-{
-    char *message;
-    size_t len;
-
-    /* Nothing to do if we don't have an output function */
-    if (!SDL_log_function) {
-        return;
-    }
-
-    /* Make sure we don't exceed array bounds */
-    if ((int)priority < 0 || priority >= SDL_NUM_LOG_PRIORITIES) {
-        return;
-    }
-
-    /* See if we want to do anything with this message */
-    if (priority < SDL_LogGetPriority(category)) {
-        return;
-    }
-
-    message = SDL_stack_alloc(char, SDL_MAX_LOG_MESSAGE);
-    if (!message) {
-        return;
-    }
-
-    SDL_vsnprintf(message, SDL_MAX_LOG_MESSAGE, fmt, ap);
-
-    /* Chop off final endline. */
-    len = SDL_strlen(message);
-    if ((len > 0) && (message[len-1] == '\n')) {
-        message[--len] = '\0';
-        if ((len > 0) && (message[len-1] == '\r')) {  /* catch "\r\n", too. */
-            message[--len] = '\0';
-        }
-    }
-
-    SDL_log_function(SDL_log_userdata, category, priority, message);
-    SDL_stack_free(message);
-}
-
-#if defined(__WIN32__)
-/* Flag tracking the attachment of the console: 0=unattached, 1=attached, -1=error */
-static int consoleAttached = 0;
-
-/* Handle to stderr output of console. */
-static HANDLE stderrHandle = NULL;
-#endif
-
-static void
-SDL_LogOutput(void *userdata, int category, SDL_LogPriority priority,
-              const char *message)
-{
-#if defined(__WIN32__) || defined(__WINRT__)
-    /* Way too many allocations here, urgh */
-    /* Note: One can't call SDL_SetError here, since that function itself logs. */
-    {
-        char *output;
-        size_t length;
-        LPTSTR tstr;
-
-#ifndef __WINRT__
-        BOOL attachResult;
-        DWORD attachError;
-        unsigned long charsWritten; 
-
-        /* Maybe attach console and get stderr handle */
-        if (consoleAttached == 0) {
-            attachResult = AttachConsole(ATTACH_PARENT_PROCESS);
-            if (!attachResult) {
-                    attachError = GetLastError();
-                    if (attachError == ERROR_INVALID_HANDLE) {
-                        OutputDebugString(TEXT("Parent process has no console\r\n"));
-                        consoleAttached = -1;
-                    } else if (attachError == ERROR_GEN_FAILURE) {
-                         OutputDebugString(TEXT("Could not attach to console of parent process\r\n"));
-                         consoleAttached = -1;
-                    } else if (attachError == ERROR_ACCESS_DENIED) {  
-                         /* Already attached */
-                        consoleAttached = 1;
-                    } else {
-                        OutputDebugString(TEXT("Error attaching console\r\n"));
-                        consoleAttached = -1;
-                    }
-                } else {
-                    /* Newly attached */
-                    consoleAttached = 1;
-                }
-			
-                if (consoleAttached == 1) {
-                        stderrHandle = GetStdHandle(STD_ERROR_HANDLE);
-                }
-        }
-#endif /* ifndef __WINRT__ */
-
-        length = SDL_strlen(SDL_priority_prefixes[priority]) + 2 + SDL_strlen(message) + 1 + 1 + 1;
-        output = SDL_stack_alloc(char, length);
-        SDL_snprintf(output, length, "%s: %s\r\n", SDL_priority_prefixes[priority], message);
-        tstr = WIN_UTF8ToString(output);
-        
-        /* Output to debugger */
-        OutputDebugString(tstr);
-       
-#ifndef __WINRT__
-        /* Screen output to stderr, if console was attached. */
-        if (consoleAttached == 1) {
-                if (!WriteConsole(stderrHandle, tstr, lstrlen(tstr), &charsWritten, NULL)) {
-                    OutputDebugString(TEXT("Error calling WriteConsole\r\n"));
-                }
-                if (charsWritten == ERROR_NOT_ENOUGH_MEMORY) {
-                    OutputDebugString(TEXT("Insufficient heap memory to write message\r\n"));
-                }
-        }
-#endif /* ifndef __WINRT__ */
-
-        SDL_free(tstr);
-        SDL_stack_free(output);
-    }
-#elif defined(__ANDROID__)
-    {
-        char tag[32];
-
-        SDL_snprintf(tag, SDL_arraysize(tag), "SDL/%s", GetCategoryPrefix(category));
-        __android_log_write(SDL_android_priority[priority], tag, message);
-    }
-#elif defined(__APPLE__) && defined(SDL_VIDEO_DRIVER_COCOA)
-    /* Technically we don't need SDL_VIDEO_DRIVER_COCOA, but that's where this function is defined for now.
-    */
-    extern void SDL_NSLog(const char *text);
-    {
-        char *text;
-
-        text = SDL_stack_alloc(char, SDL_MAX_LOG_MESSAGE);
-        if (text) {
-            SDL_snprintf(text, SDL_MAX_LOG_MESSAGE, "%s: %s", SDL_priority_prefixes[priority], message);
-            SDL_NSLog(text);
-            SDL_stack_free(text);
-            return;
-        }
-    }
-#elif defined(__PSP__)
-    {
-        FILE*        pFile;
-        pFile = fopen ("SDL_Log.txt", "a");
-        fprintf(pFile, "%s: %s\n", SDL_priority_prefixes[priority], message);
-        fclose (pFile);
-    }
-#endif
-#if HAVE_STDIO_H
-    fprintf(stderr, "%s: %s\n", SDL_priority_prefixes[priority], message);
-#endif
-}
-
-void
-SDL_LogGetOutputFunction(SDL_LogOutputFunction *callback, void **userdata)
-{
-    if (callback) {
-        *callback = SDL_log_function;
-    }
-    if (userdata) {
-        *userdata = SDL_log_userdata;
-    }
-}
-
-void
-SDL_LogSetOutputFunction(SDL_LogOutputFunction callback, void *userdata)
-{
-    SDL_log_function = callback;
-    SDL_log_userdata = userdata;
-}
-
-/* vi: set ts=4 sw=4 expandtab: */
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2013 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 "SDL_config.h"
+
+#if defined(__WIN32__) || defined(__WINRT__)
+#include "core/windows/SDL_windows.h"
+#endif
+
+/* Simple log messages in SDL */
+
+#include "SDL_log.h"
+
+#if HAVE_STDIO_H
+#include <stdio.h>
+#endif
+
+#if defined(__ANDROID__)
+#include <android/log.h>
+#endif
+
+#define DEFAULT_PRIORITY                SDL_LOG_PRIORITY_CRITICAL
+#define DEFAULT_ASSERT_PRIORITY         SDL_LOG_PRIORITY_WARN
+#define DEFAULT_APPLICATION_PRIORITY    SDL_LOG_PRIORITY_INFO
+#define DEFAULT_TEST_PRIORITY           SDL_LOG_PRIORITY_VERBOSE
+
+/* Forward definition of error function */
+extern int SDL_SetError(const char *fmt, ...);
+
+typedef struct SDL_LogLevel
+{
+    int category;
+    SDL_LogPriority priority;
+    struct SDL_LogLevel *next;
+} SDL_LogLevel;
+
+/* The default log output function */
+static void SDL_LogOutput(void *userdata,
+                          int category, SDL_LogPriority priority,
+                          const char *message);
+
+static SDL_LogLevel *SDL_loglevels;
+static SDL_LogPriority SDL_default_priority = DEFAULT_PRIORITY;
+static SDL_LogPriority SDL_assert_priority = DEFAULT_ASSERT_PRIORITY;
+static SDL_LogPriority SDL_application_priority = DEFAULT_APPLICATION_PRIORITY;
+static SDL_LogPriority SDL_test_priority = DEFAULT_TEST_PRIORITY;
+static SDL_LogOutputFunction SDL_log_function = SDL_LogOutput;
+static void *SDL_log_userdata = NULL;
+
+static const char *SDL_priority_prefixes[SDL_NUM_LOG_PRIORITIES] = {
+    NULL,
+    "VERBOSE",
+    "DEBUG",
+    "INFO",
+    "WARN",
+    "ERROR",
+    "CRITICAL"
+};
+
+#ifdef __ANDROID__
+static const char *SDL_category_prefixes[SDL_LOG_CATEGORY_RESERVED1] = {
+    "APP",
+    "ERROR",
+    "SYSTEM",
+    "AUDIO",
+    "VIDEO",
+    "RENDER",
+    "INPUT"
+};
+
+static int SDL_android_priority[SDL_NUM_LOG_PRIORITIES] = {
+    ANDROID_LOG_UNKNOWN,
+    ANDROID_LOG_VERBOSE,
+    ANDROID_LOG_DEBUG,
+    ANDROID_LOG_INFO,
+    ANDROID_LOG_WARN,
+    ANDROID_LOG_ERROR,
+    ANDROID_LOG_FATAL
+};
+#endif /* __ANDROID__ */
+
+
+void
+SDL_LogSetAllPriority(SDL_LogPriority priority)
+{
+    SDL_LogLevel *entry;
+
+    for (entry = SDL_loglevels; entry; entry = entry->next) {
+        entry->priority = priority;
+    }
+    SDL_default_priority = priority;
+    SDL_assert_priority = priority;
+    SDL_application_priority = priority;
+}
+
+void
+SDL_LogSetPriority(int category, SDL_LogPriority priority)
+{
+    SDL_LogLevel *entry;
+
+    for (entry = SDL_loglevels; entry; entry = entry->next) {
+        if (entry->category == category) {
+            entry->priority = priority;
+            return;
+        }
+    }
+
+    /* Create a new entry */
+    entry = (SDL_LogLevel *)SDL_malloc(sizeof(*entry));
+    if (entry) {
+        entry->category = category;
+        entry->priority = priority;
+        entry->next = SDL_loglevels;
+        SDL_loglevels = entry;
+    }
+}
+
+SDL_LogPriority
+SDL_LogGetPriority(int category)
+{
+    SDL_LogLevel *entry;
+
+    for (entry = SDL_loglevels; entry; entry = entry->next) {
+        if (entry->category == category) {
+            return entry->priority;
+        }
+    }
+
+    if (category == SDL_LOG_CATEGORY_TEST) {
+        return SDL_test_priority;
+    } else if (category == SDL_LOG_CATEGORY_APPLICATION) {
+        return SDL_application_priority;
+    } else if (category == SDL_LOG_CATEGORY_ASSERT) {
+        return SDL_assert_priority;
+    } else {
+        return SDL_default_priority;
+    }
+}
+
+void
+SDL_LogResetPriorities(void)
+{
+    SDL_LogLevel *entry;
+
+    while (SDL_loglevels) {
+        entry = SDL_loglevels;
+        SDL_loglevels = entry->next;
+        SDL_free(entry);
+    }
+
+    SDL_default_priority = DEFAULT_PRIORITY;
+    SDL_assert_priority = DEFAULT_ASSERT_PRIORITY;
+    SDL_application_priority = DEFAULT_APPLICATION_PRIORITY;
+    SDL_test_priority = DEFAULT_TEST_PRIORITY;
+}
+
+void
+SDL_Log(const char *fmt, ...)
+{
+    va_list ap;
+
+    va_start(ap, fmt);
+    SDL_LogMessageV(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO, fmt, ap);
+    va_end(ap);
+}
+
+void
+SDL_LogVerbose(int category, const char *fmt, ...)
+{
+    va_list ap;
+
+    va_start(ap, fmt);
+    SDL_LogMessageV(category, SDL_LOG_PRIORITY_VERBOSE, fmt, ap);
+    va_end(ap);
+}
+
+void
+SDL_LogDebug(int category, const char *fmt, ...)
+{
+    va_list ap;
+
+    va_start(ap, fmt);
+    SDL_LogMessageV(category, SDL_LOG_PRIORITY_DEBUG, fmt, ap);
+    va_end(ap);
+}
+
+void
+SDL_LogInfo(int category, const char *fmt, ...)
+{
+    va_list ap;
+
+    va_start(ap, fmt);
+    SDL_LogMessageV(category, SDL_LOG_PRIORITY_INFO, fmt, ap);
+    va_end(ap);
+}
+
+void
+SDL_LogWarn(int category, const char *fmt, ...)
+{
+    va_list ap;
+
+    va_start(ap, fmt);
+    SDL_LogMessageV(category, SDL_LOG_PRIORITY_WARN, fmt, ap);
+    va_end(ap);
+}
+
+void
+SDL_LogError(int category, const char *fmt, ...)
+{
+    va_list ap;
+
+    va_start(ap, fmt);
+    SDL_LogMessageV(category, SDL_LOG_PRIORITY_ERROR, fmt, ap);
+    va_end(ap);
+}
+
+void
+SDL_LogCritical(int category, const char *fmt, ...)
+{
+    va_list ap;
+
+    va_start(ap, fmt);
+    SDL_LogMessageV(category, SDL_LOG_PRIORITY_CRITICAL, fmt, ap);
+    va_end(ap);
+}
+
+void
+SDL_LogMessage(int category, SDL_LogPriority priority, const char *fmt, ...)
+{
+    va_list ap;
+
+    va_start(ap, fmt);
+    SDL_LogMessageV(category, priority, fmt, ap);
+    va_end(ap);
+}
+
+#ifdef __ANDROID__
+static const char *
+GetCategoryPrefix(int category)
+{
+    if (category < SDL_LOG_CATEGORY_RESERVED1) {
+        return SDL_category_prefixes[category];
+    }
+    if (category < SDL_LOG_CATEGORY_CUSTOM) {
+        return "RESERVED";
+    }
+    return "CUSTOM";
+}
+#endif /* __ANDROID__ */
+
+void
+SDL_LogMessageV(int category, SDL_LogPriority priority, const char *fmt, va_list ap)
+{
+    char *message;
+    size_t len;
+
+    /* Nothing to do if we don't have an output function */
+    if (!SDL_log_function) {
+        return;
+    }
+
+    /* Make sure we don't exceed array bounds */
+    if ((int)priority < 0 || priority >= SDL_NUM_LOG_PRIORITIES) {
+        return;
+    }
+
+    /* See if we want to do anything with this message */
+    if (priority < SDL_LogGetPriority(category)) {
+        return;
+    }
+
+    message = SDL_stack_alloc(char, SDL_MAX_LOG_MESSAGE);
+    if (!message) {
+        return;
+    }
+
+    SDL_vsnprintf(message, SDL_MAX_LOG_MESSAGE, fmt, ap);
+
+    /* Chop off final endline. */
+    len = SDL_strlen(message);
+    if ((len > 0) && (message[len-1] == '\n')) {
+        message[--len] = '\0';
+        if ((len > 0) && (message[len-1] == '\r')) {  /* catch "\r\n", too. */
+            message[--len] = '\0';
+        }
+    }
+
+    SDL_log_function(SDL_log_userdata, category, priority, message);
+    SDL_stack_free(message);
+}
+
+#if defined(__WIN32__)
+/* Flag tracking the attachment of the console: 0=unattached, 1=attached, -1=error */
+static int consoleAttached = 0;
+
+/* Handle to stderr output of console. */
+static HANDLE stderrHandle = NULL;
+#endif
+
+static void
+SDL_LogOutput(void *userdata, int category, SDL_LogPriority priority,
+              const char *message)
+{
+#if defined(__WIN32__) || defined(__WINRT__)
+    /* Way too many allocations here, urgh */
+    /* Note: One can't call SDL_SetError here, since that function itself logs. */
+    {
+        char *output;
+        size_t length;
+        LPTSTR tstr;
+
+#ifndef __WINRT__
+        BOOL attachResult;
+        DWORD attachError;
+        unsigned long charsWritten; 
+
+        /* Maybe attach console and get stderr handle */
+        if (consoleAttached == 0) {
+            attachResult = AttachConsole(ATTACH_PARENT_PROCESS);
+            if (!attachResult) {
+                    attachError = GetLastError();
+                    if (attachError == ERROR_INVALID_HANDLE) {
+                        OutputDebugString(TEXT("Parent process has no console\r\n"));
+                        consoleAttached = -1;
+                    } else if (attachError == ERROR_GEN_FAILURE) {
+                         OutputDebugString(TEXT("Could not attach to console of parent process\r\n"));
+                         consoleAttached = -1;
+                    } else if (attachError == ERROR_ACCESS_DENIED) {  
+                         /* Already attached */
+                        consoleAttached = 1;
+                    } else {
+                        OutputDebugString(TEXT("Error attaching console\r\n"));
+                        consoleAttached = -1;
+                    }
+                } else {
+                    /* Newly attached */
+                    consoleAttached = 1;
+                }
+			
+                if (consoleAttached == 1) {
+                        stderrHandle = GetStdHandle(STD_ERROR_HANDLE);
+                }
+        }
+#endif /* ifndef __WINRT__ */
+
+        length = SDL_strlen(SDL_priority_prefixes[priority]) + 2 + SDL_strlen(message) + 1 + 1 + 1;
+        output = SDL_stack_alloc(char, length);
+        SDL_snprintf(output, length, "%s: %s\r\n", SDL_priority_prefixes[priority], message);
+        tstr = WIN_UTF8ToString(output);
+        
+        /* Output to debugger */
+        OutputDebugString(tstr);
+       
+#ifndef __WINRT__
+        /* Screen output to stderr, if console was attached. */
+        if (consoleAttached == 1) {
+                if (!WriteConsole(stderrHandle, tstr, lstrlen(tstr), &charsWritten, NULL)) {
+                    OutputDebugString(TEXT("Error calling WriteConsole\r\n"));
+                }
+                if (charsWritten == ERROR_NOT_ENOUGH_MEMORY) {
+                    OutputDebugString(TEXT("Insufficient heap memory to write message\r\n"));
+                }
+        }
+#endif /* ifndef __WINRT__ */
+
+        SDL_free(tstr);
+        SDL_stack_free(output);
+    }
+#elif defined(__ANDROID__)
+    {
+        char tag[32];
+
+        SDL_snprintf(tag, SDL_arraysize(tag), "SDL/%s", GetCategoryPrefix(category));
+        __android_log_write(SDL_android_priority[priority], tag, message);
+    }
+#elif defined(__APPLE__) && defined(SDL_VIDEO_DRIVER_COCOA)
+    /* Technically we don't need SDL_VIDEO_DRIVER_COCOA, but that's where this function is defined for now.
+    */
+    extern void SDL_NSLog(const char *text);
+    {
+        char *text;
+
+        text = SDL_stack_alloc(char, SDL_MAX_LOG_MESSAGE);
+        if (text) {
+            SDL_snprintf(text, SDL_MAX_LOG_MESSAGE, "%s: %s", SDL_priority_prefixes[priority], message);
+            SDL_NSLog(text);
+            SDL_stack_free(text);
+            return;
+        }
+    }
+#elif defined(__PSP__)
+    {
+        FILE*        pFile;
+        pFile = fopen ("SDL_Log.txt", "a");
+        fprintf(pFile, "%s: %s\n", SDL_priority_prefixes[priority], message);
+        fclose (pFile);
+    }
+#endif
+#if HAVE_STDIO_H
+    fprintf(stderr, "%s: %s\n", SDL_priority_prefixes[priority], message);
+#endif
+}
+
+void
+SDL_LogGetOutputFunction(SDL_LogOutputFunction *callback, void **userdata)
+{
+    if (callback) {
+        *callback = SDL_log_function;
+    }
+    if (userdata) {
+        *userdata = SDL_log_userdata;
+    }
+}
+
+void
+SDL_LogSetOutputFunction(SDL_LogOutputFunction callback, void *userdata)
+{
+    SDL_log_function = callback;
+    SDL_log_userdata = userdata;
+}
+
+/* vi: set ts=4 sw=4 expandtab: */
--- a/src/atomic/SDL_spinlock.c	Tue Mar 04 19:49:11 2014 -0500
+++ b/src/atomic/SDL_spinlock.c	Sun Mar 09 11:06:11 2014 -0700
@@ -1,126 +1,126 @@
-/*
-  Simple DirectMedia Layer
-  Copyright (C) 1997-2013 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 "SDL_config.h"
-
-#if defined(__WIN32__) || defined(__WINRT__)
-#include "../core/windows/SDL_windows.h"
-#endif
-
-#include "SDL_atomic.h"
-#include "SDL_mutex.h"
-#include "SDL_timer.h"
-
-
-/* This function is where all the magic happens... */
-SDL_bool
-SDL_AtomicTryLock(SDL_SpinLock *lock)
-{
-#if SDL_ATOMIC_DISABLED
-    /* Terrible terrible damage */
-    static SDL_mutex *_spinlock_mutex;
-
-    if (!_spinlock_mutex) {
-        /* Race condition on first lock... */
-        _spinlock_mutex = SDL_CreateMutex();
-    }
-    SDL_LockMutex(_spinlock_mutex);
-    if (*lock == 0) {
-        *lock = 1;
-        SDL_UnlockMutex(_spinlock_mutex);
-        return SDL_TRUE;
-    } else {
-        SDL_UnlockMutex(_spinlock_mutex);
-        return SDL_FALSE;
-    }
-
-#elif defined(_MSC_VER)
-    SDL_COMPILE_TIME_ASSERT(locksize, sizeof(*lock) == sizeof(long));
-    return (InterlockedExchange((long*)lock, 1) == 0);
-
-#elif HAVE_GCC_ATOMICS || HAVE_GCC_SYNC_LOCK_TEST_AND_SET
-    return (__sync_lock_test_and_set(lock, 1) == 0);
-
-#elif defined(__GNUC__) && defined(__arm__) && \
-        (defined(__ARM_ARCH_4__) || defined(__ARM_ARCH_4T__) || \
-         defined(__ARM_ARCH_5__) || defined(__ARM_ARCH_5TE__) || \
-         defined(__ARM_ARCH_5TEJ__))
-    int result;
-    __asm__ __volatile__ (
-        "swp %0, %1, [%2]\n"
-        : "=&r,&r" (result) : "r,0" (1), "r,r" (lock) : "memory");
-    return (result == 0);
-
-#elif defined(__GNUC__) && defined(__arm__)
-    int result;
-    __asm__ __volatile__ (
-        "ldrex %0, [%2]\nteq   %0, #0\nstrexeq %0, %1, [%2]"
-        : "=&r" (result) : "r" (1), "r" (lock) : "cc", "memory");
-    return (result == 0);
-
-#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
-    int result;
-    __asm__ __volatile__(
-        "lock ; xchgl %0, (%1)\n"
-        : "=r" (result) : "r" (lock), "0" (1) : "cc", "memory");
-    return (result == 0);
-
-#elif defined(__MACOSX__) || defined(__IPHONEOS__)
-    /* Maybe used for PowerPC, but the Intel asm or gcc atomics are favored. */
-    return OSAtomicCompareAndSwap32Barrier(0, 1, lock);
-
-#elif HAVE_PTHREAD_SPINLOCK
-    /* pthread instructions */
-    return (pthread_spin_trylock(lock) == 0);
-
-#else
-#error Please implement for your platform.
-    return SDL_FALSE;
-#endif
-}
-
-void
-SDL_AtomicLock(SDL_SpinLock *lock)
-{
-    /* FIXME: Should we have an eventual timeout? */
-    while (!SDL_AtomicTryLock(lock)) {
-        SDL_Delay(0);
-    }
-}
-
-void
-SDL_AtomicUnlock(SDL_SpinLock *lock)
-{
-#if defined(_MSC_VER)
-    _ReadWriteBarrier();
-    *lock = 0;
-
-#elif HAVE_GCC_ATOMICS || HAVE_GCC_SYNC_LOCK_TEST_AND_SET
-    __sync_lock_release(lock);
-
-#elif HAVE_PTHREAD_SPINLOCK
-    pthread_spin_unlock(lock);
-
-#else
-    *lock = 0;
-#endif
-}
-
-/* vi: set ts=4 sw=4 expandtab: */
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2013 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 "SDL_config.h"
+
+#if defined(__WIN32__) || defined(__WINRT__)
+#include "../core/windows/SDL_windows.h"
+#endif
+
+#include "SDL_atomic.h"
+#include "SDL_mutex.h"
+#include "SDL_timer.h"
+
+
+/* This function is where all the magic happens... */
+SDL_bool
+SDL_AtomicTryLock(SDL_SpinLock *lock)
+{
+#if SDL_ATOMIC_DISABLED
+    /* Terrible terrible damage */
+    static SDL_mutex *_spinlock_mutex;
+
+    if (!_spinlock_mutex) {
+        /* Race condition on first lock... */
+        _spinlock_mutex = SDL_CreateMutex();
+    }
+    SDL_LockMutex(_spinlock_mutex);
+    if (*lock == 0) {
+        *lock = 1;
+        SDL_UnlockMutex(_spinlock_mutex);
+        return SDL_TRUE;
+    } else {
+        SDL_UnlockMutex(_spinlock_mutex);
+        return SDL_FALSE;
+    }
+
+#elif defined(_MSC_VER)
+    SDL_COMPILE_TIME_ASSERT(locksize, sizeof(*lock) == sizeof(long));
+    return (InterlockedExchange((long*)lock, 1) == 0);
+
+#elif HAVE_GCC_ATOMICS || HAVE_GCC_SYNC_LOCK_TEST_AND_SET
+    return (__sync_lock_test_and_set(lock, 1) == 0);
+
+#elif defined(__GNUC__) && defined(__arm__) && \
+        (defined(__ARM_ARCH_4__) || defined(__ARM_ARCH_4T__) || \
+         defined(__ARM_ARCH_5__) || defined(__ARM_ARCH_5TE__) || \
+         defined(__ARM_ARCH_5TEJ__))
+    int result;
+    __asm__ __volatile__ (
+        "swp %0, %1, [%2]\n"
+        : "=&r,&r" (result) : "r,0" (1), "r,r" (lock) : "memory");
+    return (result == 0);
+
+#elif defined(__GNUC__) && defined(__arm__)
+    int result;
+    __asm__ __volatile__ (
+        "ldrex %0, [%2]\nteq   %0, #0\nstrexeq %0, %1, [%2]"
+        : "=&r" (result) : "r" (1), "r" (lock) : "cc", "memory");
+    return (result == 0);
+
+#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
+    int result;
+    __asm__ __volatile__(
+        "lock ; xchgl %0, (%1)\n"
+        : "=r" (result) : "r" (lock), "0" (1) : "cc", "memory");
+    return (result == 0);
+
+#elif defined(__MACOSX__) || defined(__IPHONEOS__)
+    /* Maybe used for PowerPC, but the Intel asm or gcc atomics are favored. */
+    return OSAtomicCompareAndSwap32Barrier(0, 1, lock);
+
+#elif HAVE_PTHREAD_SPINLOCK
+    /* pthread instructions */
+    return (pthread_spin_trylock(lock) == 0);
+
+#else
+#error Please implement for your platform.
+    return SDL_FALSE;
+#endif
+}
+
+void
+SDL_AtomicLock(SDL_SpinLock *lock)
+{
+    /* FIXME: Should we have an eventual timeout? */
+    while (!SDL_AtomicTryLock(lock)) {
+        SDL_Delay(0);
+    }
+}
+
+void
+SDL_AtomicUnlock(SDL_SpinLock *lock)
+{
+#if defined(_MSC_VER)
+    _ReadWriteBarrier();
+    *lock = 0;
+
+#elif HAVE_GCC_ATOMICS || HAVE_GCC_SYNC_LOCK_TEST_AND_SET
+    __sync_lock_release(lock);
+
+#elif HAVE_PTHREAD_SPINLOCK
+    pthread_spin_unlock(lock);
+
+#else
+    *lock = 0;
+#endif
+}
+
+/* vi: set ts=4 sw=4 expandtab: */
--- a/src/audio/xaudio2/SDL_xaudio2.c	Tue Mar 04 19:49:11 2014 -0500
+++ b/src/audio/xaudio2/SDL_xaudio2.c	Sun Mar 09 11:06:11 2014 -0700
@@ -1,543 +1,543 @@
-/*
-  Simple DirectMedia Layer
-  Copyright (C) 1997-2013 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.
-*/
-
-/* WinRT NOTICE:
-
-   A few changes to SDL's XAudio2 backend were warranted by API
-   changes to Windows.  Many, but not all of these are documented by Microsoft
-   at:
-   http://blogs.msdn.com/b/chuckw/archive/2012/04/02/xaudio2-and-windows-8-consumer-preview.aspx
-
-   1. Windows' thread synchronization function, CreateSemaphore, was removed
-      from WinRT.  SDL's semaphore API was substituted instead.
-   2. The method calls, IXAudio2::GetDeviceCount and IXAudio2::GetDeviceDetails
-      were removed from the XAudio2 API.  Microsoft is telling developers to
-      use APIs in Windows::Foundation instead.
-      For SDL, the missing methods were reimplemented using the APIs Microsoft
-      said to use.
-   3. CoInitialize and CoUninitialize are not available in WinRT.
-      These calls were removed, as COM will have been initialized earlier,
-      at least by the call to the WinRT app's main function
-      (aka 'int main(Platform::Array<Platform::String^>^)).  (DLudwig:
-      This was my understanding of how WinRT: the 'main' function uses
-      a tag of [MTAThread], which should initialize COM.  My understanding
-      of COM is somewhat limited, and I may be incorrect here.)
-   4. IXAudio2::CreateMasteringVoice changed its integer-based 'DeviceIndex'
-      argument to a string-based one, 'szDeviceId'.  In WinRT, the
-      string-based argument will be used.
-*/
-
-#include "SDL_config.h"
-
-#if SDL_AUDIO_DRIVER_XAUDIO2
-
-#include "../../core/windows/SDL_windows.h"
-#include "SDL_audio.h"
-#include "../SDL_audio_c.h"
-#include "../SDL_sysaudio.h"
-#include "SDL_assert.h"
-
-#ifdef __GNUC__
-/* The configure script already did any necessary checking */
-#  define SDL_XAUDIO2_HAS_SDK 1
-#elif defined(__WINRT__)
-/* WinRT always has access to the .the XAudio 2 SDK */
-#  define SDL_XAUDIO2_HAS_SDK
-#else
-/* XAudio2 exists as of the March 2008 DirectX SDK 
-   The XAudio2 implementation available in the Windows 8 SDK targets Windows 8 and newer.
-   If you want to build SDL with XAudio2 support you should install the DirectX SDK.
- */
-#include <dxsdkver.h>
-#if (!defined(_DXSDK_BUILD_MAJOR) || (_DXSDK_BUILD_MAJOR < 1284))
-#  pragma message("Your DirectX SDK is too old. Disabling XAudio2 support.")
-#else
-#  define SDL_XAUDIO2_HAS_SDK 1
-#endif
-#endif
-
-#ifdef SDL_XAUDIO2_HAS_SDK
-
-/* Check to see if we're compiling for XAudio 2.8, or higher. */
-#ifdef WINVER
-#if WINVER >= 0x0602  /* Windows 8 SDK or higher? */
-#define SDL_XAUDIO2_WIN8 1
-#endif
-#endif
-
-/* The XAudio header file, when #include'd on WinRT, will only compile in C++
-   files, but not C.  A few preprocessor-based hacks are defined below in order
-   to get xaudio2.h to compile in the C/non-C++ file, SDL_xaudio2.c.
- */
-#ifdef __WINRT__
-#define uuid(x)
-#define DX_BUILD
-#endif
-
-#define INITGUID 1
-#include <xaudio2.h>
-
-/* Hidden "this" pointer for the audio functions */
-#define _THIS   SDL_AudioDevice *this
-
-#ifdef __WINRT__
-#include "SDL_xaudio2_winrthelpers.h"
-#endif
-
-/* Fixes bug 1210 where some versions of gcc need named parameters */
-#ifdef __GNUC__
-#ifdef THIS
-#undef THIS
-#endif
-#define THIS    INTERFACE *p
-#ifdef THIS_
-#undef THIS_
-#endif
-#define THIS_   INTERFACE *p,
-#endif
-
-struct SDL_PrivateAudioData
-{
-    IXAudio2 *ixa2;
-    IXAudio2SourceVoice *source;
-    IXAudio2MasteringVoice *mastering;
-    SDL_sem * semaphore;
-    Uint8 *mixbuf;
-    int mixlen;
-    Uint8 *nextbuf;
-};
-
-
-static void
-XAUDIO2_DetectDevices(int iscapture, SDL_AddAudioDevice addfn)
-{
-    IXAudio2 *ixa2 = NULL;
-    UINT32 devcount = 0;
-    UINT32 i = 0;
-
-    if (iscapture) {
-        SDL_SetError("XAudio2: capture devices unsupported.");
-        return;
-    } else if (XAudio2Create(&ixa2, 0, XAUDIO2_DEFAULT_PROCESSOR) != S_OK) {
-        SDL_SetError("XAudio2: XAudio2Create() failed at detection.");
-        return;
-    } else if (IXAudio2_GetDeviceCount(ixa2, &devcount) != S_OK) {
-        SDL_SetError("XAudio2: IXAudio2::GetDeviceCount() failed.");
-        IXAudio2_Release(ixa2);
-        return;
-    }
-
-    for (i = 0; i < devcount; i++) {
-        XAUDIO2_DEVICE_DETAILS details;
-        if (IXAudio2_GetDeviceDetails(ixa2, i, &details) == S_OK) {
-            char *str = WIN_StringToUTF8(details.DisplayName);
-            if (str != NULL) {
-                addfn(str);
-                SDL_free(str);  /* addfn() made a copy of the string. */
-            }
-        }
-    }
-
-    IXAudio2_Release(ixa2);
-}
-
-static void STDMETHODCALLTYPE
-VoiceCBOnBufferEnd(THIS_ void *data)
-{
-    /* Just signal the SDL audio thread and get out of XAudio2's way. */
-    SDL_AudioDevice *this = (SDL_AudioDevice *) data;
-    SDL_SemPost(this->hidden->semaphore);
-}
-
-static void STDMETHODCALLTYPE
-VoiceCBOnVoiceError(THIS_ void *data, HRESULT Error)
-{
-    /* !!! FIXME: attempt to recover, or mark device disconnected. */
-    SDL_assert(0 && "write me!");
-}
-
-/* no-op callbacks... */
-static void STDMETHODCALLTYPE VoiceCBOnStreamEnd(THIS) {}
-static void STDMETHODCALLTYPE VoiceCBOnVoiceProcessPassStart(THIS_ UINT32 b) {}
-static void STDMETHODCALLTYPE VoiceCBOnVoiceProcessPassEnd(THIS) {}
-static void STDMETHODCALLTYPE VoiceCBOnBufferStart(THIS_ void *data) {}
-static void STDMETHODCALLTYPE VoiceCBOnLoopEnd(THIS_ void *data) {}
-
-
-static Uint8 *
-XAUDIO2_GetDeviceBuf(_THIS)
-{
-    return this->hidden->nextbuf;
-}
-
-static void
-XAUDIO2_PlayDevice(_THIS)
-{
-    XAUDIO2_BUFFER buffer;
-    Uint8 *mixbuf = this->hidden->mixbuf;
-    Uint8 *nextbuf = this->hidden->nextbuf;
-    const int mixlen = this->hidden->mixlen;
-    IXAudio2SourceVoice *source = this->hidden->source;
-    HRESULT result = S_OK;
-
-    if (!this->enabled) { /* shutting down? */
-        return;
-    }
-
-    /* Submit the next filled buffer */
-    SDL_zero(buffer);
-    buffer.AudioBytes = mixlen;
-    buffer.pAudioData = nextbuf;
-    buffer.pContext = this;
-
-    if (nextbuf == mixbuf) {
-        nextbuf += mixlen;
-    } else {
-        nextbuf = mixbuf;
-    }
-    this->hidden->nextbuf = nextbuf;
-
-    result = IXAudio2SourceVoice_SubmitSourceBuffer(source, &buffer, NULL);
-    if (result == XAUDIO2_E_DEVICE_INVALIDATED) {
-        /* !!! FIXME: possibly disconnected or temporary lost. Recover? */
-    }
-
-    if (result != S_OK) {  /* uhoh, panic! */
-        IXAudio2SourceVoice_FlushSourceBuffers(source);
-        this->enabled = 0;
-    }
-}
-
-static void
-XAUDIO2_WaitDevice(_THIS)
-{
-    if (this->enabled) {
-        SDL_SemWait(this->hidden->semaphore);
-    }
-}
-
-static void
-XAUDIO2_WaitDone(_THIS)
-{
-    IXAudio2SourceVoice *source = this->hidden->source;
-    XAUDIO2_VOICE_STATE state;
-    SDL_assert(!this->enabled);  /* flag that stops playing. */
-    IXAudio2SourceVoice_Discontinuity(source);
-#if SDL_XAUDIO2_WIN8
-    IXAudio2SourceVoice_GetState(source, &state, 0);
-#else
-    IXAudio2SourceVoice_GetState(source, &state);
-#endif
-    while (state.BuffersQueued > 0) {
-        SDL_SemWait(this->hidden->semaphore);
-#if SDL_XAUDIO2_WIN8
-        IXAudio2SourceVoice_GetState(source, &state, 0);
-#else
-        IXAudio2SourceVoice_GetState(source, &state);
-#endif
-    }
-}
-
-
-static void
-XAUDIO2_CloseDevice(_THIS)
-{
-    if (this->hidden != NULL) {
-        IXAudio2 *ixa2 = this->hidden->ixa2;
-        IXAudio2SourceVoice *source = this->hidden->source;
-        IXAudio2MasteringVoice *mastering = this->hidden->mastering;
-
-        if (source != NULL) {
-            IXAudio2SourceVoice_Stop(source, 0, XAUDIO2_COMMIT_NOW);
-            IXAudio2SourceVoice_FlushSourceBuffers(source);
-            IXAudio2SourceVoice_DestroyVoice(source);
-        }
-        if (ixa2 != NULL) {
-            IXAudio2_StopEngine(ixa2);
-        }
-        if (mastering != NULL) {
-            IXAudio2MasteringVoice_DestroyVoice(mastering);
-        }
-        if (ixa2 != NULL) {
-            IXAudio2_Release(ixa2);
-        }
-        SDL_free(this->hidden->mixbuf);
-        if (this->hidden->semaphore != NULL) {
-            SDL_DestroySemaphore(this->hidden->semaphore);
-        }
-
-        SDL_free(this->hidden);
-        this->hidden = NULL;
-    }
-}
-
-static int
-XAUDIO2_OpenDevice(_THIS, const char *devname, int iscapture)
-{
-    HRESULT result = S_OK;
-    WAVEFORMATEX waveformat;
-    int valid_format = 0;
-    SDL_AudioFormat test_format = SDL_FirstAudioFormat(this->spec.format);
-    IXAudio2 *ixa2 = NULL;
-    IXAudio2SourceVoice *source = NULL;
-#if defined(SDL_XAUDIO2_WIN8)
-    LPCWSTR devId = NULL;
-#else
-    UINT32 devId = 0;  /* 0 == system default device. */
-#endif
-
-    static IXAudio2VoiceCallbackVtbl callbacks_vtable = {
-        VoiceCBOnVoiceProcessPassStart,
-        VoiceCBOnVoiceProcessPassEnd,
-        VoiceCBOnStreamEnd,
-        VoiceCBOnBufferStart,
-        VoiceCBOnBufferEnd,
-        VoiceCBOnLoopEnd,
-        VoiceCBOnVoiceError
-    };
-
-    static IXAudio2VoiceCallback callbacks = { &callbacks_vtable };
-
-    if (iscapture) {
-        return SDL_SetError("XAudio2: capture devices unsupported.");
-    } else if (XAudio2Create(&ixa2, 0, XAUDIO2_DEFAULT_PROCESSOR) != S_OK) {
-        return SDL_SetError("XAudio2: XAudio2Create() failed at open.");
-    }
-
-    /*
-    XAUDIO2_DEBUG_CONFIGURATION debugConfig;
-    debugConfig.TraceMask = XAUDIO2_LOG_ERRORS; //XAUDIO2_LOG_WARNINGS | XAUDIO2_LOG_DETAIL | XAUDIO2_LOG_FUNC_CALLS | XAUDIO2_LOG_TIMING | XAUDIO2_LOG_LOCKS | XAUDIO2_LOG_MEMORY | XAUDIO2_LOG_STREAMING;
-    debugConfig.BreakMask = XAUDIO2_LOG_ERRORS; //XAUDIO2_LOG_WARNINGS;
-    debugConfig.LogThreadID = TRUE;
-    debugConfig.LogFileline = TRUE;
-    debugConfig.LogFunctionName = TRUE;
-    debugConfig.LogTiming = TRUE;
-    ixa2->SetDebugConfiguration(&debugConfig);
-    */
-
-#if ! defined(__WINRT__)
-    if (devname != NULL) {
-        UINT32 devcount = 0;
-        UINT32 i = 0;
-
-        if (IXAudio2_GetDeviceCount(ixa2, &devcount) != S_OK) {
-            IXAudio2_Release(ixa2);
-            return SDL_SetError("XAudio2: IXAudio2_GetDeviceCount() failed.");
-        }
-        for (i = 0; i < devcount; i++) {
-            XAUDIO2_DEVICE_DETAILS details;
-            if (IXAudio2_GetDeviceDetails(ixa2, i, &details) == S_OK) {
-                char *str = WIN_StringToUTF8(details.DisplayName);
-                if (str != NULL) {
-                    const int match = (SDL_strcmp(str, devname) == 0);
-                    SDL_free(str);
-                    if (match) {
-                        devId = i;
-                        break;
-                    }
-                }
-            }
-        }
-
-        if (i == devcount) {
-            IXAudio2_Release(ixa2);
-            return SDL_SetError("XAudio2: Requested device not found.");
-        }
-    }
-#endif
-
-    /* Initialize all variables that we clean on shutdown */
-    this->hidden = (struct SDL_PrivateAudioData *)
-        SDL_malloc((sizeof *this->hidden));
-    if (this->hidden == NULL) {
-        IXAudio2_Release(ixa2);
-        return SDL_OutOfMemory();
-    }
-    SDL_memset(this->hidden, 0, (sizeof *this->hidden));
-
-    this->hidden->ixa2 = ixa2;
-    this->hidden->semaphore = SDL_CreateSemaphore(1);
-    if (this->hidden->semaphore == NULL) {
-        XAUDIO2_CloseDevice(this);
-        return SDL_SetError("XAudio2: CreateSemaphore() failed!");
-    }
-
-    while ((!valid_format) && (test_format)) {
-        switch (test_format) {
-        case AUDIO_U8:
-        case AUDIO_S16:
-        case AUDIO_S32:
-        case AUDIO_F32:
-            this->spec.format = test_format;
-            valid_format = 1;
-            break;
-        }
-        test_format = SDL_NextAudioFormat();
-    }
-
-    if (!valid_format) {
-        XAUDIO2_CloseDevice(this);
-        return SDL_SetError("XAudio2: Unsupported audio format");
-    }
-
-    /* Update the fragment size as size in bytes */
-    SDL_CalculateAudioSpec(&this->spec);
-
-    /* We feed a Source, it feeds the Mastering, which feeds the device. */
-    this->hidden->mixlen = this->spec.size;
-    this->hidden->mixbuf = (Uint8 *) SDL_malloc(2 * this->hidden->mixlen);
-    if (this->hidden->mixbuf == NULL) {
-        XAUDIO2_CloseDevice(this);
-        return SDL_OutOfMemory();
-    }
-    this->hidden->nextbuf = this->hidden->mixbuf;
-    SDL_memset(this->hidden->mixbuf, 0, 2 * this->hidden->mixlen);
-
-    /* We use XAUDIO2_DEFAULT_CHANNELS instead of this->spec.channels. On
-       Xbox360, this means 5.1 output, but on Windows, it means "figure out
-       what the system has." It might be preferable to let XAudio2 blast
-       stereo output to appropriate surround sound configurations
-       instead of clamping to 2 channels, even though we'll configure the
-       Source Voice for whatever number of channels you supply. */
-#if SDL_XAUDIO2_WIN8
-    result = IXAudio2_CreateMasteringVoice(ixa2, &this->hidden->mastering,
-                                           XAUDIO2_DEFAULT_CHANNELS,
-                                           this->spec.freq, 0, devId, NULL, AudioCategory_GameEffects);
-#else
-    result = IXAudio2_CreateMasteringVoice(ixa2, &this->hidden->mastering,
-                                           XAUDIO2_DEFAULT_CHANNELS,
-                                           this->spec.freq, 0, devId, NULL);
-#endif
-    if (result != S_OK) {
-        XAUDIO2_CloseDevice(this);
-        return SDL_SetError("XAudio2: Couldn't create mastering voice");
-    }
-
-    SDL_zero(waveformat);
-    if (SDL_AUDIO_ISFLOAT(this->spec.format)) {
-        waveformat.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
-    } else {
-        waveformat.wFormatTag = WAVE_FORMAT_PCM;
-    }
-    waveformat.wBitsPerSample = SDL_AUDIO_BITSIZE(this->spec.format);
-    waveformat.nChannels = this->spec.channels;
-    waveformat.nSamplesPerSec = this->spec.freq;
-    waveformat.nBlockAlign =
-        waveformat.nChannels * (waveformat.wBitsPerSample / 8);
-    waveformat.nAvgBytesPerSec =
-        waveformat.nSamplesPerSec * waveformat.nBlockAlign;
-    waveformat.cbSize = sizeof(waveformat);
-
-#ifdef __WINRT__
-    // DLudwig: for now, make XAudio2 do sample rate conversion, just to
-    // get the loopwave test to work.
-    //
-    // TODO, WinRT: consider removing WinRT-specific source-voice creation code from SDL_xaudio2.c
-    result = IXAudio2_CreateSourceVoice(ixa2, &source, &waveformat,
-                                        0,
-                                        1.0f, &callbacks, NULL, NULL);
-#else
-    result = IXAudio2_CreateSourceVoice(ixa2, &source, &waveformat,
-                                        XAUDIO2_VOICE_NOSRC |
-                                        XAUDIO2_VOICE_NOPITCH,
-                                        1.0f, &callbacks, NULL, NULL);
-
-#endif
-    if (result != S_OK) {
-        XAUDIO2_CloseDevice(this);
-        return SDL_SetError("XAudio2: Couldn't create source voice");
-    }
-    this->hidden->source = source;
-
-    /* Start everything playing! */
-    result = IXAudio2_StartEngine(ixa2);
-    if (result != S_OK) {
-        XAUDIO2_CloseDevice(this);
-        return SDL_SetError("XAudio2: Couldn't start engine");
-    }
-
-    result = IXAudio2SourceVoice_Start(source, 0, XAUDIO2_COMMIT_NOW);
-    if (result != S_OK) {
-        XAUDIO2_CloseDevice(this);
-        return SDL_SetError("XAudio2: Couldn't start source voice");
-    }
-
-    return 0; /* good to go. */
-}
-
-static void
-XAUDIO2_Deinitialize(void)
-{
-#if defined(__WIN32__)
-    WIN_CoUninitialize();
-#endif
-}
-
-#endif  /* SDL_XAUDIO2_HAS_SDK */
-
-
-static int
-XAUDIO2_Init(SDL_AudioDriverImpl * impl)
-{
-#ifndef SDL_XAUDIO2_HAS_SDK
-    SDL_SetError("XAudio2: SDL was built without XAudio2 support (old DirectX SDK).");
-    return 0;  /* no XAudio2 support, ever. Update your SDK! */
-#else
-    /* XAudio2Create() is a macro that uses COM; we don't load the .dll */
-    IXAudio2 *ixa2 = NULL;
-#if defined(__WIN32__)
-    // TODO, WinRT: Investigate using CoInitializeEx here
-    if (FAILED(WIN_CoInitialize())) {
-        SDL_SetError("XAudio2: CoInitialize() failed");
-        return 0;
-    }
-#endif
-
-    if (XAudio2Create(&ixa2, 0, XAUDIO2_DEFAULT_PROCESSOR) != S_OK) {
-#if defined(__WIN32__)
-        WIN_CoUninitialize();
-#endif
-        SDL_SetError("XAudio2: XAudio2Create() failed at initialization");
-        return 0;  /* not available. */
-    }
-    IXAudio2_Release(ixa2);
-
-    /* Set the function pointers */
-    impl->DetectDevices = XAUDIO2_DetectDevices;
-    impl->OpenDevice = XAUDIO2_OpenDevice;
-    impl->PlayDevice = XAUDIO2_PlayDevice;
-    impl->WaitDevice = XAUDIO2_WaitDevice;
-    impl->WaitDone = XAUDIO2_WaitDone;
-    impl->GetDeviceBuf = XAUDIO2_GetDeviceBuf;
-    impl->CloseDevice = XAUDIO2_CloseDevice;
-    impl->Deinitialize = XAUDIO2_Deinitialize;
-
-    return 1;   /* this audio target is available. */
-#endif
-}
-
-AudioBootStrap XAUDIO2_bootstrap = {
-    "xaudio2", "XAudio2", XAUDIO2_Init, 0
-};
-
-#endif  /* SDL_AUDIO_DRIVER_XAUDIO2 */
-
-/* vi: set ts=4 sw=4 expandtab: */
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2013 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.
+*/
+
+/* WinRT NOTICE:
+
+   A few changes to SDL's XAudio2 backend were warranted by API
+   changes to Windows.  Many, but not all of these are documented by Microsoft
+   at:
+   http://blogs.msdn.com/b/chuckw/archive/2012/04/02/xaudio2-and-windows-8-consumer-preview.aspx
+
+   1. Windows' thread synchronization function, CreateSemaphore, was removed
+      from WinRT.  SDL's semaphore API was substituted instead.
+   2. The method calls, IXAudio2::GetDeviceCount and IXAudio2::GetDeviceDetails
+      were removed from the XAudio2 API.  Microsoft is telling developers to
+      use APIs in Windows::Foundation instead.
+      For SDL, the missing methods were reimplemented using the APIs Microsoft
+      said to use.
+   3. CoInitialize and CoUninitialize are not available in WinRT.
+      These calls were removed, as COM will have been initialized earlier,
+      at least by the call to the WinRT app's main function
+      (aka 'int main(Platform::Array<Platform::String^>^)).  (DLudwig:
+      This was my understanding of how WinRT: the 'main' function uses
+      a tag of [MTAThread], which should initialize COM.  My understanding
+      of COM is somewhat limited, and I may be incorrect here.)
+   4. IXAudio2::CreateMasteringVoice changed its integer-based 'DeviceIndex'
+      argument to a string-based one, 'szDeviceId'.  In WinRT, the
+      string-based argument will be used.
+*/
+
+#include "SDL_config.h"
+
+#if SDL_AUDIO_DRIVER_XAUDIO2
+
+#include "../../core/windows/SDL_windows.h"
+#include "SDL_audio.h"
+#include "../SDL_audio_c.h"
+#include "../SDL_sysaudio.h"
+#include "SDL_assert.h"
+
+#ifdef __GNUC__
+/* The configure script already did any necessary checking */
+#  define SDL_XAUDIO2_HAS_SDK 1
+#elif defined(__WINRT__)
+/* WinRT always has access to the .the XAudio 2 SDK */
+#  define SDL_XAUDIO2_HAS_SDK
+#else
+/* XAudio2 exists as of the March 2008 DirectX SDK 
+   The XAudio2 implementation available in the Windows 8 SDK targets Windows 8 and newer.
+   If you want to build SDL with XAudio2 support you should install the DirectX SDK.
+ */
+#include <dxsdkver.h>
+#if (!defined(_DXSDK_BUILD_MAJOR) || (_DXSDK_BUILD_MAJOR < 1284))
+#  pragma message("Your DirectX SDK is too old. Disabling XAudio2 support.")
+#else
+#  define SDL_XAUDIO2_HAS_SDK 1
+#endif
+#endif
+
+#ifdef SDL_XAUDIO2_HAS_SDK
+
+/* Check to see if we're compiling for XAudio 2.8, or higher. */
+#ifdef WINVER
+#if WINVER >= 0x0602  /* Windows 8 SDK or higher? */
+#define SDL_XAUDIO2_WIN8 1
+#endif
+#endif
+
+/* The XAudio header file, when #include'd on WinRT, will only compile in C++
+   files, but not C.  A few preprocessor-based hacks are defined below in order
+   to get xaudio2.h to compile in the C/non-C++ file, SDL_xaudio2.c.
+ */
+#ifdef __WINRT__
+#define uuid(x)
+#define DX_BUILD
+#endif
+
+#define INITGUID 1
+#include <xaudio2.h>
+
+/* Hidden "this" pointer for the audio functions */
+#define _THIS   SDL_AudioDevice *this
+
+#ifdef __WINRT__
+#include "SDL_xaudio2_winrthelpers.h"
+#endif
+
+/* Fixes bug 1210 where some versions of gcc need named parameters */
+#ifdef __GNUC__
+#ifdef THIS
+#undef THIS
+#endif
+#define THIS    INTERFACE *p
+#ifdef THIS_
+#undef THIS_
+#endif
+#define THIS_   INTERFACE *p,
+#endif
+
+struct SDL_PrivateAudioData
+{
+    IXAudio2 *ixa2;
+    IXAudio2SourceVoice *source;
+    IXAudio2MasteringVoice *mastering;
+    SDL_sem * semaphore;
+    Uint8 *mixbuf;
+    int mixlen;
+    Uint8 *nextbuf;
+};
+
+
+static void
+XAUDIO2_DetectDevices(int iscapture, SDL_AddAudioDevice addfn)
+{
+    IXAudio2 *ixa2 = NULL;
+    UINT32 devcount = 0;
+    UINT32 i = 0;
+
+    if (iscapture) {
+        SDL_SetError("XAudio2: capture devices unsupported.");
+        return;
+    } else if (XAudio2Create(&ixa2, 0, XAUDIO2_DEFAULT_PROCESSOR) != S_OK) {
+        SDL_SetError("XAudio2: XAudio2Create() failed at detection.");
+        return;
+    } else if (IXAudio2_GetDeviceCount(ixa2, &devcount) != S_OK) {
+        SDL_SetError("XAudio2: IXAudio2::GetDeviceCount() failed.");
+        IXAudio2_Release(ixa2);
+        return;
+    }
+
+    for (i = 0; i < devcount; i++) {
+        XAUDIO2_DEVICE_DETAILS details;
+        if (IXAudio2_GetDeviceDetails(ixa2, i, &details) == S_OK) {
+            char *str = WIN_StringToUTF8(details.DisplayName);
+            if (str != NULL) {
+                addfn(str);
+                SDL_free(str);  /* addfn() made a copy of the string. */
+            }
+        }
+    }
+
+    IXAudio2_Release(ixa2);
+}
+
+static void STDMETHODCALLTYPE
+VoiceCBOnBufferEnd(THIS_ void *data)
+{
+    /* Just signal the SDL audio thread and get out of XAudio2's way. */
+    SDL_AudioDevice *this = (SDL_AudioDevice *) data;
+    SDL_SemPost(this->hidden->semaphore);
+}
+
+static void STDMETHODCALLTYPE
+VoiceCBOnVoiceError(THIS_ void *data, HRESULT Error)
+{
+    /* !!! FIXME: attempt to recover, or mark device disconnected. */
+    SDL_assert(0 && "write me!");
+}
+
+/* no-op callbacks... */
+static void STDMETHODCALLTYPE VoiceCBOnStreamEnd(THIS) {}
+static void STDMETHODCALLTYPE VoiceCBOnVoiceProcessPassStart(THIS_ UINT32 b) {}
+static void STDMETHODCALLTYPE VoiceCBOnVoiceProcessPassEnd(THIS) {}
+static void STDMETHODCALLTYPE VoiceCBOnBufferStart(THIS_ void *data) {}
+static void STDMETHODCALLTYPE VoiceCBOnLoopEnd(THIS_ void *data) {}
+
+
+static Uint8 *
+XAUDIO2_GetDeviceBuf(_THIS)
+{
+    return this->hidden->nextbuf;
+}
+
+static void
+XAUDIO2_PlayDevice(_THIS)
+{
+    XAUDIO2_BUFFER buffer;
+    Uint8 *mixbuf = this->hidden->mixbuf;
+    Uint8 *nextbuf = this->hidden->nextbuf;
+    const int mixlen = this->hidden->mixlen;
+    IXAudio2SourceVoice *source = this->hidden->source;
+    HRESULT result = S_OK;
+
+    if (!this->enabled) { /* shutting down? */
+        return;
+    }
+
+    /* Submit the next filled buffer */
+    SDL_zero(buffer);
+    buffer.AudioBytes = mixlen;
+    buffer.pAudioData = nextbuf;
+    buffer.pContext = this;
+
+    if (nextbuf == mixbuf) {
+        nextbuf += mixlen;
+    } else {
+        nextbuf = mixbuf;
+    }
+    this->hidden->nextbuf = nextbuf;
+
+    result = IXAudio2SourceVoice_SubmitSourceBuffer(source, &buffer, NULL);
+    if (result == XAUDIO2_E_DEVICE_INVALIDATED) {
+        /* !!! FIXME: possibly disconnected or temporary lost. Recover? */
+    }
+
+    if (result != S_OK) {  /* uhoh, panic! */
+        IXAudio2SourceVoice_FlushSourceBuffers(source);
+        this->enabled = 0;
+    }
+}
+
+static void
+XAUDIO2_WaitDevice(_THIS)
+{
+    if (this->enabled) {
+        SDL_SemWait(this->hidden->semaphore);
+    }
+}
+
+static void
+XAUDIO2_WaitDone(_THIS)
+{
+    IXAudio2SourceVoice *source = this->hidden->source;
+    XAUDIO2_VOICE_STATE state;
+    SDL_assert(!this->enabled);  /* flag that stops playing. */
+    IXAudio2SourceVoice_Discontinuity(source);
+#if SDL_XAUDIO2_WIN8
+    IXAudio2SourceVoice_GetState(source, &state, 0);
+#else
+    IXAudio2SourceVoice_GetState(source, &state);
+#endif
+    while (state.BuffersQueued > 0) {
+        SDL_SemWait(this->hidden->semaphore);
+#if SDL_XAUDIO2_WIN8
+        IXAudio2SourceVoice_GetState(source, &state, 0);
+#else
+        IXAudio2SourceVoice_GetState(source, &state);
+#endif
+    }
+}
+
+
+static void
+XAUDIO2_CloseDevice(_THIS)
+{
+    if (this->hidden != NULL) {
+        IXAudio2 *ixa2 = this->hidden->ixa2;
+        IXAudio2SourceVoice *source = this->hidden->source;
+        IXAudio2MasteringVoice *mastering = this->hidden->mastering;
+
+        if (source != NULL) {
+            IXAudio2SourceVoice_Stop(source, 0, XAUDIO2_COMMIT_NOW);
+            IXAudio2SourceVoice_FlushSourceBuffers(source);
+            IXAudio2SourceVoice_DestroyVoice(source);
+        }
+        if (ixa2 != NULL) {
+            IXAudio2_StopEngine(ixa2);
+        }
+        if (mastering != NULL) {
+            IXAudio2MasteringVoice_DestroyVoice(mastering);
+        }
+        if (ixa2 != NULL) {
+            IXAudio2_Release(ixa2);
+        }
+        SDL_free(this->hidden->mixbuf);
+        if (this->hidden->semaphore != NULL) {
+            SDL_DestroySemaphore(this->hidden->semaphore);
+        }
+
+        SDL_free(this->hidden);
+        this->hidden = NULL;
+    }
+}
+
+static int
+XAUDIO2_OpenDevice(_THIS, const char *devname, int iscapture)
+{
+    HRESULT result = S_OK;
+    WAVEFORMATEX waveformat;
+    int valid_format = 0;
+    SDL_AudioFormat test_format = SDL_FirstAudioFormat(this->spec.format);
+    IXAudio2 *ixa2 = NULL;
+    IXAudio2SourceVoice *source = NULL;
+#if defined(SDL_XAUDIO2_WIN8)
+    LPCWSTR devId = NULL;
+#else
+    UINT32 devId = 0;  /* 0 == system default device. */
+#endif
+
+    static IXAudio2VoiceCallbackVtbl callbacks_vtable = {
+        VoiceCBOnVoiceProcessPassStart,
+        VoiceCBOnVoiceProcessPassEnd,
+        VoiceCBOnStreamEnd,
+        VoiceCBOnBufferStart,
+        VoiceCBOnBufferEnd,
+        VoiceCBOnLoopEnd,
+        VoiceCBOnVoiceError
+    };
+
+    static IXAudio2VoiceCallback callbacks = { &callbacks_vtable };
+
+    if (iscapture) {
+        return SDL_SetError("XAudio2: capture devices unsupported.");
+    } else if (XAudio2Create(&ixa2, 0, XAUDIO2_DEFAULT_PROCESSOR) != S_OK) {
+        return SDL_SetError("XAudio2: XAudio2Create() failed at open.");
+    }
+
+    /*
+    XAUDIO2_DEBUG_CONFIGURATION debugConfig;
+    debugConfig.TraceMask = XAUDIO2_LOG_ERRORS; //XAUDIO2_LOG_WARNINGS | XAUDIO2_LOG_DETAIL | XAUDIO2_LOG_FUNC_CALLS | XAUDIO2_LOG_TIMING | XAUDIO2_LOG_LOCKS | XAUDIO2_LOG_MEMORY | XAUDIO2_LOG_STREAMING;
+    debugConfig.BreakMask = XAUDIO2_LOG_ERRORS; //XAUDIO2_LOG_WARNINGS;
+    debugConfig.LogThreadID = TRUE;
+    debugConfig.LogFileline = TRUE;
+    debugConfig.LogFunctionName = TRUE;
+    debugConfig.LogTiming = TRUE;
+    ixa2->SetDebugConfiguration(&debugConfig);
+    */
+
+#if ! defined(__WINRT__)
+    if (devname != NULL) {
+        UINT32 devcount = 0;
+        UINT32 i = 0;
+
+        if (IXAudio2_GetDeviceCount(ixa2, &devcount) != S_OK) {
+            IXAudio2_Release(ixa2);
+            return SDL_SetError("XAudio2: IXAudio2_GetDeviceCount() failed.");
+        }
+        for (i = 0; i < devcount; i++) {
+            XAUDIO2_DEVICE_DETAILS details;
+            if (IXAudio2_GetDeviceDetails(ixa2, i, &details) == S_OK) {
+                char *str = WIN_StringToUTF8(details.DisplayName);
+                if (str != NULL) {
+                    const int match = (SDL_strcmp(str, devname) == 0);
+                    SDL_free(str);
+                    if (match) {
+                        devId = i;
+                        break;
+                    }
+                }
+            }
+        }
+
+        if (i == devcount) {
+            IXAudio2_Release(ixa2);
+            return SDL_SetError("XAudio2: Requested device not found.");
+        }
+    }
+#endif
+
+    /* Initialize all variables that we clean on shutdown */
+    this->hidden = (struct SDL_PrivateAudioData *)
+        SDL_malloc((sizeof *this->hidden));
+    if (this->hidden == NULL) {
+        IXAudio2_Release(ixa2);
+        return SDL_OutOfMemory();
+    }
+    SDL_memset(this->hidden, 0, (sizeof *this->hidden));
+
+    this->hidden->ixa2 = ixa2;
+    this->hidden->semaphore = SDL_CreateSemaphore(1);
+    if (this->hidden->semaphore == NULL) {
+        XAUDIO2_CloseDevice(this);
+        return SDL_SetError("XAudio2: CreateSemaphore() failed!");
+    }
+
+    while ((!valid_format) && (test_format)) {
+        switch (test_format) {
+        case AUDIO_U8:
+        case AUDIO_S16:
+        case AUDIO_S32:
+        case AUDIO_F32:
+            this->spec.format = test_format;
+            valid_format = 1;
+            break;
+        }
+        test_format = SDL_NextAudioFormat();
+    }
+
+    if (!valid_format) {
+        XAUDIO2_CloseDevice(this);
+        return SDL_SetError("XAudio2: Unsupported audio format");
+    }
+
+    /* Update the fragment size as size in bytes */
+    SDL_CalculateAudioSpec(&this->spec);
+
+    /* We feed a Source, it feeds the Mastering, which feeds the device. */
+    this->hidden->mixlen = this->spec.size;
+    this->hidden->mixbuf = (Uint8 *) SDL_malloc(2 * this->hidden->mixlen);
+    if (this->hidden->mixbuf == NULL) {
+        XAUDIO2_CloseDevice(this);
+        return SDL_OutOfMemory();
+    }
+    this->hidden->nextbuf = this->hidden->mixbuf;
+    SDL_memset(this->hidden->mixbuf, 0, 2 * this->hidden->mixlen);
+
+    /* We use XAUDIO2_DEFAULT_CHANNELS instead of this->spec.channels. On
+       Xbox360, this means 5.1 output, but on Windows, it means "figure out
+       what the system has." It might be preferable to let XAudio2 blast
+       stereo output to appropriate surround sound configurations
+       instead of clamping to 2 channels, even though we'll configure the
+       Source Voice for whatever number of channels you supply. */
+#if SDL_XAUDIO2_WIN8
+    result = IXAudio2_CreateMasteringVoice(ixa2, &this->hidden->mastering,
+                                           XAUDIO2_DEFAULT_CHANNELS,
+                                           this->spec.freq, 0, devId, NULL, AudioCategory_GameEffects);
+#else
+    result = IXAudio2_CreateMasteringVoice(ixa2, &this->hidden->mastering,
+                                           XAUDIO2_DEFAULT_CHANNELS,
+                                           this->spec.freq, 0, devId, NULL);
+#endif
+    if (result != S_OK) {
+        XAUDIO2_CloseDevice(this);
+        return SDL_SetError("XAudio2: Couldn't create mastering voice");
+    }
+
+    SDL_zero(waveformat);
+    if (SDL_AUDIO_ISFLOAT(this->spec.format)) {
+        waveformat.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
+    } else {
+        waveformat.wFormatTag = WAVE_FORMAT_PCM;
+    }
+    waveformat.wBitsPerSample = SDL_AUDIO_BITSIZE(this->spec.format);
+    waveformat.nChannels = this->spec.channels;
+    waveformat.nSamplesPerSec = this->spec.freq;
+    waveformat.nBlockAlign =
+        waveformat.nChannels * (waveformat.wBitsPerSample / 8);
+    waveformat.nAvgBytesPerSec =
+        waveformat.nSamplesPerSec * waveformat.nBlockAlign;
+    waveformat.cbSize = sizeof(waveformat);
+
+#ifdef __WINRT__
+    // DLudwig: for now, make XAudio2 do sample rate conversion, just to
+    // get the loopwave test to work.
+    //
+    // TODO, WinRT: consider removing WinRT-specific source-voice creation code from SDL_xaudio2.c
+    result = IXAudio2_CreateSourceVoice(ixa2, &source, &waveformat,
+                                        0,
+                                        1.0f, &callbacks, NULL, NULL);
+#else
+    result = IXAudio2_CreateSourceVoice(ixa2, &source, &waveformat,
+                                        XAUDIO2_VOICE_NOSRC |
+                                        XAUDIO2_VOICE_NOPITCH,
+                                        1.0f, &callbacks, NULL, NULL);
+
+#endif
+    if (result != S_OK) {
+        XAUDIO2_CloseDevice(this);
+        return SDL_SetError("XAudio2: Couldn't create source voice");
+    }
+    this->hidden->source = source;
+
+    /* Start everything playing! */
+    result = IXAudio2_StartEngine(ixa2);
+    if (result != S_OK) {
+        XAUDIO2_CloseDevice(this);
+        return SDL_SetError("XAudio2: Couldn't start engine");
+    }
+
+    result = IXAudio2SourceVoice_Start(source, 0, XAUDIO2_COMMIT_NOW);
+    if (result != S_OK) {
+        XAUDIO2_CloseDevice(this);
+        return SDL_SetError("XAudio2: Couldn't start source voice");
+    }
+
+    return 0; /* good to go. */
+}
+
+static void
+XAUDIO2_Deinitialize(void)
+{
+#if defined(__WIN32__)
+    WIN_CoUninitialize();
+#endif
+}
+
+#endif  /* SDL_XAUDIO2_HAS_SDK */
+
+
+static int
+XAUDIO2_Init(SDL_AudioDriverImpl * impl)
+{
+#ifndef SDL_XAUDIO2_HAS_SDK
+    SDL_SetError("XAudio2: SDL was built without XAudio2 support (old DirectX SDK).");
+    return 0;  /* no XAudio2 support, ever. Update your SDK! */
+#else
+    /* XAudio2Create() is a macro that uses COM; we don't load the .dll */
+    IXAudio2 *ixa2 = NULL;
+#if defined(__WIN32__)
+    // TODO, WinRT: Investigate using CoInitializeEx here
+    if (FAILED(WIN_CoInitialize())) {
+        SDL_SetError("XAudio2: CoInitialize() failed");
+        return 0;
+    }
+#endif
+
+    if (XAudio2Create(&ixa2, 0, XAUDIO2_DEFAULT_PROCESSOR) != S_OK) {
+#if defined(__WIN32__)
+        WIN_CoUninitialize();
+#endif
+        SDL_SetError("XAudio2: XAudio2Create() failed at initialization");
+        return 0;  /* not available. */
+    }
+    IXAudio2_Release(ixa2);
+
+    /* Set the function pointers */
+    impl->DetectDevices = XAUDIO2_DetectDevices;
+    impl->OpenDevice = XAUDIO2_OpenDevice;
+    impl->PlayDevice = XAUDIO2_PlayDevice;
+    impl->WaitDevice = XAUDIO2_WaitDevice;
+    impl->WaitDone = XAUDIO2_WaitDone;
+    impl->GetDeviceBuf = XAUDIO2_GetDeviceBuf;
+    impl->CloseDevice = XAUDIO2_CloseDevice;
+    impl->Deinitialize = XAUDIO2_Deinitialize;
+
+    return 1;   /* this audio target is available. */
+#endif
+}
+
+AudioBootStrap XAUDIO2_bootstrap = {
+    "xaudio2", "XAudio2", XAUDIO2_Init, 0
+};
+
+#endif  /* SDL_AUDIO_DRIVER_XAUDIO2 */
+
+/* vi: set ts=4 sw=4 expandtab: */
--- a/src/audio/xaudio2/SDL_xaudio2_winrthelpers.cpp	Tue Mar 04 19:49:11 2014 -0500
+++ b/src/audio/xaudio2/SDL_xaudio2_winrthelpers.cpp	Sun Mar 09 11:06:11 2014 -0700
@@ -1,69 +1,69 @@
-
-#include <xaudio2.h>
-#include "SDL_xaudio2_winrthelpers.h"
-
-#if WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP
-using Windows::Devices::Enumeration::DeviceClass;
-using Windows::Devices::Enumeration::DeviceInformation;
-using Windows::Devices::Enumeration::DeviceInformationCollection;
-#endif
-
-extern "C" HRESULT __cdecl IXAudio2_GetDeviceCount(IXAudio2 * ixa2, UINT32 * devcount)
-{
-#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
-    // There doesn't seem to be any audio device enumeration on Windows Phone.
-    // In lieu of this, just treat things as if there is one and only one
-    // audio device.
-    *devcount = 1;
-    return S_OK;
-#else
-    // TODO, WinRT: make xaudio2 device enumeration only happen once, and in the background
-    auto operation = DeviceInformation::FindAllAsync(DeviceClass::AudioRender);
-    while (operation->Status != Windows::Foundation::AsyncStatus::Completed)
-    {
-    }
- 
-    DeviceInformationCollection^ devices = operation->GetResults();
-    *devcount = devices->Size;
-    return S_OK;
-#endif
-}
-
-extern "C" HRESULT IXAudio2_GetDeviceDetails(IXAudio2 * unused, UINT32 index, XAUDIO2_DEVICE_DETAILS * details)
-{
-#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
-    // Windows Phone doesn't seem to have the same device enumeration APIs that
-    // Windows 8/RT has, or it doesn't have them at all.  In lieu of this,
-    // just treat things as if there is one, and only one, default device.
-    if (index != 0)
-    {
-        return XAUDIO2_E_INVALID_CALL;
-    }
-
-    if (details)
-    {
-        wcsncpy_s(details->DeviceID, ARRAYSIZE(details->DeviceID), L"default", _TRUNCATE);
-        wcsncpy_s(details->DisplayName, ARRAYSIZE(details->DisplayName), L"default", _TRUNCATE);
-    }
-    return S_OK;
-#else
-    auto operation = DeviceInformation::FindAllAsync(DeviceClass::AudioRender);
-    while (operation->Status != Windows::Foundation::AsyncStatus::Completed)
-    {
-    }
- 
-    DeviceInformationCollection^ devices = operation->GetResults();
-    if (index >= devices->Size)
-    {
-        return XAUDIO2_E_INVALID_CALL;
-    }
-
-    DeviceInformation^ d = devices->GetAt(index);
-    if (details)
-    {
-        wcsncpy_s(details->DeviceID, ARRAYSIZE(details->DeviceID), d->Id->Data(), _TRUNCATE);
-        wcsncpy_s(details->DisplayName, ARRAYSIZE(details->DisplayName), d->Name->Data(), _TRUNCATE);
-    }
-    return S_OK;
-#endif
-}
+
+#include <xaudio2.h>
+#include "SDL_xaudio2_winrthelpers.h"
+
+#if WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP
+using Windows::Devices::Enumeration::DeviceClass;
+using Windows::Devices::Enumeration::DeviceInformation;
+using Windows::Devices::Enumeration::DeviceInformationCollection;
+#endif
+
+extern "C" HRESULT __cdecl IXAudio2_GetDeviceCount(IXAudio2 * ixa2, UINT32 * devcount)
+{
+#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
+    // There doesn't seem to be any audio device enumeration on Windows Phone.
+    // In lieu of this, just treat things as if there is one and only one
+    // audio device.
+    *devcount = 1;
+    return S_OK;
+#else
+    // TODO, WinRT: make xaudio2 device enumeration only happen once, and in the background
+    auto operation = DeviceInformation::FindAllAsync(DeviceClass::AudioRender);
+    while (operation->Status != Windows::Foundation::AsyncStatus::Completed)
+    {
+    }
+ 
+    DeviceInformationCollection^ devices = operation->GetResults();
+    *devcount = devices->Size;
+    return S_OK;
+#endif
+}
+
+extern "C" HRESULT IXAudio2_GetDeviceDetails(IXAudio2 * unused, UINT32 index, XAUDIO2_DEVICE_DETAILS * details)
+{
+#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
+    // Windows Phone doesn't seem to have the same device enumeration APIs that
+    // Windows 8/RT has, or it doesn't have them at all.  In lieu of this,
+    // just treat things as if there is one, and only one, default device.
+    if (index != 0)
+    {
+        return XAUDIO2_E_INVALID_CALL;
+    }
+
+    if (details)
+    {
+        wcsncpy_s(details->DeviceID, ARRAYSIZE(details->DeviceID), L"default", _TRUNCATE);
+        wcsncpy_s(details->DisplayName, ARRAYSIZE(details->DisplayName), L"default", _TRUNCATE);
+    }
+    return S_OK;
+#else
+    auto operation = DeviceInformation::FindAllAsync(DeviceClass::AudioRender);
+    while (operation->Status != Windows::Foundation::AsyncStatus::Completed)
+    {
+    }
+ 
+    DeviceInformationCollection^ devices = operation->GetResults();
+    if (index >= devices->Size)
+    {
+        return XAUDIO2_E_INVALID_CALL;
+    }
+
+    DeviceInformation^ d = devices->GetAt(index);
+    if (details)
+    {
+        wcsncpy_s(details->DeviceID, ARRAYSIZE(details->DeviceID), d->Id->Data(), _TRUNCATE);
+        wcsncpy_s(details->DisplayName, ARRAYSIZE(details->DisplayName), d->Name->Data(), _TRUNCATE);
+    }
+    return S_OK;
+#endif
+}
--- a/src/audio/xaudio2/SDL_xaudio2_winrthelpers.h	Tue Mar 04 19:49:11 2014 -0500
+++ b/src/audio/xaudio2/SDL_xaudio2_winrthelpers.h	Sun Mar 09 11:06:11 2014 -0700
@@ -1,52 +1,52 @@
-
-#pragma once
-
-//
-// Re-implementation of methods removed from XAudio2 (in WinRT):
-//
-
-typedef struct XAUDIO2_DEVICE_DETAILS
-{
-    WCHAR DeviceID[256];
-    WCHAR DisplayName[256];
-    /* Other fields exist in the pre-Windows 8 version of this struct, however
-       they weren't used by SDL, so they weren't added.
-    */
-} XAUDIO2_DEVICE_DETAILS;
-
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-HRESULT IXAudio2_GetDeviceCount(IXAudio2 * unused, UINT32 * devcount);
-HRESULT IXAudio2_GetDeviceDetails(IXAudio2 * unused, UINT32 index, XAUDIO2_DEVICE_DETAILS * details);
-
-#ifdef __cplusplus
-}
-#endif
-
-
-//
-// C-style macros to call XAudio2's methods in C++:
-//
-#ifdef __cplusplus
-/*
-#define IXAudio2_CreateMasteringVoice(A, B, C, D, E, F, G) (A)->CreateMasteringVoice((B), (C), (D), (E), (F), (G))
-#define IXAudio2_CreateSourceVoice(A, B, C, D, E, F, G, H) (A)->CreateSourceVoice((B), (C), (D), (E), (F), (G), (H))
-#define IXAudio2_QueryInterface(A, B, C) (A)->QueryInterface((B), (C))
-#define IXAudio2_Release(A) (A)->Release()
-#define IXAudio2_StartEngine(A) (A)->StartEngine()
-#define IXAudio2_StopEngine(A) (A)->StopEngine()
-
-#define IXAudio2MasteringVoice_DestroyVoice(A) (A)->DestroyVoice()
-
-#define IXAudio2SourceVoice_DestroyVoice(A) (A)->DestroyVoice()
-#define IXAudio2SourceVoice_Discontinuity(A) (A)->Discontinuity()
-#define IXAudio2SourceVoice_FlushSourceBuffers(A) (A)->FlushSourceBuffers()
-#define IXAudio2SourceVoice_GetState(A, B) (A)->GetState((B))
-#define IXAudio2SourceVoice_Start(A, B, C) (A)->Start((B), (C))
-#define IXAudio2SourceVoice_Stop(A, B, C) (A)->Stop((B), (C))
-#define IXAudio2SourceVoice_SubmitSourceBuffer(A, B, C) (A)->SubmitSourceBuffer((B), (C))
-*/
-#endif // ifdef __cplusplus
+
+#pragma once
+
+//
+// Re-implementation of methods removed from XAudio2 (in WinRT):
+//
+
+typedef struct XAUDIO2_DEVICE_DETAILS
+{
+    WCHAR DeviceID[256];
+    WCHAR DisplayName[256];
+    /* Other fields exist in the pre-Windows 8 version of this struct, however
+       they weren't used by SDL, so they weren't added.
+    */
+} XAUDIO2_DEVICE_DETAILS;
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+HRESULT IXAudio2_GetDeviceCount(IXAudio2 * unused, UINT32 * devcount);
+HRESULT IXAudio2_GetDeviceDetails(IXAudio2 * unused, UINT32 index, XAUDIO2_DEVICE_DETAILS * details);
+
+#ifdef __cplusplus
+}
+#endif
+
+
+//
+// C-style macros to call XAudio2's methods in C++:
+//
+#ifdef __cplusplus
+/*
+#define IXAudio2_CreateMasteringVoice(A, B, C, D, E, F, G) (A)->CreateMasteringVoice((B), (C), (D), (E), (F), (G))
+#define IXAudio2_CreateSourceVoice(A, B, C, D, E, F, G, H) (A)->CreateSourceVoice((B), (C), (D), (E), (F), (G), (H))
+#define IXAudio2_QueryInterface(A, B, C) (A)->QueryInterface((B), (C))
+#define IXAudio2_Release(A) (A)->Release()
+#define IXAudio2_StartEngine(A) (A)->StartEngine()
+#define IXAudio2_StopEngine(A) (A)->StopEngine()
+
+#define IXAudio2MasteringVoice_DestroyVoice(A) (A)->DestroyVoice()
+
+#define IXAudio2SourceVoice_DestroyVoice(A) (A)->DestroyVoice()
+#define IXAudio2SourceVoice_Discontinuity(A) (A)->Discontinuity()
+#define IXAudio2SourceVoice_FlushSourceBuffers(A) (A)->FlushSourceBuffers()
+#define IXAudio2SourceVoice_GetState(A, B) (A)->GetState((B))
+#define IXAudio2SourceVoice_Start(A, B, C) (A)->Start((B), (C))
+#define IXAudio2SourceVoice_Stop(A, B, C) (A)->Stop((B), (C))
+#define IXAudio2SourceVoice_SubmitSourceBuffer(A, B, C) (A)->SubmitSourceBuffer((B), (C))
+*/
+#endif // ifdef __cplusplus
--- a/src/core/winrt/SDL_winrtapp_common.cpp	Tue Mar 04 19:49:11 2014 -0500
+++ b/src/core/winrt/SDL_winrtapp_common.cpp	Sun Mar 09 11:06:11 2014 -0700
@@ -1,16 +1,16 @@
-
-#include <SDL_system.h>
-#include "SDL_winrtapp_direct3d.h"
-#include "SDL_winrtapp_xaml.h"
-
-int (*WINRT_SDLAppEntryPoint)(int, char **) = NULL;
-
+
+#include <SDL_system.h>
+#include "SDL_winrtapp_direct3d.h"
+#include "SDL_winrtapp_xaml.h"
+
+int (*WINRT_SDLAppEntryPoint)(int, char **) = NULL;
+
 extern "C" DECLSPEC int
-SDL_WinRTRunApp(int (*mainFunction)(int, char **), void * xamlBackgroundPanel)
-{
-    if (xamlBackgroundPanel) {
-        return SDL_WinRTInitXAMLApp(mainFunction, xamlBackgroundPanel);
-    } else {
-        return SDL_WinRTInitNonXAMLApp(mainFunction);
-    }
-}
+SDL_WinRTRunApp(int (*mainFunction)(int, char **), void * xamlBackgroundPanel)
+{
+    if (xamlBackgroundPanel) {
+        return SDL_WinRTInitXAMLApp(mainFunction, xamlBackgroundPanel);
+    } else {
+        return SDL_WinRTInitNonXAMLApp(mainFunction);
+    }
+}
--- a/src/core/winrt/SDL_winrtapp_common.h	Tue Mar 04 19:49:11 2014 -0500
+++ b/src/core/winrt/SDL_winrtapp_common.h	Sun Mar 09 11:06:11 2014 -0700
@@ -19,13 +19,13 @@
   3. This notice may not be removed or altered from any source distribution.
 */
 #include "SDL_config.h"
-
+
 #ifndef _SDL_winrtapp_common_h
-#define _SDL_winrtapp_common_h
-
-/* A pointer to the app's C-style main() function (which is a different
-   function than the WinRT app's actual entry point).
- */
-extern int (*WINRT_SDLAppEntryPoint)(int, char **);
-
-#endif // ifndef _SDL_winrtapp_common_h
+#define _SDL_winrtapp_common_h
+
+/* A pointer to the app's C-style main() function (which is a different
+   function than the WinRT app's actual entry point).
+ */
+extern int (*WINRT_SDLAppEntryPoint)(int, char **);
+
+#endif // ifndef _SDL_winrtapp_common_h
--- a/src/core/winrt/SDL_winrtapp_direct3d.cpp	Tue Mar 04 19:49:11 2014 -0500
+++ b/src/core/winrt/SDL_winrtapp_direct3d.cpp	Sun Mar 09 11:06:11 2014 -0700
@@ -1,668 +1,668 @@
-
-/* Standard C++11 includes */
-#include <functional>
-#include <string>
-#include <sstream>
-using namespace std;
-
-
-/* Windows includes */
-#include "ppltasks.h"
-using namespace concurrency;
-using namespace Windows::ApplicationModel;
-using namespace Windows::ApplicationModel::Core;
-using namespace Windows::ApplicationModel::Activation;
-using namespace Windows::Devices::Input;
-using namespace Windows::Graphics::Display;
-using namespace Windows::Foundation;
-using namespace Windows::System;
-using namespace Windows::UI::Core;
-using namespace Windows::UI::Input;
-
-#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
-using namespace Windows::Phone::UI::Input;
-#endif
-
-
-/* SDL includes */
-extern "C" {
-#include "SDL_assert.h"
-#include "SDL_events.h"
-#include "SDL_hints.h"
-#include "SDL_log.h"
-#include "SDL_main.h"
-#include "SDL_stdinc.h"
-#include "SDL_render.h"
-#include "../../video/SDL_sysvideo.h"
-//#include "../../SDL_hints_c.h"
-#include "../../events/SDL_events_c.h"
-#include "../../events/SDL_keyboard_c.h"
-#include "../../events/SDL_mouse_c.h"
-#include "../../events/SDL_windowevents_c.h"
-#include "../../render/SDL_sysrender.h"
-#include "../windows/SDL_windows.h"
-}
-
-#include "../../video/winrt/SDL_winrtevents_c.h"
-#include "../../video/winrt/SDL_winrtvideo_cpp.h"
-#include "SDL_winrtapp_common.h"
-#include "SDL_winrtapp_direct3d.h"
-
-
-// Compile-time debugging options:
-// To enable, uncomment; to disable, comment them out.
-//#define LOG_POINTER_EVENTS 1
-//#define LOG_WINDOW_EVENTS 1
-//#define LOG_ORIENTATION_EVENTS 1
-
-
-// HACK, DLudwig: record a reference to the global, WinRT 'app'/view.
-// SDL/WinRT will use this throughout its code.
-//
-// TODO, WinRT: consider replacing SDL_WinRTGlobalApp with something
-// non-global, such as something created inside
-// SDL_InitSubSystem(SDL_INIT_VIDEO), or something inside
-// SDL_CreateWindow().
-SDL_WinRTApp ^ SDL_WinRTGlobalApp = nullptr;
-
-ref class SDLApplicationSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
-{
-public:
-    virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
-};
-
-IFrameworkView^ SDLApplicationSource::CreateView()
-{
-    // TODO, WinRT: see if this function (CreateView) can ever get called
-    // more than once.  For now, just prevent it from ever assigning
-    // SDL_WinRTGlobalApp more than once.
-    SDL_assert(!SDL_WinRTGlobalApp);
-    SDL_WinRTApp ^ app = ref new SDL_WinRTApp();
-    if (!SDL_WinRTGlobalApp)
-    {
-        SDL_WinRTGlobalApp = app;
-    }
-    return app;
-}
-
-int SDL_WinRTInitNonXAMLApp(int (*mainFunction)(int, char **))
-{
-    WINRT_SDLAppEntryPoint = mainFunction;
-    auto direct3DApplicationSource = ref new SDLApplicationSource();
-    CoreApplication::Run(direct3DApplicationSource);
-    return 0;
-}
-
-static void WINRT_SetDisplayOrientationsPreference(void *userdata, const char *name, const char *oldValue, const char *newValue)
-{
-    SDL_assert(SDL_strcmp(name, SDL_HINT_ORIENTATIONS) == 0);
-
-    // Start with no orientation flags, then add each in as they're parsed
-    // from newValue.
-    unsigned int orientationFlags = 0;
-    if (newValue) {
-        std::istringstream tokenizer(newValue);
-        while (!tokenizer.eof()) {
-            std::string orientationName;
-            std::getline(tokenizer, orientationName, ' ');
-            if (orientationName == "LandscapeLeft") {
-                orientationFlags |= (unsigned int) DisplayOrientations::LandscapeFlipped;
-            } else if (orientationName == "LandscapeRight") {
-                orientationFlags |= (unsigned int) DisplayOrientations::Landscape;
-            } else if (orientationName == "Portrait") {
-                orientationFlags |= (unsigned int) DisplayOrientations::Portrait;
-            } else if (orientationName == "PortraitUpsideDown") {
-                orientationFlags |= (unsigned int) DisplayOrientations::PortraitFlipped;
-            }
-        }
-    }
-
-    // If no valid orientation flags were specified, use a reasonable set of defaults:
-    if (!orientationFlags) {
-        // TODO, WinRT: consider seeing if an app's default orientation flags can be found out via some API call(s).
-        orientationFlags = (unsigned int) ( \
-            DisplayOrientations::Landscape |
-            DisplayOrientations::LandscapeFlipped |
-            DisplayOrientations::Portrait |
-            DisplayOrientations::PortraitFlipped);
-    }
-
-    // Set the orientation/rotation preferences.  Please note that this does
-    // not constitute a 100%-certain lock of a given set of possible
-    // orientations.  According to Microsoft's documentation on WinRT [1]
-    // when a device is not capable of being rotated, Windows may ignore
-    // the orientation preferences, and stick to what the device is capable of
-    // displaying.
-    //
-    // [1] Documentation on the 'InitialRotationPreference' setting for a
-    // Windows app's manifest file describes how some orientation/rotation
-    // preferences may be ignored.  See
-    // http://msdn.microsoft.com/en-us/library/windows/apps/hh700343.aspx
-    // for details.  Microsoft's "Display orientation sample" also gives an
-    // outline of how Windows treats device rotation
-    // (http://code.msdn.microsoft.com/Display-Orientation-Sample-19a58e93).
-    DisplayProperties::AutoRotationPreferences = (DisplayOrientations) orientationFlags;
-}
-
-static void
-WINRT_ProcessWindowSizeChange()
-{
-    // Make the new window size be the one true fullscreen mode.
-    // This change was initially done, in part, to allow the Direct3D 11.1
-    // renderer to receive window-resize events as a device rotates.
-    // Before, rotating a device from landscape, to portrait, and then
-    // back to landscape would cause the Direct3D 11.1 swap buffer to
-    // not get resized appropriately.  SDL would, on the rotation from
-    // landscape to portrait, re-resize the SDL window to it's initial
-    // size (landscape).  On the subsequent rotation, SDL would drop the
-    // window-resize event as it appeared the SDL window didn't change
-    // size, and the Direct3D 11.1 renderer wouldn't resize its swap
-    // chain.
-    SDL_DisplayMode newDisplayMode;
-    if (WINRT_CalcDisplayModeUsingNativeWindow(&newDisplayMode) != 0) {
-        return;
-    }
-
-    // Make note of the old display mode, and it's old driverdata.
-    SDL_DisplayMode oldDisplayMode;
-    SDL_zero(oldDisplayMode);
-    if (WINRT_GlobalSDLVideoDevice) {
-        oldDisplayMode = WINRT_GlobalSDLVideoDevice->displays[0].desktop_mode;
-    }
-
-    // Setup the new display mode in the appropriate spots.
-    if (WINRT_GlobalSDLVideoDevice) {
-        // Make a full copy of the display mode for display_modes[0],
-        // one with with a separately malloced 'driverdata' field.
-        // SDL_VideoQuit(), if called, will attempt to free the driverdata
-        // fields in 'desktop_mode' and each entry in the 'display_modes'
-        // array.
-        if (WINRT_GlobalSDLVideoDevice->displays[0].display_modes[0].driverdata) {
-            // Free the previous mode's memory
-            SDL_free(WINRT_GlobalSDLVideoDevice->displays[0].display_modes[0].driverdata);
-            WINRT_GlobalSDLVideoDevice->displays[0].display_modes[0].driverdata = NULL;
-        }
-        if (WINRT_DuplicateDisplayMode(&(WINRT_GlobalSDLVideoDevice->displays[0].display_modes[0]), &newDisplayMode) != 0) {
-            // Uh oh, something went wrong.  A malloc call probably failed.
-            SDL_free(newDisplayMode.driverdata);
-            return;
-        }
-
-        // Install 'newDisplayMode' into 'current_mode' and 'desktop_mode'.
-        WINRT_GlobalSDLVideoDevice->displays[0].current_mode = newDisplayMode;
-        WINRT_GlobalSDLVideoDevice->displays[0].desktop_mode = newDisplayMode;
-    }
-
-    if (WINRT_GlobalSDLWindow) {
-        // Send a window-resize event to the rest of SDL, and to apps:
-        SDL_SendWindowEvent(
-            WINRT_GlobalSDLWindow,
-            SDL_WINDOWEVENT_RESIZED,
-            newDisplayMode.w,
-            newDisplayMode.h);
-
-#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
-        // HACK: On Windows Phone, make sure that orientation changes from
-        // Landscape to LandscapeFlipped, Portrait to PortraitFlipped,
-        // or vice-versa on either of those two, lead to the Direct3D renderer
-        // getting updated.
-        const DisplayOrientations oldOrientation = ((SDL_DisplayModeData *)oldDisplayMode.driverdata)->currentOrientation;
-        const DisplayOrientations newOrientation = ((SDL_DisplayModeData *)newDisplayMode.driverdata)->currentOrientation;
-
-        if ((oldOrientation == DisplayOrientations::Landscape && newOrientation == DisplayOrientations::LandscapeFlipped) ||
-            (oldOrientation == DisplayOrientations::LandscapeFlipped && newOrientation == DisplayOrientations::Landscape) ||
-            (oldOrientation == DisplayOrientations::Portrait && newOrientation == DisplayOrientations::PortraitFlipped) ||
-            (oldOrientation == DisplayOrientations::PortraitFlipped && newOrientation == DisplayOrientations::Portrait))
-        {
-            // One of the reasons this event is getting sent out is because SDL
-            // will ignore requests to send out SDL_WINDOWEVENT_RESIZED events
-            // if and when the event size doesn't change (and the Direct3D 11.1
-            // renderer doesn't get the memo).
-            //
-            // Make sure that the display/window size really didn't change.  If
-            // it did, then a SDL_WINDOWEVENT_SIZE_CHANGED event got sent, and
-            // the Direct3D 11.1 renderer picked it up, presumably.
-            if (oldDisplayMode.w == newDisplayMode.w &&
-                oldDisplayMode.h == newDisplayMode.h)
-            {
-                SDL_SendWindowEvent(
-                    WINRT_GlobalSDLWindow,
-                    SDL_WINDOWEVENT_SIZE_CHANGED,
-                    newDisplayMode.w,
-                    newDisplayMode.h);
-            }
-        }
-#endif
-    }
-    
-    // Finally, free the 'driverdata' field of the old 'desktop_mode'.
-    if (oldDisplayMode.driverdata) {
-        SDL_free(oldDisplayMode.driverdata);
-        oldDisplayMode.driverdata = NULL;
-    }
-}
-
-SDL_WinRTApp::SDL_WinRTApp() :
-    m_windowClosed(false),
-    m_windowVisible(true)
-{
-}
-
-void SDL_WinRTApp::Initialize(CoreApplicationView^ applicationView)
-{
-    applicationView->Activated +=
-        ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &SDL_WinRTApp::OnActivated);
-
-    CoreApplication::Suspending +=
-        ref new EventHandler<SuspendingEventArgs^>(this, &SDL_WinRTApp::OnSuspending);
-
-    CoreApplication::Resuming +=
-        ref new EventHandler<Platform::Object^>(this, &SDL_WinRTApp::OnResuming);
-
-    CoreApplication::Exiting +=
-        ref new EventHandler<Platform::Object^>(this, &SDL_WinRTApp::OnExiting);
-
-    DisplayProperties::OrientationChanged +=
-        ref new DisplayPropertiesEventHandler(this, &SDL_WinRTApp::OnOrientationChanged);
-
-    // Register the hint, SDL_HINT_ORIENTATIONS, with SDL.  This needs to be
-    // done before the hint's callback is registered (as of Feb 22, 2013),
-    // otherwise the hint callback won't get registered.
-    //
-    // TODO, WinRT: see if an app's default orientation can be found out via WinRT API(s), then set the initial value of SDL_HINT_ORIENTATIONS accordingly.
-    //SDL_SetHint(SDL_HINT_ORIENTATIONS, "LandscapeLeft LandscapeRight Portrait PortraitUpsideDown");   // DavidL: this is no longer needed (for SDL_AddHintCallback)
-    SDL_AddHintCallback(SDL_HINT_ORIENTATIONS, WINRT_SetDisplayOrientationsPreference, NULL);
-}
-
-void SDL_WinRTApp::OnOrientationChanged(Object^ sender)
-{
-#if LOG_ORIENTATION_EVENTS==1
-    CoreWindow^ window = CoreWindow::GetForCurrentThread();
-    if (window) {
-        SDL_Log("%s, current orientation=%d, native orientation=%d, auto rot. pref=%d, CoreWindow Size={%f,%f}\n",
-            __FUNCTION__,
-            (int)DisplayProperties::CurrentOrientation,
-            (int)DisplayProperties::NativeOrientation,
-            (int)DisplayProperties::AutoRotationPreferences,
-            window->Bounds.Width,
-            window->Bounds.Height);
-    } else {
-        SDL_Log("%s, current orientation=%d, native orientation=%d, auto rot. pref=%d\n",
-            __FUNCTION__,
-            (int)DisplayProperties::CurrentOrientation,
-            (int)DisplayProperties::NativeOrientation,
-            (int)DisplayProperties::AutoRotationPreferences);
-    }
-#endif
-
-#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
-    // On Windows Phone, treat an orientation change as a change in window size.
-    // The native window's size doesn't seem to change, however SDL will simulate
-    // a window size change.
-    WINRT_ProcessWindowSizeChange();
-#endif
-}
-
-void SDL_WinRTApp::SetWindow(CoreWindow^ window)
-{
-#if LOG_WINDOW_EVENTS==1
-    SDL_Log("%s, current orientation=%d, native orientation=%d, auto rot. pref=%d, window Size={%f,%f}\n",
-        __FUNCTION__,
-        (int)DisplayProperties::CurrentOrientation,
-        (int)DisplayProperties::NativeOrientation,
-        (int)DisplayProperties::AutoRotationPreferences,
-        window->Bounds.Width,
-        window->Bounds.Height);
-#endif
-
-    window->SizeChanged += 
-        ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &SDL_WinRTApp::OnWindowSizeChanged);
-
-    window->VisibilityChanged +=
-        ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &SDL_WinRTApp::OnVisibilityChanged);
-
-    window->Closed += 
-        ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &SDL_WinRTApp::OnWindowClosed);
-
-#if WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP
-    window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
-#endif
-
-    window->PointerPressed +=
-        ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerPressed);
-
-    window->PointerMoved +=
-        ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerMoved);
-
-    window->PointerReleased +=
-        ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerReleased);
-
-    window->PointerWheelChanged +=
-        ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerWheelChanged);
-
-#if WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP
-    // Retrieves relative-only mouse movements:
-    Windows::Devices::Input::MouseDevice::GetForCurrentView()->MouseMoved +=
-        ref new TypedEventHandler<MouseDevice^, MouseEventArgs^>(this, &SDL_WinRTApp::OnMouseMoved);
-#endif
-
-    window->KeyDown +=
-        ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &SDL_WinRTApp::OnKeyDown);
-
-    window->KeyUp +=
-        ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &SDL_WinRTApp::OnKeyUp);
-
-#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
-    HardwareButtons::BackPressed +=
-        ref new EventHandler<BackPressedEventArgs^>(this, &SDL_WinRTApp::OnBackButtonPressed);
-#endif
-
-#if WINAPI_FAMILY == WINAPI_FAMILY_APP  // for Windows 8/8.1/RT apps... (and not Phone apps)
-    // Make sure we know when a user has opened the app's settings pane.
-    // This is needed in order to display a privacy policy, which needs
-    // to be done for network-enabled apps, as per Windows Store requirements.
-    using namespace Windows::UI::ApplicationSettings;
-    SettingsPane::GetForCurrentView()->CommandsRequested +=
-        ref new TypedEventHandler<SettingsPane^, SettingsPaneCommandsRequestedEventArgs^>
-            (this, &SDL_WinRTApp::OnSettingsPaneCommandsRequested);
-#endif
-}
-
-void SDL_WinRTApp::Load(Platform::String^ entryPoint)
-{
-}
-
-void SDL_WinRTApp::Run()
-{
-    SDL_SetMainReady();
-    if (WINRT_SDLAppEntryPoint)
-    {
-        // TODO, WinRT: pass the C-style main() a reasonably realistic
-        // representation of command line arguments.
-        int argc = 0;
-        char **argv = NULL;
-        WINRT_SDLAppEntryPoint(argc, argv);
-    }
-}
-
-void SDL_WinRTApp::PumpEvents()
-{
-    if (!m_windowClosed)
-    {
-        if (m_windowVisible)
-        {
-            CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
-        }
-        else
-        {
-            CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
-        }
-    }
-}
-
-void SDL_WinRTApp::Uninitialize()
-{
-}
-
-#if WINAPI_FAMILY == WINAPI_FAMILY_APP
-void SDL_WinRTApp::OnSettingsPaneCommandsRequested(
-    Windows::UI::ApplicationSettings::SettingsPane ^p,
-    Windows::UI::ApplicationSettings::SettingsPaneCommandsRequestedEventArgs ^args)
-{
-    using namespace Platform;
-    using namespace Windows::UI::ApplicationSettings;
-    using namespace Windows::UI::Popups;
-
-    String ^privacyPolicyURL = nullptr;     // a URL to an app's Privacy Policy
-    String ^privacyPolicyLabel = nullptr;   // label/link text
-    const char *tmpHintValue = NULL;        // SDL_GetHint-retrieved value, used immediately
-    wchar_t *tmpStr = NULL;                 // used for UTF8 to UCS2 conversion
-
-    // Setup a 'Privacy Policy' link, if one is available (via SDL_GetHint):
-    tmpHintValue = SDL_GetHint(SDL_HINT_WINRT_PRIVACY_POLICY_URL);
-    if (tmpHintValue && tmpHintValue[0] != '\0') {
-        // Convert the privacy policy's URL to UCS2:
-        tmpStr = WIN_UTF8ToString(tmpHintValue);
-        privacyPolicyURL = ref new String(tmpStr);
-        SDL_free(tmpStr);
-
-        // Optionally retrieve custom label-text for the link.  If this isn't
-        // available, a default value will be used instead.
-        tmpHintValue = SDL_GetHint(SDL_HINT_WINRT_PRIVACY_POLICY_LABEL);
-        if (tmpHintValue && tmpHintValue[0] != '\0') {
-            tmpStr = WIN_UTF8ToString(tmpHintValue);
-            privacyPolicyLabel = ref new String(tmpStr);
-            SDL_free(tmpStr);
-        } else {
-            privacyPolicyLabel = ref new String(L"Privacy Policy");
-        }
-
-        // Register the link, along with a handler to be called if and when it is
-        // clicked:
-        auto cmd = ref new SettingsCommand(L"privacyPolicy", privacyPolicyLabel,
-            ref new UICommandInvokedHandler([=](IUICommand ^) {
-                Windows::System::Launcher::LaunchUriAsync(ref new Uri(privacyPolicyURL));
-        }));
-        args->Request->ApplicationCommands->Append(cmd);
-    }
-}
-#endif // if WINAPI_FAMILY == WINAPI_FAMILY_APP
-
-void SDL_WinRTApp::OnWindowSizeChanged(CoreWindow^ sender, WindowSizeChangedEventArgs^ args)
-{
-#if LOG_WINDOW_EVENTS==1
-    SDL_Log("%s, size={%f,%f}, current orientation=%d, native orientation=%d, auto rot. pref=%d, WINRT_GlobalSDLWindow?=%s\n",
-        __FUNCTION__,
-        args->Size.Width, args->Size.Height,
-        (int)DisplayProperties::CurrentOrientation,
-        (int)DisplayProperties::NativeOrientation,
-        (int)DisplayProperties::AutoRotationPreferences,
-        (WINRT_GlobalSDLWindow ? "yes" : "no"));
-#endif
-
-    WINRT_ProcessWindowSizeChange();
-}
-
-void SDL_WinRTApp::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
-{
-#if LOG_WINDOW_EVENTS==1
-    SDL_Log("%s, visible?=%s, WINRT_GlobalSDLWindow?=%s\n",
-        __FUNCTION__,
-        (args->Visible ? "yes" : "no"),
-        (WINRT_GlobalSDLWindow ? "yes" : "no"));
-#endif
-
-    m_windowVisible = args->Visible;
-    if (WINRT_GlobalSDLWindow) {
-        SDL_bool wasSDLWindowSurfaceValid = WINRT_GlobalSDLWindow->surface_valid;
-
-        if (args->Visible) {
-            SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_SHOWN, 0, 0);
-        } else {
-            SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_HIDDEN, 0, 0);
-        }
-
-        // HACK: Prevent SDL's window-hide handling code, which currently
-        // triggers a fake window resize (possibly erronously), from
-        // marking the SDL window's surface as invalid.
-        //
-        // A better solution to this probably involves figuring out if the
-        // fake window resize can be prevented.
-        WINRT_GlobalSDLWindow->surface_valid = wasSDLWindowSurfaceValid;
-    }
-}
-
-void SDL_WinRTApp::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
-{
-#if LOG_WINDOW_EVENTS==1
-    SDL_Log("%s\n", __FUNCTION__);
-#endif
-    m_windowClosed = true;
-}
-
-void SDL_WinRTApp::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args)
-{
-    CoreWindow::GetForCurrentThread()->Activate();
-}
-
-static int SDLCALL RemoveAppSuspendAndResumeEvents(void * userdata, SDL_Event * event)
-{
-    if (event->type == SDL_WINDOWEVENT)
-    {
-        switch (event->window.event)
-        {
-            case SDL_WINDOWEVENT_MINIMIZED:
-            case SDL_WINDOWEVENT_RESTORED:
-                // Return 0 to indicate that the event should be removed from the
-                // event queue:
-                return 0;
-            default:
-                break;
-        }
-    }
-
-    // Return 1 to indicate that the event should stay in the event queue:
-    return 1;
-}
-
-void SDL_WinRTApp::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
-{
-    // Save app state asynchronously after requesting a deferral. Holding a deferral
-    // indicates that the application is busy performing suspending operations. Be
-    // aware that a deferral may not be held indefinitely. After about five seconds,
-    // the app will be forced to exit.
-    SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();
-    create_task([this, deferral]()
-    {
-        // Send a window-minimized event immediately to observers.
-        // CoreDispatcher::ProcessEvents, which is the backbone on which
-        // SDL_WinRTApp::PumpEvents is built, will not return to its caller
-        // once it sends out a suspend event.  Any events posted to SDL's
-        // event queue won't get received until the WinRT app is resumed.
-        // SDL_AddEventWatch() may be used to receive app-suspend events on
-        // WinRT.
-        //
-        // In order to prevent app-suspend events from being received twice:
-        // first via a callback passed to SDL_AddEventWatch, and second via
-        // SDL's event queue, the event will be sent to SDL, then immediately
-        // removed from the queue.
-        if (WINRT_GlobalSDLWindow)
-        {
-            SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_MINIMIZED, 0, 0);   // TODO: see if SDL_WINDOWEVENT_SIZE_CHANGED should be getting triggered here (it is, currently)
-            SDL_FilterEvents(RemoveAppSuspendAndResumeEvents, 0);
-        }
-
-        SDL_SendAppEvent(SDL_APP_WILLENTERBACKGROUND);
-        SDL_SendAppEvent(SDL_APP_DIDENTERBACKGROUND);
-
-        deferral->Complete();
-    });
-}
-
-void SDL_WinRTApp::OnResuming(Platform::Object^ sender, Platform::Object^ args)
-{
-    SDL_SendAppEvent(SDL_APP_WILLENTERFOREGROUND);
-    SDL_SendAppEvent(SDL_APP_DIDENTERFOREGROUND);
-
-    // Restore any data or state that was unloaded on suspend. By default, data
-    // and state are persisted when resuming from suspend. Note that this event
-    // does not occur if the app was previously terminated.
-    if (WINRT_GlobalSDLWindow)
-    {
-        SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_RESTORED, 0, 0);    // TODO: see if SDL_WINDOWEVENT_SIZE_CHANGED should be getting triggered here (it is, currently)
-
-        // Remove the app-resume event from the queue, as is done with the
-        // app-suspend event.
-        //
-        // TODO, WinRT: consider posting this event to the queue even though
-        // its counterpart, the app-suspend event, effectively has to be
-        // processed immediately.
-        SDL_FilterEvents(RemoveAppSuspendAndResumeEvents, 0);
-    }
-}
-
-void SDL_WinRTApp::OnExiting(Platform::Object^ sender, Platform::Object^ args)
-{
-    SDL_SendAppEvent(SDL_APP_TERMINATING);
-}
-
-static void
-WINRT_LogPointerEvent(const char * header, Windows::UI::Core::PointerEventArgs ^ args, Windows::Foundation::Point transformedPoint)
-{
-    Windows::UI::Input::PointerPoint ^ pt = args->CurrentPoint;
-    SDL_Log("%s: Position={%f,%f}, Transformed Pos={%f, %f}, MouseWheelDelta=%d, FrameId=%d, PointerId=%d, SDL button=%d\n",
-        header,
-        pt->Position.X, pt->Position.Y,
-        transformedPoint.X, transformedPoint.Y,
-        pt->Properties->MouseWheelDelta,
-        pt->FrameId,
-        pt->PointerId,
-        WINRT_GetSDLButtonForPointerPoint(pt));
-}
-
-void SDL_WinRTApp::OnPointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
-{
-#if LOG_POINTER_EVENTS
-    WINRT_LogPointerEvent("pointer pressed", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
-#endif
-
-    WINRT_ProcessPointerPressedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
-}
-
-void SDL_WinRTApp::OnPointerMoved(CoreWindow^ sender, PointerEventArgs^ args)
-{
-#if LOG_POINTER_EVENTS
-    WINRT_LogPointerEvent("pointer moved", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
-#endif
-
-    WINRT_ProcessPointerMovedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
-}
-
-void SDL_WinRTApp::OnPointerReleased(CoreWindow^ sender, PointerEventArgs^ args)
-{
-#if LOG_POINTER_EVENTS
-    WINRT_LogPointerEvent("pointer released", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
-#endif
-
-    WINRT_ProcessPointerReleasedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
-}
-
-void SDL_WinRTApp::OnPointerWheelChanged(CoreWindow^ sender, PointerEventArgs^ args)
-{
-#if LOG_POINTER_EVENTS
-    WINRT_LogPointerEvent("pointer wheel changed", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
-#endif
-
-    WINRT_ProcessPointerWheelChangedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
-}
-
-void SDL_WinRTApp::OnMouseMoved(MouseDevice^ mouseDevice, MouseEventArgs^ args)
-{
-    WINRT_ProcessMouseMovedEvent(WINRT_GlobalSDLWindow, args);
-}
-
-void SDL_WinRTApp::OnKeyDown(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args)
-{
-    WINRT_ProcessKeyDownEvent(args);
-}
-
-void SDL_WinRTApp::OnKeyUp(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args)
-{
-    WINRT_ProcessKeyUpEvent(args);
-}
-
-#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
-void SDL_WinRTApp::OnBackButtonPressed(Platform::Object^ sender, Windows::Phone::UI::Input::BackPressedEventArgs^ args)
-{
-    SDL_SendKeyboardKey(SDL_PRESSED, SDL_SCANCODE_AC_BACK);
-    SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_AC_BACK);
-
+
+/* Standard C++11 includes */
+#include <functional>
+#include <string>
+#include <sstream>
+using namespace std;
+
+
+/* Windows includes */
+#include "ppltasks.h"
+using namespace concurrency;
+using namespace Windows::ApplicationModel;
+using namespace Windows::ApplicationModel::Core;
+using namespace Windows::ApplicationModel::Activation;
+using namespace Windows::Devices::Input;
+using namespace Windows::Graphics::Display;
+using namespace Windows::Foundation;
+using namespace Windows::System;
+using namespace Windows::UI::Core;
+using namespace Windows::UI::Input;
+
+#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
+using namespace Windows::Phone::UI::Input;
+#endif
+
+
+/* SDL includes */
+extern "C" {
+#include "SDL_assert.h"
+#include "SDL_events.h"
+#include "SDL_hints.h"
+#include "SDL_log.h"
+#include "SDL_main.h"
+#include "SDL_stdinc.h"
+#include "SDL_render.h"
+#include "../../video/SDL_sysvideo.h"
+//#include "../../SDL_hints_c.h"
+#include "../../events/SDL_events_c.h"
+#include "../../events/SDL_keyboard_c.h"
+#include "../../events/SDL_mouse_c.h"
+#include "../../events/SDL_windowevents_c.h"
+#include "../../render/SDL_sysrender.h"
+#include "../windows/SDL_windows.h"
+}
+
+#include "../../video/winrt/SDL_winrtevents_c.h"
+#include "../../video/winrt/SDL_winrtvideo_cpp.h"
+#include "SDL_winrtapp_common.h"
+#include "SDL_winrtapp_direct3d.h"
+
+
+// Compile-time debugging options:
+// To enable, uncomment; to disable, comment them out.
+//#define LOG_POINTER_EVENTS 1
+//#define LOG_WINDOW_EVENTS 1
+//#define LOG_ORIENTATION_EVENTS 1
+
+
+// HACK, DLudwig: record a reference to the global, WinRT 'app'/view.
+// SDL/WinRT will use this throughout its code.
+//
+// TODO, WinRT: consider replacing SDL_WinRTGlobalApp with something
+// non-global, such as something created inside
+// SDL_InitSubSystem(SDL_INIT_VIDEO), or something inside
+// SDL_CreateWindow().
+SDL_WinRTApp ^ SDL_WinRTGlobalApp = nullptr;
+
+ref class SDLApplicationSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource
+{
+public:
+    virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView();
+};
+
+IFrameworkView^ SDLApplicationSource::CreateView()
+{
+    // TODO, WinRT: see if this function (CreateView) can ever get called
+    // more than once.  For now, just prevent it from ever assigning
+    // SDL_WinRTGlobalApp more than once.
+    SDL_assert(!SDL_WinRTGlobalApp);
+    SDL_WinRTApp ^ app = ref new SDL_WinRTApp();
+    if (!SDL_WinRTGlobalApp)
+    {
+        SDL_WinRTGlobalApp = app;
+    }
+    return app;
+}
+
+int SDL_WinRTInitNonXAMLApp(int (*mainFunction)(int, char **))
+{
+    WINRT_SDLAppEntryPoint = mainFunction;
+    auto direct3DApplicationSource = ref new SDLApplicationSource();
+    CoreApplication::Run(direct3DApplicationSource);
+    return 0;
+}
+
+static void WINRT_SetDisplayOrientationsPreference(void *userdata, const char *name, const char *oldValue, const char *newValue)
+{
+    SDL_assert(SDL_strcmp(name, SDL_HINT_ORIENTATIONS) == 0);
+
+    // Start with no orientation flags, then add each in as they're parsed
+    // from newValue.
+    unsigned int orientationFlags = 0;
+    if (newValue) {
+        std::istringstream tokenizer(newValue);
+        while (!tokenizer.eof()) {
+            std::string orientationName;
+            std::getline(tokenizer, orientationName, ' ');
+            if (orientationName == "LandscapeLeft") {
+                orientationFlags |= (unsigned int) DisplayOrientations::LandscapeFlipped;
+            } else if (orientationName == "LandscapeRight") {
+                orientationFlags |= (unsigned int) DisplayOrientations::Landscape;
+            } else if (orientationName == "Portrait") {
+                orientationFlags |= (unsigned int) DisplayOrientations::Portrait;
+            } else if (orientationName == "PortraitUpsideDown") {
+                orientationFlags |= (unsigned int) DisplayOrientations::PortraitFlipped;
+            }
+        }
+    }
+
+    // If no valid orientation flags were specified, use a reasonable set of defaults:
+    if (!orientationFlags) {
+        // TODO, WinRT: consider seeing if an app's default orientation flags can be found out via some API call(s).
+        orientationFlags = (unsigned int) ( \
+            DisplayOrientations::Landscape |
+            DisplayOrientations::LandscapeFlipped |
+            DisplayOrientations::Portrait |
+            DisplayOrientations::PortraitFlipped);
+    }
+
+    // Set the orientation/rotation preferences.  Please note that this does
+    // not constitute a 100%-certain lock of a given set of possible
+    // orientations.  According to Microsoft's documentation on WinRT [1]
+    // when a device is not capable of being rotated, Windows may ignore
+    // the orientation preferences, and stick to what the device is capable of
+    // displaying.
+    //
+    // [1] Documentation on the 'InitialRotationPreference' setting for a
+    // Windows app's manifest file describes how some orientation/rotation
+    // preferences may be ignored.  See
+    // http://msdn.microsoft.com/en-us/library/windows/apps/hh700343.aspx
+    // for details.  Microsoft's "Display orientation sample" also gives an
+    // outline of how Windows treats device rotation
+    // (http://code.msdn.microsoft.com/Display-Orientation-Sample-19a58e93).
+    DisplayProperties::AutoRotationPreferences = (DisplayOrientations) orientationFlags;
+}
+
+static void
+WINRT_ProcessWindowSizeChange()
+{
+    // Make the new window size be the one true fullscreen mode.
+    // This change was initially done, in part, to allow the Direct3D 11.1
+    // renderer to receive window-resize events as a device rotates.
+    // Before, rotating a device from landscape, to portrait, and then
+    // back to landscape would cause the Direct3D 11.1 swap buffer to
+    // not get resized appropriately.  SDL would, on the rotation from
+    // landscape to portrait, re-resize the SDL window to it's initial
+    // size (landscape).  On the subsequent rotation, SDL would drop the
+    // window-resize event as it appeared the SDL window didn't change
+    // size, and the Direct3D 11.1 renderer wouldn't resize its swap
+    // chain.
+    SDL_DisplayMode newDisplayMode;
+    if (WINRT_CalcDisplayModeUsingNativeWindow(&newDisplayMode) != 0) {
+        return;
+    }
+
+    // Make note of the old display mode, and it's old driverdata.
+    SDL_DisplayMode oldDisplayMode;
+    SDL_zero(oldDisplayMode);
+    if (WINRT_GlobalSDLVideoDevice) {
+        oldDisplayMode = WINRT_GlobalSDLVideoDevice->displays[0].desktop_mode;
+    }
+
+    // Setup the new display mode in the appropriate spots.
+    if (WINRT_GlobalSDLVideoDevice) {
+        // Make a full copy of the display mode for display_modes[0],
+        // one with with a separately malloced 'driverdata' field.
+        // SDL_VideoQuit(), if called, will attempt to free the driverdata
+        // fields in 'desktop_mode' and each entry in the 'display_modes'
+        // array.
+        if (WINRT_GlobalSDLVideoDevice->displays[0].display_modes[0].driverdata) {
+            // Free the previous mode's memory
+            SDL_free(WINRT_GlobalSDLVideoDevice->displays[0].display_modes[0].driverdata);
+            WINRT_GlobalSDLVideoDevice->displays[0].display_modes[0].driverdata = NULL;
+        }
+        if (WINRT_DuplicateDisplayMode(&(WINRT_GlobalSDLVideoDevice->displays[0].display_modes[0]), &newDisplayMode) != 0) {
+            // Uh oh, something went wrong.  A malloc call probably failed.
+            SDL_free(newDisplayMode.driverdata);
+            return;
+        }
+
+        // Install 'newDisplayMode' into 'current_mode' and 'desktop_mode'.
+        WINRT_GlobalSDLVideoDevice->displays[0].current_mode = newDisplayMode;
+        WINRT_GlobalSDLVideoDevice->displays[0].desktop_mode = newDisplayMode;
+    }
+
+    if (WINRT_GlobalSDLWindow) {
+        // Send a window-resize event to the rest of SDL, and to apps:
+        SDL_SendWindowEvent(
+            WINRT_GlobalSDLWindow,
+            SDL_WINDOWEVENT_RESIZED,
+            newDisplayMode.w,
+            newDisplayMode.h);
+
+#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
+        // HACK: On Windows Phone, make sure that orientation changes from
+        // Landscape to LandscapeFlipped, Portrait to PortraitFlipped,
+        // or vice-versa on either of those two, lead to the Direct3D renderer
+        // getting updated.
+        const DisplayOrientations oldOrientation = ((SDL_DisplayModeData *)oldDisplayMode.driverdata)->currentOrientation;
+        const DisplayOrientations newOrientation = ((SDL_DisplayModeData *)newDisplayMode.driverdata)->currentOrientation;
+
+        if ((oldOrientation == DisplayOrientations::Landscape && newOrientation == DisplayOrientations::LandscapeFlipped) ||
+            (oldOrientation == DisplayOrientations::LandscapeFlipped && newOrientation == DisplayOrientations::Landscape) ||
+            (oldOrientation == DisplayOrientations::Portrait && newOrientation == DisplayOrientations::PortraitFlipped) ||
+            (oldOrientation == DisplayOrientations::PortraitFlipped && newOrientation == DisplayOrientations::Portrait))
+        {
+            // One of the reasons this event is getting sent out is because SDL
+            // will ignore requests to send out SDL_WINDOWEVENT_RESIZED events
+            // if and when the event size doesn't change (and the Direct3D 11.1
+            // renderer doesn't get the memo).
+            //
+            // Make sure that the display/window size really didn't change.  If
+            // it did, then a SDL_WINDOWEVENT_SIZE_CHANGED event got sent, and
+            // the Direct3D 11.1 renderer picked it up, presumably.
+            if (oldDisplayMode.w == newDisplayMode.w &&
+                oldDisplayMode.h == newDisplayMode.h)
+            {
+                SDL_SendWindowEvent(
+                    WINRT_GlobalSDLWindow,
+                    SDL_WINDOWEVENT_SIZE_CHANGED,
+                    newDisplayMode.w,
+                    newDisplayMode.h);
+            }
+        }
+#endif
+    }
+    
+    // Finally, free the 'driverdata' field of the old 'desktop_mode'.
+    if (oldDisplayMode.driverdata) {
+        SDL_free(oldDisplayMode.driverdata);
+        oldDisplayMode.driverdata = NULL;
+    }
+}
+
+SDL_WinRTApp::SDL_WinRTApp() :
+    m_windowClosed(false),
+    m_windowVisible(true)
+{
+}
+
+void SDL_WinRTApp::Initialize(CoreApplicationView^ applicationView)
+{
+    applicationView->Activated +=
+        ref new TypedEventHandler<CoreApplicationView^, IActivatedEventArgs^>(this, &SDL_WinRTApp::OnActivated);
+
+    CoreApplication::Suspending +=
+        ref new EventHandler<SuspendingEventArgs^>(this, &SDL_WinRTApp::OnSuspending);
+
+    CoreApplication::Resuming +=
+        ref new EventHandler<Platform::Object^>(this, &SDL_WinRTApp::OnResuming);
+
+    CoreApplication::Exiting +=
+        ref new EventHandler<Platform::Object^>(this, &SDL_WinRTApp::OnExiting);
+
+    DisplayProperties::OrientationChanged +=
+        ref new DisplayPropertiesEventHandler(this, &SDL_WinRTApp::OnOrientationChanged);
+
+    // Register the hint, SDL_HINT_ORIENTATIONS, with SDL.  This needs to be
+    // done before the hint's callback is registered (as of Feb 22, 2013),
+    // otherwise the hint callback won't get registered.
+    //
+    // TODO, WinRT: see if an app's default orientation can be found out via WinRT API(s), then set the initial value of SDL_HINT_ORIENTATIONS accordingly.
+    //SDL_SetHint(SDL_HINT_ORIENTATIONS, "LandscapeLeft LandscapeRight Portrait PortraitUpsideDown");   // DavidL: this is no longer needed (for SDL_AddHintCallback)
+    SDL_AddHintCallback(SDL_HINT_ORIENTATIONS, WINRT_SetDisplayOrientationsPreference, NULL);
+}
+
+void SDL_WinRTApp::OnOrientationChanged(Object^ sender)
+{
+#if LOG_ORIENTATION_EVENTS==1
+    CoreWindow^ window = CoreWindow::GetForCurrentThread();
+    if (window) {
+        SDL_Log("%s, current orientation=%d, native orientation=%d, auto rot. pref=%d, CoreWindow Size={%f,%f}\n",
+            __FUNCTION__,
+            (int)DisplayProperties::CurrentOrientation,
+            (int)DisplayProperties::NativeOrientation,
+            (int)DisplayProperties::AutoRotationPreferences,
+            window->Bounds.Width,
+            window->Bounds.Height);
+    } else {
+        SDL_Log("%s, current orientation=%d, native orientation=%d, auto rot. pref=%d\n",
+            __FUNCTION__,
+            (int)DisplayProperties::CurrentOrientation,
+            (int)DisplayProperties::NativeOrientation,
+            (int)DisplayProperties::AutoRotationPreferences);
+    }
+#endif
+
+#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
+    // On Windows Phone, treat an orientation change as a change in window size.
+    // The native window's size doesn't seem to change, however SDL will simulate
+    // a window size change.
+    WINRT_ProcessWindowSizeChange();
+#endif
+}
+
+void SDL_WinRTApp::SetWindow(CoreWindow^ window)
+{
+#if LOG_WINDOW_EVENTS==1
+    SDL_Log("%s, current orientation=%d, native orientation=%d, auto rot. pref=%d, window Size={%f,%f}\n",
+        __FUNCTION__,
+        (int)DisplayProperties::CurrentOrientation,
+        (int)DisplayProperties::NativeOrientation,
+        (int)DisplayProperties::AutoRotationPreferences,
+        window->Bounds.Width,
+        window->Bounds.Height);
+#endif
+
+    window->SizeChanged += 
+        ref new TypedEventHandler<CoreWindow^, WindowSizeChangedEventArgs^>(this, &SDL_WinRTApp::OnWindowSizeChanged);
+
+    window->VisibilityChanged +=
+        ref new TypedEventHandler<CoreWindow^, VisibilityChangedEventArgs^>(this, &SDL_WinRTApp::OnVisibilityChanged);
+
+    window->Closed += 
+        ref new TypedEventHandler<CoreWindow^, CoreWindowEventArgs^>(this, &SDL_WinRTApp::OnWindowClosed);
+
+#if WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP
+    window->PointerCursor = ref new CoreCursor(CoreCursorType::Arrow, 0);
+#endif
+
+    window->PointerPressed +=
+        ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerPressed);
+
+    window->PointerMoved +=
+        ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerMoved);
+
+    window->PointerReleased +=
+        ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerReleased);
+
+    window->PointerWheelChanged +=
+        ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, &SDL_WinRTApp::OnPointerWheelChanged);
+
+#if WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP
+    // Retrieves relative-only mouse movements:
+    Windows::Devices::Input::MouseDevice::GetForCurrentView()->MouseMoved +=
+        ref new TypedEventHandler<MouseDevice^, MouseEventArgs^>(this, &SDL_WinRTApp::OnMouseMoved);
+#endif
+
+    window->KeyDown +=
+        ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &SDL_WinRTApp::OnKeyDown);
+
+    window->KeyUp +=
+        ref new TypedEventHandler<CoreWindow^, KeyEventArgs^>(this, &SDL_WinRTApp::OnKeyUp);
+
+#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
+    HardwareButtons::BackPressed +=
+        ref new EventHandler<BackPressedEventArgs^>(this, &SDL_WinRTApp::OnBackButtonPressed);
+#endif
+
+#if WINAPI_FAMILY == WINAPI_FAMILY_APP  // for Windows 8/8.1/RT apps... (and not Phone apps)
+    // Make sure we know when a user has opened the app's settings pane.
+    // This is needed in order to display a privacy policy, which needs
+    // to be done for network-enabled apps, as per Windows Store requirements.
+    using namespace Windows::UI::ApplicationSettings;
+    SettingsPane::GetForCurrentView()->CommandsRequested +=
+        ref new TypedEventHandler<SettingsPane^, SettingsPaneCommandsRequestedEventArgs^>
+            (this, &SDL_WinRTApp::OnSettingsPaneCommandsRequested);
+#endif
+}
+
+void SDL_WinRTApp::Load(Platform::String^ entryPoint)
+{
+}
+
+void SDL_WinRTApp::Run()
+{
+    SDL_SetMainReady();
+    if (WINRT_SDLAppEntryPoint)
+    {
+        // TODO, WinRT: pass the C-style main() a reasonably realistic
+        // representation of command line arguments.
+        int argc = 0;
+        char **argv = NULL;
+        WINRT_SDLAppEntryPoint(argc, argv);
+    }
+}
+
+void SDL_WinRTApp::PumpEvents()
+{
+    if (!m_windowClosed)
+    {
+        if (m_windowVisible)
+        {
+            CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
+        }
+        else
+        {
+            CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessOneAndAllPending);
+        }
+    }
+}
+
+void SDL_WinRTApp::Uninitialize()
+{
+}
+
+#if WINAPI_FAMILY == WINAPI_FAMILY_APP
+void SDL_WinRTApp::OnSettingsPaneCommandsRequested(
+    Windows::UI::ApplicationSettings::SettingsPane ^p,
+    Windows::UI::ApplicationSettings::SettingsPaneCommandsRequestedEventArgs ^args)
+{
+    using namespace Platform;
+    using namespace Windows::UI::ApplicationSettings;
+    using namespace Windows::UI::Popups;
+
+    String ^privacyPolicyURL = nullptr;     // a URL to an app's Privacy Policy
+    String ^privacyPolicyLabel = nullptr;   // label/link text
+    const char *tmpHintValue = NULL;        // SDL_GetHint-retrieved value, used immediately
+    wchar_t *tmpStr = NULL;                 // used for UTF8 to UCS2 conversion
+
+    // Setup a 'Privacy Policy' link, if one is available (via SDL_GetHint):
+    tmpHintValue = SDL_GetHint(SDL_HINT_WINRT_PRIVACY_POLICY_URL);
+    if (tmpHintValue && tmpHintValue[0] != '\0') {
+        // Convert the privacy policy's URL to UCS2:
+        tmpStr = WIN_UTF8ToString(tmpHintValue);
+        privacyPolicyURL = ref new String(tmpStr);
+        SDL_free(tmpStr);
+
+        // Optionally retrieve custom label-text for the link.  If this isn't
+        // available, a default value will be used instead.
+        tmpHintValue = SDL_GetHint(SDL_HINT_WINRT_PRIVACY_POLICY_LABEL);
+        if (tmpHintValue && tmpHintValue[0] != '\0') {
+            tmpStr = WIN_UTF8ToString(tmpHintValue);
+            privacyPolicyLabel = ref new String(tmpStr);
+            SDL_free(tmpStr);
+        } else {
+            privacyPolicyLabel = ref new String(L"Privacy Policy");
+        }
+
+        // Register the link, along with a handler to be called if and when it is
+        // clicked:
+        auto cmd = ref new SettingsCommand(L"privacyPolicy", privacyPolicyLabel,
+            ref new UICommandInvokedHandler([=](IUICommand ^) {
+                Windows::System::Launcher::LaunchUriAsync(ref new Uri(privacyPolicyURL));
+        }));
+        args->Request->ApplicationCommands->Append(cmd);
+    }
+}
+#endif // if WINAPI_FAMILY == WINAPI_FAMILY_APP
+
+void SDL_WinRTApp::OnWindowSizeChanged(CoreWindow^ sender, WindowSizeChangedEventArgs^ args)
+{
+#if LOG_WINDOW_EVENTS==1
+    SDL_Log("%s, size={%f,%f}, current orientation=%d, native orientation=%d, auto rot. pref=%d, WINRT_GlobalSDLWindow?=%s\n",
+        __FUNCTION__,
+        args->Size.Width, args->Size.Height,
+        (int)DisplayProperties::CurrentOrientation,
+        (int)DisplayProperties::NativeOrientation,
+        (int)DisplayProperties::AutoRotationPreferences,
+        (WINRT_GlobalSDLWindow ? "yes" : "no"));
+#endif
+
+    WINRT_ProcessWindowSizeChange();
+}
+
+void SDL_WinRTApp::OnVisibilityChanged(CoreWindow^ sender, VisibilityChangedEventArgs^ args)
+{
+#if LOG_WINDOW_EVENTS==1
+    SDL_Log("%s, visible?=%s, WINRT_GlobalSDLWindow?=%s\n",
+        __FUNCTION__,
+        (args->Visible ? "yes" : "no"),
+        (WINRT_GlobalSDLWindow ? "yes" : "no"));
+#endif
+
+    m_windowVisible = args->Visible;
+    if (WINRT_GlobalSDLWindow) {
+        SDL_bool wasSDLWindowSurfaceValid = WINRT_GlobalSDLWindow->surface_valid;
+
+        if (args->Visible) {
+            SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_SHOWN, 0, 0);
+        } else {
+            SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_HIDDEN, 0, 0);
+        }
+
+        // HACK: Prevent SDL's window-hide handling code, which currently
+        // triggers a fake window resize (possibly erronously), from
+        // marking the SDL window's surface as invalid.
+        //
+        // A better solution to this probably involves figuring out if the
+        // fake window resize can be prevented.
+        WINRT_GlobalSDLWindow->surface_valid = wasSDLWindowSurfaceValid;
+    }
+}
+
+void SDL_WinRTApp::OnWindowClosed(CoreWindow^ sender, CoreWindowEventArgs^ args)
+{
+#if LOG_WINDOW_EVENTS==1
+    SDL_Log("%s\n", __FUNCTION__);
+#endif
+    m_windowClosed = true;
+}
+
+void SDL_WinRTApp::OnActivated(CoreApplicationView^ applicationView, IActivatedEventArgs^ args)
+{
+    CoreWindow::GetForCurrentThread()->Activate();
+}
+
+static int SDLCALL RemoveAppSuspendAndResumeEvents(void * userdata, SDL_Event * event)
+{
+    if (event->type == SDL_WINDOWEVENT)
+    {
+        switch (event->window.event)
+        {
+            case SDL_WINDOWEVENT_MINIMIZED:
+            case SDL_WINDOWEVENT_RESTORED:
+                // Return 0 to indicate that the event should be removed from the
+                // event queue:
+                return 0;
+            default:
+                break;
+        }
+    }
+
+    // Return 1 to indicate that the event should stay in the event queue:
+    return 1;
+}
+
+void SDL_WinRTApp::OnSuspending(Platform::Object^ sender, SuspendingEventArgs^ args)
+{
+    // Save app state asynchronously after requesting a deferral. Holding a deferral
+    // indicates that the application is busy performing suspending operations. Be
+    // aware that a deferral may not be held indefinitely. After about five seconds,
+    // the app will be forced to exit.
+    SuspendingDeferral^ deferral = args->SuspendingOperation->GetDeferral();
+    create_task([this, deferral]()
+    {
+        // Send a window-minimized event immediately to observers.
+        // CoreDispatcher::ProcessEvents, which is the backbone on which
+        // SDL_WinRTApp::PumpEvents is built, will not return to its caller
+        // once it sends out a suspend event.  Any events posted to SDL's
+        // event queue won't get received until the WinRT app is resumed.
+        // SDL_AddEventWatch() may be used to receive app-suspend events on
+        // WinRT.
+        //
+        // In order to prevent app-suspend events from being received twice:
+        // first via a callback passed to SDL_AddEventWatch, and second via
+        // SDL's event queue, the event will be sent to SDL, then immediately
+        // removed from the queue.
+        if (WINRT_GlobalSDLWindow)
+        {
+            SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_MINIMIZED, 0, 0);   // TODO: see if SDL_WINDOWEVENT_SIZE_CHANGED should be getting triggered here (it is, currently)
+            SDL_FilterEvents(RemoveAppSuspendAndResumeEvents, 0);
+        }
+
+        SDL_SendAppEvent(SDL_APP_WILLENTERBACKGROUND);
+        SDL_SendAppEvent(SDL_APP_DIDENTERBACKGROUND);
+
+        deferral->Complete();
+    });
+}
+
+void SDL_WinRTApp::OnResuming(Platform::Object^ sender, Platform::Object^ args)
+{
+    SDL_SendAppEvent(SDL_APP_WILLENTERFOREGROUND);
+    SDL_SendAppEvent(SDL_APP_DIDENTERFOREGROUND);
+
+    // Restore any data or state that was unloaded on suspend. By default, data
+    // and state are persisted when resuming from suspend. Note that this event
+    // does not occur if the app was previously terminated.
+    if (WINRT_GlobalSDLWindow)
+    {
+        SDL_SendWindowEvent(WINRT_GlobalSDLWindow, SDL_WINDOWEVENT_RESTORED, 0, 0);    // TODO: see if SDL_WINDOWEVENT_SIZE_CHANGED should be getting triggered here (it is, currently)
+
+        // Remove the app-resume event from the queue, as is done with the
+        // app-suspend event.
+        //
+        // TODO, WinRT: consider posting this event to the queue even though
+        // its counterpart, the app-suspend event, effectively has to be
+        // processed immediately.
+        SDL_FilterEvents(RemoveAppSuspendAndResumeEvents, 0);
+    }
+}
+
+void SDL_WinRTApp::OnExiting(Platform::Object^ sender, Platform::Object^ args)
+{
+    SDL_SendAppEvent(SDL_APP_TERMINATING);
+}
+
+static void
+WINRT_LogPointerEvent(const char * header, Windows::UI::Core::PointerEventArgs ^ args, Windows::Foundation::Point transformedPoint)
+{
+    Windows::UI::Input::PointerPoint ^ pt = args->CurrentPoint;
+    SDL_Log("%s: Position={%f,%f}, Transformed Pos={%f, %f}, MouseWheelDelta=%d, FrameId=%d, PointerId=%d, SDL button=%d\n",
+        header,
+        pt->Position.X, pt->Position.Y,
+        transformedPoint.X, transformedPoint.Y,
+        pt->Properties->MouseWheelDelta,
+        pt->FrameId,
+        pt->PointerId,
+        WINRT_GetSDLButtonForPointerPoint(pt));
+}
+
+void SDL_WinRTApp::OnPointerPressed(CoreWindow^ sender, PointerEventArgs^ args)
+{
+#if LOG_POINTER_EVENTS
+    WINRT_LogPointerEvent("pointer pressed", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
+#endif
+
+    WINRT_ProcessPointerPressedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
+}
+
+void SDL_WinRTApp::OnPointerMoved(CoreWindow^ sender, PointerEventArgs^ args)
+{
+#if LOG_POINTER_EVENTS
+    WINRT_LogPointerEvent("pointer moved", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
+#endif
+
+    WINRT_ProcessPointerMovedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
+}
+
+void SDL_WinRTApp::OnPointerReleased(CoreWindow^ sender, PointerEventArgs^ args)
+{
+#if LOG_POINTER_EVENTS
+    WINRT_LogPointerEvent("pointer released", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
+#endif
+
+    WINRT_ProcessPointerReleasedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
+}
+
+void SDL_WinRTApp::OnPointerWheelChanged(CoreWindow^ sender, PointerEventArgs^ args)
+{
+#if LOG_POINTER_EVENTS
+    WINRT_LogPointerEvent("pointer wheel changed", args, WINRT_TransformCursorPosition(WINRT_GlobalSDLWindow, args->CurrentPoint->Position, TransformToSDLWindowSize));
+#endif
+
+    WINRT_ProcessPointerWheelChangedEvent(WINRT_GlobalSDLWindow, args->CurrentPoint);
+}
+
+void SDL_WinRTApp::OnMouseMoved(MouseDevice^ mouseDevice, MouseEventArgs^ args)
+{
+    WINRT_ProcessMouseMovedEvent(WINRT_GlobalSDLWindow, args);
+}
+
+void SDL_WinRTApp::OnKeyDown(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args)
+{
+    WINRT_ProcessKeyDownEvent(args);
+}
+
+void SDL_WinRTApp::OnKeyUp(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args)
+{
+    WINRT_ProcessKeyUpEvent(args);
+}
+
+#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
+void SDL_WinRTApp::OnBackButtonPressed(Platform::Object^ sender, Windows::Phone::UI::Input::BackPressedEventArgs^ args)
+{
+    SDL_SendKeyboardKey(SDL_PRESSED, SDL_SCANCODE_AC_BACK);
+    SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_AC_BACK);
+
     const char *hint = SDL_GetHint(SDL_HINT_WINRT_HANDLE_BACK_BUTTON);
     if (hint) {
         if (*hint == '1') {
             args->Handled = true;
         }
-    }
-}
-#endif
-
+    }
+}
+#endif
+
--- a/src/core/winrt/SDL_winrtapp_direct3d.h	Tue Mar 04 19:49:11 2014 -0500
+++ b/src/core/winrt/SDL_winrtapp_direct3d.h	Sun Mar 09 11:06:11 2014 -0700
@@ -1,58 +1,58 @@
-#pragma once
-
-#include <Windows.h>
-
-extern int SDL_WinRTInitNonXAMLApp(int (*mainFunction)(int, char **));
-
-ref class SDL_WinRTApp sealed : public Windows::ApplicationModel::Core::IFrameworkView
-{
-public:
-    SDL_WinRTApp();
-    
-    // IFrameworkView Methods.
-    virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
-    virtual void SetWindow(Windows::UI::Core::CoreWindow^ window);
-    virtual void Load(Platform::String^ entryPoint);
-    virtual void Run();
-    virtual void Uninitialize();
-
-internal:
-    // SDL-specific methods
-    void PumpEvents();
-
-protected:
-    // Event Handlers.
-
-#if WINAPI_FAMILY == WINAPI_FAMILY_APP  // for Windows 8/8.1/RT apps... (and not Phone apps)
-    void OnSettingsPaneCommandsRequested(
-        Windows::UI::ApplicationSettings::SettingsPane ^p,
-        Windows::UI::ApplicationSettings::SettingsPaneCommandsRequestedEventArgs ^args);
-#endif // if WINAPI_FAMILY == WINAPI_FAMILY_APP
-
-    void OnOrientationChanged(Platform::Object^ sender);
-    void OnWindowSizeChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ args);
-    void OnLogicalDpiChanged(Platform::Object^ sender);
-    void OnActivated(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args);
-    void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args);
-    void OnResuming(Platform::Object^ sender, Platform::Object^ args);
-    void OnExiting(Platform::Object^ sender, Platform::Object^ args);
-    void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args);
-    void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args);
-    void OnPointerPressed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args);
-    void OnPointerReleased(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args);
-    void OnPointerWheelChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args);
-    void OnPointerMoved(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args);
-    void OnMouseMoved(Windows::Devices::Input::MouseDevice^ mouseDevice, Windows::Devices::Input::MouseEventArgs^ args);
-    void OnKeyDown(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args);
-    void OnKeyUp(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args);
-
-#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
-    void OnBackButtonPressed(Platform::Object^ sender, Windows::Phone::UI::Input::BackPressedEventArgs^ args);
-#endif
-
-private:
-    bool m_windowClosed;
-    bool m_windowVisible;
-};
-
-extern SDL_WinRTApp ^ SDL_WinRTGlobalApp;
+#pragma once
+
+#include <Windows.h>
+
+extern int SDL_WinRTInitNonXAMLApp(int (*mainFunction)(int, char **));
+
+ref class SDL_WinRTApp sealed : public Windows::ApplicationModel::Core::IFrameworkView
+{
+public:
+    SDL_WinRTApp();
+    
+    // IFrameworkView Methods.
+    virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView);
+    virtual void SetWindow(Windows::UI::Core::CoreWindow^ window);
+    virtual void Load(Platform::String^ entryPoint);
+    virtual void Run();
+    virtual void Uninitialize();
+
+internal:
+    // SDL-specific methods
+    void PumpEvents();
+
+protected:
+    // Event Handlers.
+
+#if WINAPI_FAMILY == WINAPI_FAMILY_APP  // for Windows 8/8.1/RT apps... (and not Phone apps)
+    void OnSettingsPaneCommandsRequested(
+        Windows::UI::ApplicationSettings::SettingsPane ^p,
+        Windows::UI::ApplicationSettings::SettingsPaneCommandsRequestedEventArgs ^args);
+#endif // if WINAPI_FAMILY == WINAPI_FAMILY_APP
+
+    void OnOrientationChanged(Platform::Object^ sender);
+    void OnWindowSizeChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ args);
+    void OnLogicalDpiChanged(Platform::Object^ sender);
+    void OnActivated(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args);
+    void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args);
+    void OnResuming(Platform::Object^ sender, Platform::Object^ args);
+    void OnExiting(Platform::Object^ sender, Platform::Object^ args);
+    void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args);
+    void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args);
+    void OnPointerPressed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args);
+    void OnPointerReleased(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args);
+    void OnPointerWheelChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args);
+    void OnPointerMoved(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::PointerEventArgs^ args);
+    void OnMouseMoved(Windows::Devices::Input::MouseDevice^ mouseDevice, Windows::Devices::Input::MouseEventArgs^ args);
+    void OnKeyDown(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args);
+    void OnKeyUp(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::KeyEventArgs^ args);
+
+#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
+    void OnBackButtonPressed(Platform::Object^ sender, Windows::Phone::UI::Input::BackPressedEventArgs^ args);
+#endif
+
+private:
+    bool m_windowClosed;
+    bool m_windowVisible;
+};
+
+extern SDL_WinRTApp ^ SDL_WinRTGlobalApp;
--- a/src/file/SDL_rwops.c	Tue Mar 04 19:49:11 2014 -0500
+++ b/src/file/SDL_rwops.c	Sun Mar 09 11:06:11 2014 -0700
@@ -1,765 +1,765 @@
-/*
-  Simple DirectMedia Layer
-  Copyright (C) 1997-2013 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.
-*/
-/* Need this so Linux systems define fseek64o, ftell64o and off64_t */
-#define _LARGEFILE64_SOURCE
-#include "SDL_config.h"
-
-#if defined(__WIN32__)
-#include "../core/windows/SDL_windows.h"
-#endif
-
-
-/* This file provides a general interface for SDL to read and write
-   data sources.  It can easily be extended to files, memory, etc.
-*/
-
-#include "SDL_endian.h"
-#include "SDL_rwops.h"
-
-#ifdef __APPLE__
-#include "cocoa/SDL_rwopsbundlesupport.h"
-#endif /* __APPLE__ */
-
-#ifdef ANDROID
-#include "../core/android/SDL_android.h"
-#include "SDL_system.h"
-#endif
-
-#ifdef __WIN32__
-
-/* Functions to read/write Win32 API file pointers */
-
-#ifndef INVALID_SET_FILE_POINTER
-#define INVALID_SET_FILE_POINTER 0xFFFFFFFF
-#endif
-
-#define READAHEAD_BUFFER_SIZE   1024
-
-static int SDLCALL
-windows_file_open(SDL_RWops * context, const char *filename, const char *mode)
-{
-    UINT old_error_mode;
-    HANDLE h;
-    DWORD r_right, w_right;
-    DWORD must_exist, truncate;
-    int a_mode;
-
-    if (!context)
-        return -1;              /* failed (invalid call) */
-
-    context->hidden.windowsio.h = INVALID_HANDLE_VALUE;   /* mark this as unusable */
-    context->hidden.windowsio.buffer.data = NULL;
-    context->hidden.windowsio.buffer.size = 0;
-    context->hidden.windowsio.buffer.left = 0;
-
-    /* "r" = reading, file must exist */
-    /* "w" = writing, truncate existing, file may not exist */
-    /* "r+"= reading or writing, file must exist            */
-    /* "a" = writing, append file may not exist             */
-    /* "a+"= append + read, file may not exist              */
-    /* "w+" = read, write, truncate. file may not exist    */
-
-    must_exist = (SDL_strchr(mode, 'r') != NULL) ? OPEN_EXISTING : 0;
-    truncate = (SDL_strchr(mode, 'w') != NULL) ? CREATE_ALWAYS : 0;
-    r_right = (SDL_strchr(mode, '+') != NULL
-               || must_exist) ? GENERIC_READ : 0;
-    a_mode = (SDL_strchr(mode, 'a') != NULL) ? OPEN_ALWAYS : 0;
-    w_right = (a_mode || SDL_strchr(mode, '+')
-               || truncate) ? GENERIC_WRITE : 0;
-
-    if (!r_right && !w_right)   /* inconsistent mode */
-        return -1;              /* failed (invalid call) */
-
-    context->hidden.windowsio.buffer.data =
-        (char *) SDL_malloc(READAHEAD_BUFFER_SIZE);
-    if (!context->hidden.windowsio.buffer.data) {
-        return SDL_OutOfMemory();
-    }
-    /* Do not open a dialog box if failure */
-    old_error_mode =
-        SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);
-
-    {
-        LPTSTR tstr = WIN_UTF8ToString(filename);
-        h = CreateFile(tstr, (w_right | r_right),
-                       (w_right) ? 0 : FILE_SHARE_READ, NULL,
-                       (must_exist | truncate | a_mode),
-                       FILE_ATTRIBUTE_NORMAL, NULL);
-        SDL_free(tstr);
-    }
-
-    /* restore old behavior */
-    SetErrorMode(old_error_mode);
-
-    if (h == INVALID_HANDLE_VALUE) {
-        SDL_free(context->hidden.windowsio.buffer.data);
-        context->hidden.windowsio.buffer.data = NULL;
-        SDL_SetError("Couldn't open %s", filename);
-        return -2;              /* failed (CreateFile) */
-    }
-    context->hidden.windowsio.h = h;
-    context->hidden.windowsio.append = a_mode ? SDL_TRUE : SDL_FALSE;
-
-    return 0;                   /* ok */
-}
-
-static Sint64 SDLCALL
-windows_file_size(SDL_RWops * context)
-{
-    LARGE_INTEGER size;
-
-    if (!context || context->hidden.windowsio.h == INVALID_HANDLE_VALUE) {
-        return SDL_SetError("windows_file_size: invalid context/file not opened");
-    }
-
-    if (!GetFileSizeEx(context->hidden.windowsio.h, &size)) {
-        return WIN_SetError("windows_file_size");
-    }
-
-    return size.QuadPart;
-}
-
-static Sint64 SDLCALL
-windows_file_seek(SDL_RWops * context, Sint64 offset, int whence)
-{
-    DWORD windowswhence;
-    LARGE_INTEGER windowsoffset;
-
-    if (!context || context->hidden.windowsio.h == INVALID_HANDLE_VALUE) {
-        return SDL_SetError("windows_file_seek: invalid context/file not opened");
-    }
-
-    /* FIXME: We may be able to satisfy the seek within buffered data */
-    if (whence == RW_SEEK_CUR && context->hidden.windowsio.buffer.left) {
-        offset -= (long)context->hidden.windowsio.buffer.left;
-    }
-    context->hidden.windowsio.buffer.left = 0;
-
-    switch (whence) {
-    case RW_SEEK_SET:
-        windowswhence = FILE_BEGIN;
-        break;
-    case RW_SEEK_CUR:
-        windowswhence = FILE_CURRENT;
-        break;
-    case RW_SEEK_END:
-        windowswhence = FILE_END;
-        break;
-    default:
-        return SDL_SetError("windows_file_seek: Unknown value for 'whence'");
-    }
-
-    windowsoffset.QuadPart = offset;
-    if (!SetFilePointerEx(context->hidden.windowsio.h, windowsoffset, &windowsoffset, windowswhence)) {
-        return WIN_SetError("windows_file_seek");
-    }
-    return windowsoffset.QuadPart;
-}
-
-static size_t SDLCALL
-windows_file_read(SDL_RWops * context, void *ptr, size_t size, size_t maxnum)
-{
-    size_t total_need;
-    size_t total_read = 0;
-    size_t read_ahead;
-    DWORD byte_read;
-
-    total_need = size * maxnum;
-
-    if (!context || context->hidden.windowsio.h == INVALID_HANDLE_VALUE
-        || !total_need)
-        return 0;
-
-    if (context->hidden.windowsio.buffer.left > 0) {
-        void *data = (char *) context->hidden.windowsio.buffer.data +
-            context->hidden.windowsio.buffer.size -
-            context->hidden.windowsio.buffer.left;
-        read_ahead =
-            SDL_min(total_need, context->hidden.windowsio.buffer.left);
-        SDL_memcpy(ptr, data, read_ahead);
-        context->hidden.windowsio.buffer.left -= read_ahead;
-
-        if (read_ahead == total_need) {
-            return maxnum;
-        }
-        ptr = (char *) ptr + read_ahead;
-        total_need -= read_ahead;
-        total_read += read_ahead;
-    }
-
-    if (total_need < READAHEAD_BUFFER_SIZE) {
-        if (!ReadFile
-            (context->hidden.windowsio.h, context->hidden.windowsio.buffer.data,
-             READAHEAD_BUFFER_SIZE, &byte_read, NULL)) {
-            SDL_Error(SDL_EFREAD);
-            return 0;
-        }
-        read_ahead = SDL_min(total_need, (int) byte_read);
-        SDL_memcpy(ptr, context->hidden.windowsio.buffer.data, read_ahead);
-        context->hidden.windowsio.buffer.size = byte_read;
-        context->hidden.windowsio.buffer.left = byte_read - read_ahead;
-        total_read += read_ahead;
-    } else {
-        if (!ReadFile
-            (context->hidden.windowsio.h, ptr, (DWORD)total_need, &byte_read, NULL)) {
-            SDL_Error(SDL_EFREAD);
-            return 0;
-        }
-        total_read += byte_read;
-    }
-    return (total_read / size);
-}
-
-static size_t SDLCALL
-windows_file_write(SDL_RWops * context, const void *ptr, size_t size,
-                 size_t num)
-{
-
-    size_t total_bytes;
-    DWORD byte_written;
-    size_t nwritten;
-
-    total_bytes = size * num;
-
-    if (!context || context->hidden.windowsio.h == INVALID_HANDLE_VALUE
-        || total_bytes <= 0 || !size)
-        return 0;
-
-    if (context->hidden.windowsio.buffer.left) {
-        SetFilePointer(context->hidden.windowsio.h,
-                       -(LONG)context->hidden.windowsio.buffer.left, NULL,
-                       FILE_CURRENT);
-        context->hidden.windowsio.buffer.left = 0;
-    }
-
-    /* if in append mode, we must go to the EOF before write */
-    if (context->hidden.windowsio.append) {
-        if (SetFilePointer(context->hidden.windowsio.h, 0L, NULL, FILE_END) ==
-            INVALID_SET_FILE_POINTER) {
-            SDL_Error(SDL_EFWRITE);
-            return 0;
-        }
-    }
-
-    if (!WriteFile
-        (context->hidden.windowsio.h, ptr, (DWORD)total_bytes, &byte_written, NULL)) {
-        SDL_Error(SDL_EFWRITE);
-        return 0;
-    }
-
-    nwritten = byte_written / size;
-    return nwritten;
-}
-
-static int SDLCALL
-windows_file_close(SDL_RWops * context)
-{
-
-    if (context) {
-        if (context->hidden.windowsio.h != INVALID_HANDLE_VALUE) {
-            CloseHandle(context->hidden.windowsio.h);
-            context->hidden.windowsio.h = INVALID_HANDLE_VALUE;   /* to be sure */
-        }
-        SDL_free(context->hidden.windowsio.buffer.data);
-        context->hidden.windowsio.buffer.data = NULL;
-        SDL_FreeRW(context);
-    }
-    return (0);
-}
-#endif /* __WIN32__ */
-
-#ifdef HAVE_STDIO_H
-
-/* Functions to read/write stdio file pointers */
-
-static Sint64 SDLCALL
-stdio_size(SDL_RWops * context)
-{
-    Sint64 pos, size;
-
-    pos = SDL_RWseek(context, 0, RW_SEEK_CUR);
-    if (pos < 0) {
-        return -1;
-    }
-    size = SDL_RWseek(context, 0, RW_SEEK_END);
-
-    SDL_RWseek(context, pos, RW_SEEK_SET);
-    return size;
-}
-
-static Sint64 SDLCALL
-stdio_seek(SDL_RWops * context, Sint64 offset, int whence)
-{
-#ifdef HAVE_FSEEKO64
-    if (fseeko64(context->hidden.stdio.fp, (off64_t)offset, whence) == 0) {
-        return ftello64(context->hidden.stdio.fp);
-    }
-#elif defined(HAVE_FSEEKO)
-    if (fseeko(context->hidden.stdio.fp, (off_t)offset, whence) == 0) {
-        return ftello(context->hidden.stdio.fp);
-    }
-#elif defined(HAVE__FSEEKI64)
-    if (_fseeki64(context->hidden.stdio.fp, offset, whence) == 0) {
-        return _ftelli64(context->hidden.stdio.fp);
-    }
-#else
-    if (fseek(context->hidden.stdio.fp, offset, whence) == 0) {
-        return (ftell(context->hidden.stdio.fp));
-    }
-#endif
-    return SDL_Error(SDL_EFSEEK);
-}
-
-static size_t SDLCALL
-stdio_read(SDL_RWops * context, void *ptr, size_t size, size_t maxnum)
-{
-    size_t nread;
-
-    nread = fread(ptr, size, maxnum, context->hidden.stdio.fp);
-    if (nread == 0 && ferror(context->hidden.stdio.fp)) {
-        SDL_Error(SDL_EFREAD);
-    }
-    return (nread);
-}
-
-static size_t SDLCALL
-stdio_write(SDL_RWops * context, const void *ptr, size_t size, size_t num)
-{
-    size_t nwrote;
-
-    nwrote = fwrite(ptr, size, num, context->hidden.stdio.fp);
-    if (nwrote == 0 && ferror(context->hidden.stdio.fp)) {
-        SDL_Error(SDL_EFWRITE);
-    }
-    return (nwrote);
-}
-
-static int SDLCALL
-stdio_close(SDL_RWops * context)
-{
-    int status = 0;
-    if (context) {
-        if (context->hidden.stdio.autoclose) {
-            /* WARNING:  Check the return value here! */
-            if (fclose(context->hidden.stdio.fp) != 0) {
-                status = SDL_Error(SDL_EFWRITE);
-            }
-        }
-        SDL_FreeRW(context);
-    }
-    return status;
-}
-#endif /* !HAVE_STDIO_H */
-
-/* Functions to read/write memory pointers */
-
-static Sint64 SDLCALL
-mem_size(SDL_RWops * context)
-{
-    return (Sint64)(context->hidden.mem.stop - context->hidden.mem.base);
-}
-
-static Sint64 SDLCALL
-mem_seek(SDL_RWops * context, Sint64 offset, int whence)
-{
-    Uint8 *newpos;
-
-    switch (whence) {
-    case RW_SEEK_SET:
-        newpos = context->hidden.mem.base + offset;
-        break;
-    case RW_SEEK_CUR:
-        newpos = context->hidden.mem.here + offset;
-        break;
-    case RW_SEEK_END:
-        newpos = context->hidden.mem.stop + offset;
-        break;
-    default:
-        return SDL_SetError("Unknown value for 'whence'");
-    }
-    if (newpos < context->hidden.mem.base) {
-        newpos = context->hidden.mem.base;
-    }
-    if (newpos > context->hidden.mem.stop) {
-        newpos = context->hidden.mem.stop;
-    }
-    context->hidden.mem.here = newpos;
-    return (Sint64)(context->hidden.mem.here - context->hidden.mem.base);
-}
-
-static size_t SDLCALL
-mem_read(SDL_RWops * context, void *ptr, size_t size, size_t maxnum)
-{
-    size_t total_bytes;
-    size_t mem_available;
-
-    total_bytes = (maxnum * size);
-    if ((maxnum <= 0) || (size <= 0)
-        || ((total_bytes / maxnum) != (size_t) size)) {
-        return 0;
-    }
-
-    mem_available = (context->hidden.mem.stop - context->hidden.mem.here);
-    if (total_bytes > mem_available) {
-        total_bytes = mem_available;
-    }
-
-    SDL_memcpy(ptr, context->hidden.mem.here, total_bytes);
-    context->hidden.mem.here += total_bytes;
-
-    return (total_bytes / size);
-}
-
-static size_t SDLCALL
-mem_write(SDL_RWops * context, const void *ptr, size_t size, size_t num)
-{
-    if ((context->hidden.mem.here + (num * size)) > context->hidden.mem.stop) {
-        num = (context->hidden.mem.stop - context->hidden.mem.here) / size;
-    }
-    SDL_memcpy(context->hidden.mem.here, ptr, num * size);
-    context->hidden.mem.here += num * size;
-    return (num);
-}
-
-static size_t SDLCALL
-mem_writeconst(SDL_RWops * context, const void *ptr, size_t size, size_t num)
-{
-    SDL_SetError("Can't write to read-only memory");
-    return (0);
-}
-
-static int SDLCALL
-mem_close(SDL_RWops * context)
-{
-    if (context) {
-        SDL_FreeRW(context);
-    }
-    return (0);
-}
-
-
-/* Functions to create SDL_RWops structures from various data sources */
-
-SDL_RWops *
-SDL_RWFromFile(const char *file, const char *mode)
-{
-    SDL_RWops *rwops = NULL;
-    if (!file || !*file || !mode || !*mode) {
-        SDL_SetError("SDL_RWFromFile(): No file or no mode specified");
-        return NULL;
-    }
-#if defined(ANDROID)
-#ifdef HAVE_STDIO_H
-    /* Try to open the file on the filesystem first */
-    if (*file == '/') {
-        FILE *fp = fopen(file, mode);
-        if (fp) {
-            return SDL_RWFromFP(fp, 1);
-        }
-    } else {
-        /* Try opening it from internal storage if it's a relative path */
-        char *path;
-        FILE *fp;
-
-        path = SDL_stack_alloc(char, PATH_MAX);
-        if (path) {
-            SDL_snprintf(path, PATH_MAX, "%s/%s",
-                         SDL_AndroidGetInternalStoragePath(), file);
-            fp = fopen(path, mode);
-            SDL_stack_free(path);
-            if (fp) {
-                return SDL_RWFromFP(fp, 1);
-            }
-        }
-    }
-#endif /* HAVE_STDIO_H */
-
-    /* Try to open the file from the asset system */
-    rwops = SDL_AllocRW();
-    if (!rwops)
-        return NULL;            /* SDL_SetError already setup by SDL_AllocRW() */
-    if (Android_JNI_FileOpen(rwops, file, mode) < 0) {
-        SDL_FreeRW(rwops);
-        return NULL;
-    }
-    rwops->size = Android_JNI_FileSize;
-    rwops->seek = Android_JNI_FileSeek;
-    rwops->read = Android_JNI_FileRead;
-    rwops->write = Android_JNI_FileWrite;
-    rwops->close = Android_JNI_FileClose;
-    rwops->type = SDL_RWOPS_JNIFILE;
-
-#elif defined(__WIN32__)
-    rwops = SDL_AllocRW();
-    if (!rwops)
-        return NULL;            /* SDL_SetError already setup by SDL_AllocRW() */
-    if (windows_file_open(rwops, file, mode) < 0) {
-        SDL_FreeRW(rwops);
-        return NULL;
-    }
-    rwops->size = windows_file_size;
-    rwops->seek = windows_file_seek;
-    rwops->read = windows_file_read;
-    rwops->write = windows_file_write;
-    rwops->close = windows_file_close;
-    rwops->type = SDL_RWOPS_WINFILE;
-
-#elif HAVE_STDIO_H
-    {
-        #ifdef __APPLE__
-        FILE *fp = SDL_OpenFPFromBundleOrFallback(file, mode);
-        #elif __WINRT__
-        FILE *fp = NULL;
-        fopen_s(&fp, file, mode);
-        #else
-        FILE *fp = fopen(file, mode);
-        #endif
-        if (fp == NULL) {
-            SDL_SetError("Couldn't open %s", file);
-        } else {
-            rwops = SDL_RWFromFP(fp, 1);
-        }
-    }
-#else
-    SDL_SetError("SDL not compiled with stdio support");
-#endif /* !HAVE_STDIO_H */
-
-    return (rwops);
-}
-
-#ifdef HAVE_STDIO_H
-SDL_RWops *
-SDL_RWFromFP(FILE * fp, SDL_bool autoclose)
-{
-    SDL_RWops *rwops = NULL;
-
-    rwops = SDL_AllocRW();
-    if (rwops != NULL) {
-        rwops->size = stdio_size;
-        rwops->seek = stdio_seek;
-        rwops->read = stdio_read;
-        rwops->write = stdio_write;
-        rwops->close = stdio_close;
-        rwops->hidden.stdio.fp = fp;
-        rwops->hidden.stdio.autoclose = autoclose;
-        rwops->type = SDL_RWOPS_STDFILE;
-    }
-    return (rwops);
-}
-#else
-SDL_RWops *
-SDL_RWFromFP(void * fp, SDL_bool autoclose)
-{
-    SDL_SetError("SDL not compiled with stdio support");
-    return NULL;
-}
-#endif /* HAVE_STDIO_H */
-
-SDL_RWops *
-SDL_RWFromMem(void *mem, int size)
-{
-    SDL_RWops *rwops = NULL;
-    if (!mem) {
-      SDL_InvalidParamError("mem");
-      return (rwops);
-    }
-    if (!size) {
-      SDL_InvalidParamError("size");
-      return (rwops);
-    }
-
-    rwops = SDL_AllocRW();
-    if (rwops != NULL) {
-        rwops->size = mem_size;
-        rwops->seek = mem_seek;
-        rwops->read = mem_read;
-        rwops->write = mem_write;
-        rwops->close = mem_close;
-        rwops->hidden.mem.base = (Uint8 *) mem;
-        rwops->hidden.mem.here = rwops->hidden.mem.base;
-        rwops->hidden.mem.stop = rwops->hidden.mem.base + size;
-        rwops->type = SDL_RWOPS_MEMORY;
-    }
-    return (rwops);
-}
-
-SDL_RWops *
-SDL_RWFromConstMem(const void *mem, int size)
-{
-    SDL_RWops *rwops = NULL;
-    if (!mem) {
-      SDL_InvalidParamError("mem");
-      return (rwops);
-    }
-    if (!size) {
-      SDL_InvalidParamError("size");
-      return (rwops);
-    }
-
-    rwops = SDL_AllocRW();
-    if (rwops != NULL) {
-        rwops->size = mem_size;
-        rwops->seek = mem_seek;
-        rwops->read = mem_read;
-        rwops->write = mem_writeconst;
-        rwops->close = mem_close;
-        rwops->hidden.mem.base = (Uint8 *) mem;
-        rwops->hidden.mem.here = rwops->hidden.mem.base;
-        rwops->hidden.mem.stop = rwops->hidden.mem.base + size;
-        rwops->type = SDL_RWOPS_MEMORY_RO;
-    }
-    return (rwops);
-}
-
-SDL_RWops *
-SDL_AllocRW(void)
-{
-    SDL_RWops *area;
-
-    area = (SDL_RWops *) SDL_malloc(sizeof *area);
-    if (area == NULL) {
-        SDL_OutOfMemory();
-    } else {
-        area->type = SDL_RWOPS_UNKNOWN;
-    }
-    return (area);
-}
-
-void
-SDL_FreeRW(SDL_RWops * area)
-{
-    SDL_free(area);
-}
-
-/* Functions for dynamically reading and writing endian-specific values */
-
-Uint8
-SDL_ReadU8(SDL_RWops * src)
-{
-    Uint8 value = 0;
-
-    SDL_RWread(src, &value, (sizeof value), 1);
-    return value;
-}
-
-Uint16
-SDL_ReadLE16(SDL_RWops * src)
-{
-    Uint16 value = 0;
-
-    SDL_RWread(src, &value, (sizeof value), 1);
-    return (SDL_SwapLE16(value));
-}
-
-Uint16
-SDL_ReadBE16(SDL_RWops * src)
-{
-    Uint16 value = 0;
-
-    SDL_RWread(src, &value, (sizeof value), 1);
-    return (SDL_SwapBE16(value));
-}
-
-Uint32
-SDL_ReadLE32(SDL_RWops * src)
-{
-    Uint32 value = 0;
-
-    SDL_RWread(src, &value, (sizeof value), 1);
-    return (SDL_SwapLE32(value));
-}
-
-Uint32
-SDL_ReadBE32(SDL_RWops * src)
-{
-    Uint32 value = 0;
-
-    SDL_RWread(src, &value, (sizeof value), 1);
-    return (SDL_SwapBE32(value));
-}
-
-Uint64
-SDL_ReadLE64(SDL_RWops * src)
-{
-    Uint64 value = 0;
-
-    SDL_RWread(src, &value, (sizeof value), 1);
-    return (SDL_SwapLE64(value));
-}
-
-Uint64
-SDL_ReadBE64(SDL_RWops * src)
-{
-    Uint64 value = 0;
-
-    SDL_RWread(src, &value, (sizeof value), 1);
-    return (SDL_SwapBE64(value));
-}
-
-size_t
-SDL_WriteU8(SDL_RWops * dst, Uint8 value)
-{
-    return (SDL_RWwrite(dst, &value, (sizeof value), 1));
-}
-
-size_t
-SDL_WriteLE16(SDL_RWops * dst, Uint16 value)
-{
-    value = SDL_SwapLE16(value);
-    return (SDL_RWwrite(dst, &value, (sizeof value), 1));
-}
-
-size_t
-SDL_WriteBE16(SDL_RWops * dst, Uint16 value)
-{
-    value = SDL_SwapBE16(value);
-    return (SDL_RWwrite(dst, &value, (sizeof value), 1));
-}
-
-size_t
-SDL_WriteLE32(SDL_RWops * dst, Uint32 value)
-{
-    value = SDL_SwapLE32(value);
-    return (SDL_RWwrite(dst, &value, (sizeof value), 1));
-}
-
-size_t
-SDL_WriteBE32(SDL_RWops * dst, Uint32 value)
-{
-    value = SDL_SwapBE32(value);
-    return (SDL_RWwrite(dst, &value, (sizeof value), 1));
-}
-
-size_t
-SDL_WriteLE64(SDL_RWops * dst, Uint64 value)
-{
-    value = SDL_SwapLE64(value);
-    return (SDL_RWwrite(dst, &value, (sizeof value), 1));
-}
-
-size_t
-SDL_WriteBE64(SDL_RWops * dst, Uint64 value)
-{
-    value = SDL_SwapBE64(value);
-    return (SDL_RWwrite(dst, &value, (sizeof value), 1));
-}
-
-/* vi: set ts=4 sw=4 expandtab: */
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2013 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.
+*/
+/* Need this so Linux systems define fseek64o, ftell64o and off64_t */
+#define _LARGEFILE64_SOURCE
+#include "SDL_config.h"
+
+#if defined(__WIN32__)
+#include "../core/windows/SDL_windows.h"
+#endif
+
+
+/* This file provides a general interface for SDL to read and write
+   data sources.  It can easily be extended to files, memory, etc.
+*/
+
+#include "SDL_endian.h"
+#include "SDL_rwops.h"
+
+#ifdef __APPLE__
+#include "cocoa/SDL_rwopsbundlesupport.h"
+#endif /* __APPLE__ */
+
+#ifdef ANDROID
+#include "../core/android/SDL_android.h"
+#include "SDL_system.h"
+#endif
+
+#ifdef __WIN32__
+
+/* Functions to read/write Win32 API file pointers */
+
+#ifndef INVALID_SET_FILE_POINTER
+#define INVALID_SET_FILE_POINTER 0xFFFFFFFF
+#endif
+
+#define READAHEAD_BUFFER_SIZE   1024
+
+static int SDLCALL
+windows_file_open(SDL_RWops * context, const char *filename, const char *mode)
+{
+    UINT old_error_mode;
+    HANDLE h;
+    DWORD r_right, w_right;
+    DWORD must_exist, truncate;
+    int a_mode;
+
+    if (!context)
+        return -1;              /* failed (invalid call) */
+
+    context->hidden.windowsio.h = INVALID_HANDLE_VALUE;   /* mark this as unusable */
+    context->hidden.windowsio.buffer.data = NULL;
+    context->hidden.windowsio.buffer.size = 0;
+    context->hidden.windowsio.buffer.left = 0;
+
+    /* "r" = reading, file must exist */
+    /* "w" = writing, truncate existing, file may not exist */
+    /* "r+"= reading or writing, file must exist            */
+    /* "a" = writing, append file may not exist             */
+    /* "a+"= append + read, file may not exist              */
+    /* "w+" = read, write, truncate. file may not exist    */
+
+    must_exist = (SDL_strchr(mode, 'r') != NULL) ? OPEN_EXISTING : 0;
+    truncate = (SDL_strchr(mode, 'w') != NULL) ? CREATE_ALWAYS : 0;
+    r_right = (SDL_strchr(mode, '+') != NULL
+               || must_exist) ? GENERIC_READ : 0;
+    a_mode = (SDL_strchr(mode, 'a') != NULL) ? OPEN_ALWAYS : 0;
+    w_right = (a_mode || SDL_strchr(mode, '+')
+               || truncate) ? GENERIC_WRITE : 0;
+
+    if (!r_right && !w_right)   /* inconsistent mode */
+        return -1;              /* failed (invalid call) */
+
+    context->hidden.windowsio.buffer.data =
+        (char *) SDL_malloc(READAHEAD_BUFFER_SIZE);
+    if (!context->hidden.windowsio.buffer.data) {
+        return SDL_OutOfMemory();
+    }
+    /* Do not open a dialog box if failure */
+    old_error_mode =
+        SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);
+
+    {
+        LPTSTR tstr = WIN_UTF8ToString(filename);
+        h = CreateFile(tstr, (w_right | r_right),
+                       (w_right) ? 0 : FILE_SHARE_READ, NULL,
+                       (must_exist | truncate | a_mode),
+                       FILE_ATTRIBUTE_NORMAL, NULL);
+        SDL_free(tstr);
+    }
+
+    /* restore old behavior */
+    SetErrorMode(old_error_mode);
+
+    if (h == INVALID_HANDLE_VALUE) {
+        SDL_free(context->hidden.windowsio.buffer.data);
+        context->hidden.windowsio.buffer.data = NULL;
+        SDL_SetError("Couldn't open %s", filename);
+        return -2;              /* failed (CreateFile) */
+    }
+    context->hidden.windowsio.h = h;
+    context->hidden.windowsio.append = a_mode ? SDL_TRUE : SDL_FALSE;
+
+    return 0;                   /* ok */
+}
+
+static Sint64 SDLCALL
+windows_file_size(SDL_RWops * context)
+{
+    LARGE_INTEGER size;
+
+    if (!context || context->hidden.windowsio.h == INVALID_HANDLE_VALUE) {
+        return SDL_SetError("windows_file_size: invalid context/file not opened");
+    }
+
+    if (!GetFileSizeEx(context->hidden.windowsio.h, &size)) {
+        return WIN_SetError("windows_file_size");
+    }
+
+    return size.QuadPart;
+}
+
+static Sint64 SDLCALL
+windows_file_seek(SDL_RWops * context, Sint64 offset, int whence)
+{
+    DWORD windowswhence;
+    LARGE_INTEGER windowsoffset;
+
+    if (!context || context->hidden.windowsio.h == INVALID_HANDLE_VALUE) {
+        return SDL_SetError("windows_file_seek: invalid context/file not opened");
+    }
+
+    /* FIXME: We may be able to satisfy the seek within buffered data */
+    if (whence == RW_SEEK_CUR && context->hidden.windowsio.buffer.left) {
+        offset -= (long)context->hidden.windowsio.buffer.left;
+    }
+    context->hidden.windowsio.buffer.left = 0;
+
+    switch (whence) {
+    case RW_SEEK_SET:
+        windowswhence = FILE_BEGIN;
+        break;
+    case RW_SEEK_CUR:
+        windowswhence = FILE_CURRENT;
+        break;
+    case RW_SEEK_END:
+        windowswhence = FILE_END;
+        break;
+    default:
+        return SDL_SetError("windows_file_seek: Unknown value for 'whence'");
+    }
+
+    windowsoffset.QuadPart = offset;
+    if (!SetFilePointerEx(context->hidden.windowsio.h, windowsoffset, &windowsoffset, windowswhence)) {
+        return WIN_SetError("windows_file_seek");
+    }
+    return windowsoffset.QuadPart;
+}
+
+static size_t SDLCALL
+windows_file_read(SDL_RWops * context, void *ptr, size_t size, size_t maxnum)
+{
+    size_t total_need;
+    size_t total_read = 0;
+    size_t read_ahead;
+    DWORD byte_read;
+
+    total_need = size * maxnum;
+
+    if (!context || context->hidden.windowsio.h == INVALID_HANDLE_VALUE
+        || !total_need)
+        return 0;
+
+    if (context->hidden.windowsio.buffer.left > 0) {
+        void *data = (char *) context->hidden.windowsio.buffer.data +
+            context->hidden.windowsio.buffer.size -
+            context->hidden.windowsio.buffer.left;
+        read_ahead =
+            SDL_min(total_need, context->hidden.windowsio.buffer.left);
+        SDL_memcpy(ptr, data, read_ahead);
+        context->hidden.windowsio.buffer.left -= read_ahead;
+
+        if (read_ahead == total_need) {
+            return maxnum;
+        }
+        ptr = (char *) ptr + read_ahead;
+        total_need -= read_ahead;
+        total_read += read_ahead;
+    }
+
+    if (total_need < READAHEAD_BUFFER_SIZE) {
+        if (!ReadFile
+            (context->hidden.windowsio.h, context->hidden.windowsio.buffer.data,
+             READAHEAD_BUFFER_SIZE, &byte_read, NULL)) {
+            SDL_Error(SDL_EFREAD);
+            return 0;
+        }
+        read_ahead = SDL_min(total_need, (int) byte_read);
+        SDL_memcpy(ptr, context->hidden.windowsio.buffer.data, read_ahead);
+        context->hidden.windowsio.buffer.size = byte_read;
+        context->hidden.windowsio.buffer.left = byte_read - read_ahead;
+        total_read += read_ahead;
+    } else {
+        if (!ReadFile
+            (context->hidden.windowsio.h, ptr, (DWORD)total_need, &byte_read, NULL)) {
+            SDL_Error(SDL_EFREAD);
+            return 0;
+        }
+        total_read += byte_read;
+    }
+    return (total_read / size);
+}
+
+static size_t SDLCALL
+windows_file_write(SDL_RWops * context, const void *ptr, size_t size,
+                 size_t num)
+{
+
+    size_t total_bytes;
+    DWORD byte_written;
+    size_t nwritten;
+
+    total_bytes = size * num;
+
+    if (!context || context->hidden.windowsio.h == INVALID_HANDLE_VALUE
+        || total_bytes <= 0 || !size)
+        return 0;
+
+    if (context->hidden.windowsio.buffer.left) {
+        SetFilePointer(context->hidden.windowsio.h,
+                       -(LONG)context->hidden.windowsio.buffer.left, NULL,
+                       FILE_CURRENT);
+        context->hidden.windowsio.buffer.left = 0;
+    }
+
+    /* if in append mode, we must go to the EOF before write */
+    if (context->hidden.windowsio.append) {
+        if (SetFilePointer(context->hidden.windowsio.h, 0L, NULL, FILE_END) ==
+            INVALID_SET_FILE_POINTER) {
+            SDL_Error(SDL_EFWRITE);
+            return 0;
+        }
+    }
+
+    if (!WriteFile
+        (context->hidden.windowsio.h, ptr, (DWORD)total_bytes, &byte_written, NULL)) {
+        SDL_Error(SDL_EFWRITE);
+        return 0;
+    }
+
+    nwritten = byte_written / size;
+    return nwritten;
+}
+
+static int SDLCALL
+windows_file_close(SDL_RWops * context)
+{
+
+    if (context) {
+        if (context->hidden.windowsio.h != INVALID_HANDLE_VALUE) {
+            CloseHandle(context->hidden.windowsio.h);
+            context->hidden.windowsio.h = INVALID_HANDLE_VALUE;   /* to be sure */
+        }
+        SDL_free(context->hidden.windowsio.buffer.data);
+        context->hidden.windowsio.buffer.data = NULL;
+        SDL_FreeRW(context);
+    }
+    return (0);
+}
+#endif /* __WIN32__ */
+
+#ifdef HAVE_STDIO_H
+
+/* Functions to read/write stdio file pointers */
+
+static Sint64 SDLCALL
+stdio_size(SDL_RWops * context)
+{
+    Sint64 pos, size;
+
+    pos = SDL_RWseek(context, 0, RW_SEEK_CUR);
+    if (pos < 0) {
+        return -1;
+    }
+    size = SDL_RWseek(context, 0, RW_SEEK_END);
+
+    SDL_RWseek(context, pos, RW_SEEK_SET);
+    return size;
+}
+
+static Sint64 SDLCALL
+stdio_seek(SDL_RWops * context, Sint64 offset, int whence)
+{
+#ifdef HAVE_FSEEKO64
+    if (fseeko64(context->hidden.stdio.fp, (off64_t)offset, whence) == 0) {
+        return ftello64(context->hidden.stdio.fp);
+    }
+#elif defined(HAVE_FSEEKO)
+    if (fseeko(context->hidden.stdio.fp, (off_t)offset, whence) == 0) {
+        return ftello(context->hidden.stdio.fp);
+    }
+#elif defined(HAVE__FSEEKI64)
+    if (_fseeki64(context->hidden.stdio.fp, offset, whence) == 0) {
+        return _ftelli64(context->hidden.stdio.fp);
+    }
+#else
+    if (fseek(context->hidden.stdio.fp, offset, whence) == 0) {
+        return (ftell(context->hidden.stdio.fp));
+    }
+#endif
+    return SDL_Error(SDL_EFSEEK);
+}
+
+static size_t SDLCALL
+stdio_read(SDL_RWops * context, void *ptr, size_t size, size_t maxnum)
+{
+    size_t nread;
+
+    nread = fread(ptr, size, maxnum, context->hidden.stdio.fp);
+    if (nread == 0 && ferror(context->hidden.stdio.fp)) {
+        SDL_Error(SDL_EFREAD);
+    }
+    return (nread);
+}
+
+static size_t SDLCALL
+stdio_write(SDL_RWops * context, const void *ptr, size_t size, size_t num)
+{
+    size_t nwrote;
+
+    nwrote = fwrite(ptr, size, num, context->hidden.stdio.fp);
+    if (nwrote == 0 && ferror(context->hidden.stdio.fp)) {
+        SDL_Error(SDL_EFWRITE);
+    }
+    return (nwrote);
+}
+
+static int SDLCALL
+stdio_close(SDL_RWops * context)
+{
+    int status = 0;
+    if (context) {
+        if (context->hidden.stdio.autoclose) {
+            /* WARNING:  Check the return value here! */
+            if (fclose(context->hidden.stdio.fp) != 0) {
+                status = SDL_Error(SDL_EFWRITE);
+            }
+        }
+        SDL_FreeRW(context);
+    }
+    return status;
+}
+#endif /* !HAVE_STDIO_H */
+
+/* Functions to read/write memory pointers */
+
+static Sint64 SDLCALL
+mem_size(SDL_RWops * context)
+{
+    return (Sint64)(context->hidden.mem.stop - context->hidden.mem.base);
+}
+
+static Sint64 SDLCALL
+mem_seek(SDL_RWops * context, Sint64 offset, int whence)
+{
+    Uint8 *newpos;
+
+    switch (whence) {
+    case RW_SEEK_SET:
+        newpos = context->hidden.mem.base + offset;
+        break;
+    case RW_SEEK_CUR:
+        newpos = context->hidden.mem.here + offset;
+        break;
+    case RW_SEEK_END:
+        newpos = context->hidden.mem.stop + offset;
+        break;
+    default:
+        return SDL_SetError("Unknown value for 'whence'");
+    }
+    if (newpos < context->hidden.mem.base) {
+        newpos = context->hidden.mem.base;
+    }
+    if (newpos > context->hidden.mem.stop) {
+        newpos = context->hidden.mem.stop;
+    }
+    context->hidden.mem.here = newpos;
+    return (Sint64)(context->hidden.mem.here - context->hidden.mem.base);
+}
+
+static size_t SDLCALL
+mem_read(SDL_RWops * context, void *ptr, size_t size, size_t maxnum)
+{
+    size_t total_bytes;
+    size_t mem_available;
+
+    total_bytes = (maxnum * size);
+    if ((maxnum <= 0) || (size <= 0)
+        || ((total_bytes / maxnum) != (size_t) size)) {
+        return 0;
+    }
+
+    mem_available = (context->hidden.mem.stop - context->hidden.mem.here);
+    if (total_bytes > mem_available) {
+        total_bytes = mem_available;
+    }
+
+    SDL_memcpy(ptr, context->hidden.mem.here, total_bytes);
+    context->hidden.mem.here += total_bytes;
+
+    return (total_bytes / size);
+}
+
+static size_t SDLCALL
+mem_write(SDL_RWops * context, const void *ptr, size_t size, size_t num)
+{
+    if ((context->hidden.mem.here + (num * size)) > context->hidden.mem.stop) {
+        num = (context->hidden.mem.stop - context->hidden.mem.here) / size;
+    }
+    SDL_memcpy(context->hidden.mem.here, ptr, num * size);
+    context->hidden.mem.here += num * size;
+    return (num);
+}
+
+static size_t SDLCALL
+mem_writeconst(SDL_RWops * context, const void *ptr, size_t size, size_t num)
+{
+    SDL_SetError("Can't write to read-only memory");
+    return (0);
+}
+
+static int SDLCALL
+mem_close(SDL_RWops * context)
+{
+    if (context) {
+        SDL_FreeRW(context);
+    }
+    return (0);
+}
+
+
+/* Functions to create SDL_RWops structures from various data sources */
+
+SDL_RWops *
+SDL_RWFromFile(const char *file, const char *mode)
+{
+    SDL_RWops *rwops = NULL;
+    if (!file || !*file || !mode || !*mode) {
+        SDL_SetError("SDL_RWFromFile(): No file or no mode specified");
+        return NULL;
+    }
+#if defined(ANDROID)
+#ifdef HAVE_STDIO_H
+    /* Try to open the file on the filesystem first */
+    if (*file == '/') {
+        FILE *fp = fopen(file, mode);
+        if (fp) {
+            return SDL_RWFromFP(fp, 1);
+        }
+    } else {
+        /* Try opening it from internal storage if it's a relative path */
+        char *path;
+        FILE *fp;
+
+        path = SDL_stack_alloc(char, PATH_MAX);
+        if (path) {
+            SDL_snprintf(path, PATH_MAX, "%s/%s",
+                         SDL_AndroidGetInternalStoragePath(), file);
+            fp = fopen(path, mode);
+            SDL_stack_free(path);
+            if (fp) {
+                return SDL_RWFromFP(fp, 1);
+            }
+        }
+    }
+#endif /* HAVE_STDIO_H */
+
+    /* Try to open the file from the asset system */
+    rwops = SDL_AllocRW();
+    if (!rwops)
+        return NULL;            /* SDL_SetError already setup by SDL_AllocRW() */
+    if (Android_JNI_FileOpen(rwops, file, mode) < 0) {
+        SDL_FreeRW(rwops);
+        return NULL;
+    }
+    rwops->size = Android_JNI_FileSize;
+    rwops->seek = Android_JNI_FileSeek;
+    rwops->read = Android_JNI_FileRead;
+    rwops->write = Android_JNI_FileWrite;
+    rwops->close = Android_JNI_FileClose;
+    rwops->type = SDL_RWOPS_JNIFILE;
+
+#elif defined(__WIN32__)
+    rwops = SDL_AllocRW();
+    if (!rwops)
+        return NULL;            /* SDL_SetError already setup by SDL_AllocRW() */
+    if (windows_file_open(rwops, file, mode) < 0) {
+        SDL_FreeRW(rwops);
+        return NULL;
+    }
+    rwops->size = windows_file_size;
+    rwops->seek = windows_file_seek;
+    rwops->read = windows_file_read;
+    rwops->write = windows_file_write;
+    rwops->close = windows_file_close;
+    rwops->type = SDL_RWOPS_WINFILE;
+
+#elif HAVE_STDIO_H
+    {
+        #ifdef __APPLE__
+        FILE *fp = SDL_OpenFPFromBundleOrFallback(file, mode);
+        #elif __WINRT__
+        FILE *fp = NULL;
+        fopen_s(&fp, file, mode);
+        #else
+        FILE *fp = fopen(file, mode);
+        #endif
+        if (fp == NULL) {
+            SDL_SetError("Couldn't open %s", file);
+        } else {
+            rwops = SDL_RWFromFP(fp, 1);
+        }
+    }
+#else
+    SDL_SetError("SDL not compiled with stdio support");
+#endif /* !HAVE_STDIO_H */
+
+    return (rwops);
+}
+
+#ifdef HAVE_STDIO_H
+SDL_RWops *
+SDL_RWFromFP(FILE * fp, SDL_bool autoclose)
+{
+    SDL_RWops *rwops = NULL;
+
+    rwops = SDL_AllocRW();
+    if (rwops != NULL) {
+        rwops->size = stdio_size;
+        rwops->seek = stdio_seek;
+        rwops->read = stdio_read;
+        rwops->write = stdio_write;
+        rwops->close = stdio_close;
+        rwops->hidden.stdio.fp = fp;
+        rwops->hidden.stdio.autoclose = autoclose;
+        rwops->type = SDL_RWOPS_STDFILE;
+    }
+    return (rwops);
+}
+#else
+SDL_RWops *
+SDL_RWFromFP(void * fp, SDL_bool autoclose)
+{
+    SDL_SetError("SDL not compiled with stdio support");
+    return NULL;
+}
+#endif /* HAVE_STDIO_H */
+
+SDL_RWops *
+SDL_RWFromMem(void *mem, int size)
+{
+    SDL_RWops *rwops = NULL;
+    if (!mem) {
+      SDL_InvalidParamError("mem");
+      return (rwops);
+    }
+    if (!size) {
+      SDL_InvalidParamError("size");
+      return (rwops);
+    }
+
+    rwops = SDL_AllocRW();
+    if (rwops != NULL) {
+        rwops->size = mem_size;
+        rwops->seek = mem_seek;
+        rwops->read = mem_read;
+        rwops->write = mem_write;
+        rwops->close = mem_close;
+        rwops->hidden.mem.base = (Uint8 *) mem;
+        rwops->hidden.mem.here = rwops->hidden.mem.base;
+        rwops->hidden.mem.stop = rwops->hidden.mem.base + size;
+        rwops->type = SDL_RWOPS_MEMORY;
+    }
+    return (rwops);
+}
+
+SDL_RWops *
+SDL_RWFromConstMem(const void *mem, int size)
+{
+    SDL_RWops *rwops = NULL;
+    if (!mem) {
+      SDL_InvalidParamError("mem");
+      return (rwops);
+    }
+    if (!size) {
+      SDL_InvalidParamError("size");
+      return (rwops);
+    }
+
+    rwops = SDL_AllocRW();
+    if (rwops != NULL) {
+        rwops->size = mem_size;
+        rwops->seek = mem_seek;
+        rwops->read = mem_read;
+        rwops->write = mem_writeconst;
+        rwops->close = mem_close;
+        rwops->hidden.mem.base = (Uint8 *) mem;
+        rwops->hidden.mem.here = rwops->hidden.mem.base;
+        rwops->hidden.mem.stop = rwops->hidden.mem.base + size;
+        rwops->type = SDL_RWOPS_MEMORY_RO;
+    }
+    return (rwops);
+}
+
+SDL_RWops *
+SDL_AllocRW(void)
+{
+    SDL_RWops *area;
+
+    area = (SDL_RWops *) SDL_malloc(sizeof *area);
+    if (area == NULL) {
+        SDL_OutOfMemory();
+    } else {
+        area->type = SDL_RWOPS_UNKNOWN;
+    }
+    return (area);
+}
+
+void
+SDL_FreeRW(SDL_RWops * area)
+{
+    SDL_free(area);
+}
+
+/* Functions for dynamically reading and writing endian-specific values */
+
+Uint8
+SDL_ReadU8(SDL_RWops * src)
+{
+    Uint8 value = 0;
+
+    SDL_RWread(src, &value, (sizeof value), 1);
+    return value;
+}
+
+Uint16
+SDL_ReadLE16(SDL_RWops * src)
+{
+    Uint16 value = 0;
+
+    SDL_RWread(src, &value, (sizeof value), 1);
+    return (SDL_SwapLE16(value));
+}
+
+Uint16
+SDL_ReadBE16(SDL_RWops * src)
+{
+    Uint16 value = 0;
+
+    SDL_RWread(src, &value, (sizeof value), 1);
+    return (SDL_SwapBE16(value));
+}
+
+Uint32
+SDL_ReadLE32(SDL_RWops * src)
+{
+    Uint32 value = 0;
+
+    SDL_RWread(src, &value, (sizeof value), 1);
+    return (SDL_SwapLE32(value));
+}
+
+Uint32
+SDL_ReadBE32(SDL_RWops * src)
+{
+    Uint32 value = 0;
+
+    SDL_RWread(src, &value, (sizeof value), 1);
+    return (SDL_SwapBE32(value));
+}
+
+Uint64
+SDL_ReadLE64(SDL_RWops * src)
+{
+    Uint64 value = 0;
+
+    SDL_RWread(src, &value, (sizeof value), 1);
+    return (SDL_SwapLE64(value));
+}
+
+Uint64
+SDL_ReadBE64(SDL_RWops * src)
+{
+    Uint64 value = 0;
+
+    SDL_RWread(src, &value, (sizeof value), 1);
+    return (SDL_SwapBE64(value));
+}
+
+size_t
+SDL_WriteU8(SDL_RWops * dst, Uint8 value)
+{
+    return (SDL_RWwrite(dst, &value, (sizeof value), 1));
+}
+
+size_t
+SDL_WriteLE16(SDL_RWops * dst, Uint16 value)
+{
+    value = SDL_SwapLE16(value);
+    return (SDL_RWwrite(dst, &value, (sizeof value), 1));
+}
+
+size_t
+SDL_WriteBE16(SDL_RWops * dst, Uint16 value)
+{
+    value = SDL_SwapBE16(value);
+    return (SDL_RWwrite(dst, &value, (sizeof value), 1));
+}
+
+size_t
+SDL_WriteLE32(SDL_RWops * dst, Uint32 value)
+{
+    value = SDL_SwapLE32(value);
+    return (SDL_RWwrite(dst, &value, (sizeof value), 1));
+}
+
+size_t
+SDL_WriteBE32(SDL_RWops * dst, Uint32 value)
+{
+    value = SDL_SwapBE32(value);
+    return (SDL_RWwrite(dst, &value, (sizeof value), 1));
+}
+
+size_t
+SDL_WriteLE64(SDL_RWops * dst, Uint64 value)
+{
+    value = SDL_SwapLE64(value);
+    return (SDL_RWwrite(dst, &value, (sizeof value), 1));
+}
+
+size_t
+SDL_WriteBE64(SDL_RWops * dst, Uint64 value)
+{
+    value = SDL_SwapBE64(value);
+    return (SDL_RWwrite(dst, &value, (sizeof value), 1));
+}
+
+/* vi: set ts=4 sw=4 expandtab: */
--- a/src/filesystem/winrt/SDL_sysfilesystem.cpp	Tue Mar 04 19:49:11 2014 -0500
+++ b/src/filesystem/winrt/SDL_sysfilesystem.cpp	Sun Mar 09 11:06:11 2014 -0700
@@ -1,154 +1,154 @@
-/* TODO, WinRT: include copyright info in SDL_winrtpaths.cpp
-   TODO, WinRT: remove the need to compile this with C++/CX (/ZW) extensions, and if possible, without C++ at all
-*/
-
-#include "SDL_config.h"
-
-#ifdef __WINRT__
-
-extern "C" {
-#include "SDL_filesystem.h"
-#include "SDL_error.h"
-#include "SDL_stdinc.h"
-#include "SDL_system.h"
-#include "../../core/windows/SDL_windows.h"
-}
-
-#include <string>
-#include <unordered_map>
-
-using namespace std;
-using namespace Windows::Storage;
-
-extern "C" const wchar_t *
-SDL_WinRTGetFSPathUNICODE(SDL_WinRT_Path pathType)
-{
-    switch (pathType) {
-        case SDL_WINRT_PATH_INSTALLED_LOCATION:
-        {
-            static wstring path;
-            if (path.empty()) {
-                path = Windows::ApplicationModel::Package::Current->InstalledLocation->Path->Data();
-            }
-            return path.c_str();
-        }
-
-        case SDL_WINRT_PATH_LOCAL_FOLDER:
-        {
-            static wstring path;
-            if (path.empty()) {
-                path = ApplicationData::Current->LocalFolder->Path->Data();
-            }
-            return path.c_str();
-        }
-
-#if WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP
-        case SDL_WINRT_PATH_ROAMING_FOLDER:
-        {
-            static wstring path;
-            if (path.empty()) {
-                path = ApplicationData::Current->RoamingFolder->Path->Data();
-            }
-            return path.c_str();
-        }
-
-        case SDL_WINRT_PATH_TEMP_FOLDER:
-        {
-            static wstring path;
-            if (path.empty()) {
-                path = ApplicationData::Current->TemporaryFolder->Path->Data();
-            }
-            return path.c_str();
-        }
-#endif
-
-        default:
-            break;
-    }
-
-    SDL_Unsupported();
-    return NULL;
-}
-
-extern "C" const char *
-SDL_WinRTGetFSPathUTF8(SDL_WinRT_Path pathType)
-{
-    typedef unordered_map<SDL_WinRT_Path, string> UTF8PathMap;
-    static UTF8PathMap utf8Paths;
-
-    UTF8PathMap::iterator searchResult = utf8Paths.find(pathType);
-    if (searchResult != utf8Paths.end()) {
-        return searchResult->second.c_str();
-    }
-
-    const wchar_t * ucs2Path = SDL_WinRTGetFSPathUNICODE(pathType);
-    if (!ucs2Path) {
-        return NULL;
-    }
-
-    char * utf8Path = WIN_StringToUTF8(ucs2Path);
-    utf8Paths[pathType] = utf8Path;
-    SDL_free(utf8Path);
-    return utf8Paths[pathType].c_str();
-}
-
-extern "C" char *
-SDL_GetBasePath(void)
-{
-    const char * srcPath = SDL_WinRTGetFSPathUTF8(SDL_WINRT_PATH_INSTALLED_LOCATION);
-    size_t destPathLen;
-    char * destPath = NULL;
-
-    if (!srcPath) {
-        SDL_SetError("Couldn't locate our basepath: %s", SDL_GetError());
-        return NULL;
-    }
-
-    destPathLen = SDL_strlen(srcPath) + 2;
-    destPath = (char *) SDL_malloc(destPathLen);
-    if (!destPath) {
-        SDL_OutOfMemory();
-        return NULL;
-    }
-
-    SDL_snprintf(destPath, destPathLen, "%s\\", srcPath);
-    return destPath;
-}
-
-extern "C" char *
-SDL_GetPrefPath(const char *org, const char *app)
-{
-    /* WinRT note: The 'SHGetFolderPath' API that is used in Windows 7 and
-     * earlier is not available on WinRT or Windows Phone.  WinRT provides
-     * a similar API, but SHGetFolderPath can't be called, at least not
-     * without violating Microsoft's app-store requirements.
-     */
-
-#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
-    /* A 'Roaming' folder is not available in Windows Phone 8, however a 'Local' folder is. */
-    const char * srcPath = SDL_WinRTGetFSPathUTF8(SDL_WINRT_PATH_LOCAL_FOLDER);
-#else
-    /* A 'Roaming' folder is available on Windows 8 and 8.1.  Use that. */
-    const char * srcPath = SDL_WinRTGetFSPathUTF8(SDL_WINRT_PATH_ROAMING_FOLDER);
-#endif
-
-    size_t destPathLen;
-    char * destPath = NULL;
-
-    if (!srcPath) {
-        SDL_SetError("Couldn't locate our basepath: %s", SDL_GetError());
-        return NULL;
-    }
-
-    destPathLen = SDL_strlen(srcPath) + SDL_strlen(org) + SDL_strlen(app) + 4;
-    destPath = (char *) SDL_malloc(destPathLen);
-    if (!destPath) {
-        SDL_OutOfMemory();
-        return NULL;
-    }
-
-    SDL_snprintf(destPath, destPathLen, "%s\\%s\\%s\\", srcPath, org, app);
-    return destPath;
-}
-
-#endif /* __WINRT__ */
+/* TODO, WinRT: include copyright info in SDL_winrtpaths.cpp
+   TODO, WinRT: remove the need to compile this with C++/CX (/ZW) extensions, and if possible, without C++ at all
+*/
+
+#include "SDL_config.h"
+
+#ifdef __WINRT__
+
+extern "C" {
+#include "SDL_filesystem.h"
+#include "SDL_error.h"
+#include "SDL_stdinc.h"
+#include "SDL_system.h"
+#include "../../core/windows/SDL_windows.h"
+}
+
+#include <string>
+#include <unordered_map>
+
+using namespace std;
+using namespace Windows::Storage;
+
+extern "C" const wchar_t *
+SDL_WinRTGetFSPathUNICODE(SDL_WinRT_Path pathType)
+{
+    switch (pathType) {
+        case SDL_WINRT_PATH_INSTALLED_LOCATION:
+        {
+            static wstring path;
+            if (path.empty()) {
+                path = Windows::ApplicationModel::Package::Current->InstalledLocation->Path->Data();
+            }
+            return path.c_str();
+        }
+
+        case SDL_WINRT_PATH_LOCAL_FOLDER:
+        {
+            static wstring path;
+            if (path.empty()) {
+                path = ApplicationData::Current->LocalFolder->Path->Data();
+            }
+            return path.c_str();
+        }
+
+#if WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP
+        case SDL_WINRT_PATH_ROAMING_FOLDER:
+        {
+            static wstring path;
+            if (path.empty()) {
+                path = ApplicationData::Current->RoamingFolder->Path->Data();
+            }
+            return path.c_str();
+        }
+
+        case SDL_WINRT_PATH_TEMP_FOLDER:
+        {
+            static wstring path;
+            if (path.empty()) {
+                path = ApplicationData::Current->TemporaryFolder->Path->Data();
+            }
+            return path.c_str();
+        }
+#endif
+
+        default:
+            break;
+    }
+
+    SDL_Unsupported();
+    return NULL;
+}
+
+extern "C" const char *
+SDL_WinRTGetFSPathUTF8(SDL_WinRT_Path pathType)
+{
+    typedef unordered_map<SDL_WinRT_Path, string> UTF8PathMap;
+    static UTF8PathMap utf8Paths;
+
+    UTF8PathMap::iterator searchResult = utf8Paths.find(pathType);
+    if (searchResult != utf8Paths.end()) {
+        return searchResult->second.c_str();
+    }
+
+    const wchar_t * ucs2Path = SDL_WinRTGetFSPathUNICODE(pathType);
+    if (!ucs2Path) {
+        return NULL;
+    }
+
+    char * utf8Path = WIN_StringToUTF8(ucs2Path);
+    utf8Paths[pathType] = utf8Path;
+    SDL_free(utf8Path);
+    return utf8Paths[pathType].c_str();
+}
+
+extern "C" char *
+SDL_GetBasePath(void)
+{
+    const char * srcPath = SDL_WinRTGetFSPathUTF8(SDL_WINRT_PATH_INSTALLED_LOCATION);
+    size_t destPathLen;
+    char * destPath = NULL;
+
+    if (!srcPath) {
+        SDL_SetError("Couldn't locate our basepath: %s", SDL_GetError());
+        return NULL;
+    }
+
+    destPathLen = SDL_strlen(srcPath) + 2;
+    destPath = (char *) SDL_malloc(destPathLen);
+    if (!destPath) {
+        SDL_OutOfMemory();
+        return NULL;
+    }
+
+    SDL_snprintf(destPath, destPathLen, "%s\\", srcPath);
+    return destPath;
+}
+
+extern "C" char *
+SDL_GetPrefPath(const char *org, const char *app)
+{
+    /* WinRT note: The 'SHGetFolderPath' API that is used in Windows 7 and
+     * earlier is not available on WinRT or Windows Phone.  WinRT provides
+     * a similar API, but SHGetFolderPath can't be called, at least not
+     * without violating Microsoft's app-store requirements.
+     */
+
+#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
+    /* A 'Roaming' folder is not available in Windows Phone 8, however a 'Local' folder is. */
+    const char * srcPath = SDL_WinRTGetFSPathUTF8(SDL_WINRT_PATH_LOCAL_FOLDER);
+#else
+    /* A 'Roaming' folder is available on Windows 8 and 8.1.  Use that. */
+    const char * srcPath = SDL_WinRTGetFSPathUTF8(SDL_WINRT_PATH_ROAMING_FOLDER);
+#endif
+
+    size_t destPathLen;
+    char * destPath = NULL;
+
+    if (!srcPath) {
+        SDL_SetError("Couldn't locate our basepath: %s", SDL_GetError());
+        return NULL;
+    }
+
+    destPathLen = SDL_strlen(srcPath) + SDL_strlen(org) + SDL_strlen(app) + 4;
+    destPath = (char *) SDL_malloc(destPathLen);
+    if (!destPath) {
+        SDL_OutOfMemory();
+        return NULL;
+    }
+
+    SDL_snprintf(destPath, destPathLen, "%s\\%s\\%s\\", srcPath, org, app);
+    return destPath;
+}
+
+#endif /* __WINRT__ */
--- a/src/joystick/SDL_gamecontroller.c	Tue Mar 04 19:49:11 2014 -0500
+++ b/src/joystick/SDL_gamecontroller.c	Sun Mar 09 11:06:11 2014 -0700
@@ -1,1247 +1,1247 @@
-/*
-  Simple DirectMedia Layer
-  Copyright (C) 1997-2013 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 "SDL_config.h"
-
-/* This is the game controller API for Simple DirectMedia Layer */
-
-#include "SDL_events.h"
-#include "SDL_assert.h"
-#include "SDL_sysjoystick.h"
-#include "SDL_hints.h"
-#include "SDL_gamecontrollerdb.h"
-
-#if !SDL_EVENTS_DISABLED
-#include "../events/SDL_events_c.h"
-#endif
-#define ABS(_x) ((_x) < 0 ? -(_x) : (_x))
-
-
-/* a list of currently opened game controllers */
-static SDL_GameController *SDL_gamecontrollers = NULL;
-
-/* keep track of the hat and mask value that transforms this hat movement into a button/axis press */
-struct _SDL_HatMapping
-{
-    int hat;
-    Uint8 mask;
-};
-
-#define k_nMaxReverseEntries 20
-
-/**
- * We are encoding the "HAT" as 0xhm. where h == hat ID and m == mask
- * MAX 4 hats supported
- */
-#define k_nMaxHatEntries 0x3f + 1
-
-/* our in memory mapping db between joystick objects and controller mappings */
-struct _SDL_ControllerMapping
-{
-    SDL_JoystickGUID guid;
-    const char *name;
-
-    /* mapping of axis/button id to controller version */
-    int axes[SDL_CONTROLLER_AXIS_MAX];
-    int buttonasaxis[SDL_CONTROLLER_AXIS_MAX];
-
-    int buttons[SDL_CONTROLLER_BUTTON_MAX];
-    int axesasbutton[SDL_CONTROLLER_BUTTON_MAX];
-    struct _SDL_HatMapping hatasbutton[SDL_CONTROLLER_BUTTON_MAX];
-
-    /* reverse mapping, joystick indices to buttons */
-    SDL_GameControllerAxis raxes[k_nMaxReverseEntries];
-    SDL_GameControllerAxis rbuttonasaxis[k_nMaxReverseEntries];
-
-    SDL_GameControllerButton rbuttons[k_nMaxReverseEntries];
-    SDL_GameControllerButton raxesasbutton[k_nMaxReverseEntries];
-    SDL_GameControllerButton rhatasbutton[k_nMaxHatEntries];
-
-};
-
-
-/* our hard coded list of mapping support */
-typedef struct _ControllerMapping_t
-{
-    SDL_JoystickGUID guid;
-    char *name;
-    char *mapping;
-    struct _ControllerMapping_t *next;
-} ControllerMapping_t;
-
-static ControllerMapping_t *s_pSupportedControllers = NULL;
-#if defined(SDL_JOYSTICK_DINPUT) || defined(SDL_JOYSTICK_XINPUT)
-static ControllerMapping_t *s_pXInputMapping = NULL;
-#endif
-
-/* The SDL game controller structure */
-struct _SDL_GameController
-{
-    SDL_Joystick *joystick; /* underlying joystick device */
-    int ref_count;
-    Uint8 hatState[4]; /* the current hat state for this controller */
-    struct _SDL_ControllerMapping mapping; /* the mapping object for this controller */
-    struct _SDL_GameController *next; /* pointer to next game controller we have allocated */
-};
-
-
-int SDL_PrivateGameControllerAxis(SDL_GameController * gamecontroller, SDL_GameControllerAxis axis, Sint16 value);
-int SDL_PrivateGameControllerButton(SDL_GameController * gamecontroller, SDL_GameControllerButton button, Uint8 state);
-
-/*
- * Event filter to fire controller events from joystick ones
- */
-int SDL_GameControllerEventWatcher(void *userdata, SDL_Event * event)
-{
-    switch( event->type )
-    {
-    case SDL_JOYAXISMOTION:
-        {
-            SDL_GameController *controllerlist;
-
-            if ( event->jaxis.axis >= k_nMaxReverseEntries ) break;
-
-            controllerlist = SDL_gamecontrollers;
-            while ( controllerlist )
-            {
-                if ( controllerlist->joystick->instance_id == event->jaxis.which )
-                {
-                    if ( controllerlist->mapping.raxes[event->jaxis.axis] >= 0 ) /* simple axis to axis, send it through */
-                    {
-                        SDL_GameControllerAxis axis = controllerlist->mapping.raxes[event->jaxis.axis];
-                        Sint16 value = event->jaxis.value;
-                        switch (axis)
-                        {
-                            case SDL_CONTROLLER_AXIS_TRIGGERLEFT:
-                            case SDL_CONTROLLER_AXIS_TRIGGERRIGHT:
-                                /* Shift it to be 0 - 32767. */
-                                value = value / 2 + 16384;
-                            default:
-                                break;
-                        }
-                        SDL_PrivateGameControllerAxis( controllerlist, axis, value );
-                    }
-                    else if ( controllerlist->mapping.raxesasbutton[event->jaxis.axis] >= 0 ) /* simulate an axis as a button */
-                    {
-                        SDL_PrivateGameControllerButton( controllerlist, controllerlist->mapping.raxesasbutton[event->jaxis.axis], ABS(event->jaxis.value) > 32768/2 ? SDL_PRESSED : SDL_RELEASED );
-                    }
-                    break;
-                }
-                controllerlist = controllerlist->next;
-            }
-        }
-        break;
-    case SDL_JOYBUTTONDOWN:
-    case SDL_JOYBUTTONUP:
-        {
-            SDL_GameController *controllerlist;
-
-            if ( event->jbutton.button >= k_nMaxReverseEntries ) break;
-
-            controllerlist = SDL_gamecontrollers;
-            while ( controllerlist )
-            {
-                if ( controllerlist->joystick->instance_id == event->jbutton.which )
-                {
-                    if ( controllerlist->mapping.rbuttons[event->jbutton.button] >= 0 ) /* simple button as button */
-                    {
-                        SDL_PrivateGameControllerButton( controllerlist, controllerlist->mapping.rbuttons[event->jbutton.button], event->jbutton.state );
-                    }
-                    else if ( controllerlist->mapping.rbuttonasaxis[event->jbutton.button] >= 0 ) /* an button pretending to be an axis */
-                    {
-                        SDL_PrivateGameControllerAxis( controllerlist, controllerlist->mapping.rbuttonasaxis[event->jbutton.button], event->jbutton.state > 0 ? 32767 : 0 );
-                    }
-                    break;
-                }
-                controllerlist = controllerlist->next;
-            }
-        }
-        break;
-    case SDL_JOYHATMOTION:
-        {
-            SDL_GameController *controllerlist;
-
-            if ( event->jhat.hat >= 4 ) break;
-
-            controllerlist = SDL_gamecontrollers;
-            while ( controllerlist )
-            {
-                if ( controllerlist->joystick->instance_id == event->jhat.which )
-                {
-                    Uint8 bSame = controllerlist->hatState[event->jhat.hat] & event->jhat.value;
-                    /* Get list of removed bits (button release) */
-                    Uint8 bChanged = controllerlist->hatState[event->jhat.hat] ^ bSame;
-                    /* the hat idx in the high nibble */
-                    int bHighHat = event->jhat.hat << 4;
-
-                    if ( bChanged & SDL_HAT_DOWN )
-                        SDL_PrivateGameControllerButton( controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_DOWN], SDL_RELEASED );
-                    if ( bChanged & SDL_HAT_UP )
-                        SDL_PrivateGameControllerButton( controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_UP], SDL_RELEASED );
-                    if ( bChanged & SDL_HAT_LEFT )
-                        SDL_PrivateGameControllerButton( controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_LEFT], SDL_RELEASED );
-                    if ( bChanged & SDL_HAT_RIGHT )
-                        SDL_PrivateGameControllerButton( controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_RIGHT], SDL_RELEASED );
-
-                    /* Get list of added bits (button press) */
-                    bChanged = event->jhat.value ^ bSame;
-
-                    if ( bChanged & SDL_HAT_DOWN )
-                        SDL_PrivateGameControllerButton( controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_DOWN], SDL_PRESSED );
-                    if ( bChanged & SDL_HAT_UP )
-                        SDL_PrivateGameControllerButton( controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_UP], SDL_PRESSED );
-                    if ( bChanged & SDL_HAT_LEFT )
-                        SDL_PrivateGameControllerButton( controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_LEFT], SDL_PRESSED );
-                    if ( bChanged & SDL_HAT_RIGHT )
-                        SDL_PrivateGameControllerButton( controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_RIGHT], SDL_PRESSED );
-
-                    /* update our state cache */
-                    controllerlist->hatState[event->jhat.hat] = event->jhat.value;
-
-                    break;
-                }
-                controllerlist = controllerlist->next;
-            }
-        }
-        break;
-    case SDL_JOYDEVICEADDED:
-        {
-            if ( SDL_IsGameController(event->jdevice.which ) )
-            {
-                SDL_Event deviceevent;
-                deviceevent.type = SDL_CONTROLLERDEVICEADDED;
-                deviceevent.cdevice.which = event->jdevice.which;
-                SDL_PushEvent(&deviceevent);
-            }
-        }
-        break;
-    case SDL_JOYDEVICEREMOVED:
-        {
-            SDL_GameController *controllerlist = SDL_gamecontrollers;
-            while ( controllerlist )
-            {
-                if ( controllerlist->joystick->instance_id == event->jdevice.which )
-                {
-                    SDL_Event deviceevent;
-                    deviceevent.type = SDL_CONTROLLERDEVICEREMOVED;
-                    deviceevent.cdevice.which = event->jdevice.which;
-                    SDL_PushEvent(&deviceevent);
-                    break;
-                }
-                controllerlist = controllerlist->next;
-            }
-        }
-        break;
-    default:
-        break;
-    }
-
-    return 1;
-}
-
-/*
- * Helper function to scan the mappings database for a controller with the specified GUID
- */
-ControllerMapping_t *SDL_PrivateGetControllerMappingForGUID(SDL_JoystickGUID *guid)
-{
-    ControllerMapping_t *pSupportedController = s_pSupportedControllers;
-    while ( pSupportedController )
-    {
-        if ( !SDL_memcmp( guid, &pSupportedController->guid, sizeof(*guid) ) )
-        {
-            return pSupportedController;
-        }
-        pSupportedController = pSupportedController->next;
-    }
-    return NULL;
-}
-
-/*
- * Helper function to determine pre-calculated offset to certain joystick mappings
- */
-ControllerMapping_t *SDL_PrivateGetControllerMapping(int device_index)
-{
-#if defined(SDL_JOYSTICK_DINPUT) || defined(SDL_JOYSTICK_XINPUT)
-    if ( SDL_SYS_IsXInputDeviceIndex(device_index) && s_pXInputMapping )
-    {
-        return s_pXInputMapping;
-    }
-    else
-#endif
-    {
-        SDL_JoystickGUID jGUID = SDL_JoystickGetDeviceGUID( device_index );
-        return SDL_PrivateGetControllerMappingForGUID(&jGUID);
-    }
-}
-
-static const char* map_StringForControllerAxis[] = {
-    "leftx",
-    "lefty",
-    "rightx",
-    "righty",
-    "lefttrigger",
-    "righttrigger",
-    NULL
-};
-
-/*
- * convert a string to its enum equivalent
- */
-SDL_GameControllerAxis SDL_GameControllerGetAxisFromString( const char *pchString )
-{
-    int entry;
-    if ( !pchString || !pchString[0] )
-        return SDL_CONTROLLER_AXIS_INVALID;
-
-    for ( entry = 0; map_StringForControllerAxis[entry]; ++entry)
-    {
-        if ( !SDL_strcasecmp( pchString, map_StringForControllerAxis[entry] ) )
-            return entry;
-    }
-    return SDL_CONTROLLER_AXIS_INVALID;
-}
-
-/*
- * convert an enum to its string equivalent
- */
-const char* SDL_GameControllerGetStringForAxis( SDL_GameControllerAxis axis )
-{
-    if (axis > SDL_CONTROLLER_AXIS_INVALID && axis < SDL_CONTROLLER_AXIS_MAX)
-    {
-        return map_StringForControllerAxis[axis];
-    }
-    return NULL;
-}
-
-static const char* map_StringForControllerButton[] = {
-    "a",
-    "b",
-    "x",
-    "y",
-    "back",
-    "guide",
-    "start",
-    "leftstick",
-    "rightstick",
-    "leftshoulder",
-    "rightshoulder",
-    "dpup",
-    "dpdown",
-    "dpleft",
-    "dpright",
-    NULL
-};
-
-/*
- * convert a string to its enum equivalent
- */
-SDL_GameControllerButton SDL_GameControllerGetButtonFromString( const char *pchString )
-{
-    int entry;
-    if ( !pchString || !pchString[0] )
-        return SDL_CONTROLLER_BUTTON_INVALID;
-
-    for ( entry = 0; map_StringForControllerButton[entry]; ++entry)
-    {
-        if ( !SDL_strcasecmp( pchString, map_StringForControllerButton[entry] ) )
-        return entry;
-    }
-    return SDL_CONTROLLER_BUTTON_INVALID;
-}
-
-/*
- * convert an enum to its string equivalent
- */
-const char* SDL_GameControllerGetStringForButton( SDL_GameControllerButton axis )
-{
-    if (axis > SDL_CONTROLLER_BUTTON_INVALID && axis < SDL_CONTROLLER_BUTTON_MAX)
-    {
-        return map_StringForControllerButton[axis];
-    }
-    return NULL;
-}
-
-/*
- * given a controller button name and a joystick name update our mapping structure with it
- */
-void SDL_PrivateGameControllerParseButton( const char *szGameButton, const char *szJoystickButton, struct _SDL_ControllerMapping *pMapping )
-{
-    int iSDLButton = 0;
-    SDL_GameControllerButton button;
-    SDL_GameControllerAxis axis;
-    button = SDL_GameControllerGetButtonFromString( szGameButton );
-    axis = SDL_GameControllerGetAxisFromString( szGameButton );
-    iSDLButton = SDL_atoi( &szJoystickButton[1] );
-
-    if ( szJoystickButton[0] == 'a' )
-    {
-        if ( iSDLButton >= k_nMaxReverseEntries )
-        {
-            SDL_SetError("Axis index too large: %d", iSDLButton );
-            return;
-        }
-        if ( axis != SDL_CONTROLLER_AXIS_INVALID )
-        {
-            pMapping->axes[ axis ] = iSDLButton;
-            pMapping->raxes[ iSDLButton ] = axis;
-        }
-        else if ( button != SDL_CONTROLLER_BUTTON_INVALID )
-        {
-            pMapping->axesasbutton[ button ] = iSDLButton;
-            pMapping->raxesasbutton[ iSDLButton ] = button;
-        }
-        else
-        {
-            SDL_assert( !"How did we get here?" );
-        }
-
-    }
-    else if ( szJoystickButton[0] == 'b' )
-    {
-        if ( iSDLButton >= k_nMaxReverseEntries )
-        {
-            SDL_SetError("Button index too large: %d", iSDLButton );
-            return;
-        }
-        if ( button != SDL_CONTROLLER_BUTTON_INVALID )
-        {
-            pMapping->buttons[ button ] = iSDLButton;
-            pMapping->rbuttons[ iSDLButton ] = button;
-        }
-        else if ( axis != SDL_CONTROLLER_AXIS_INVALID )
-        {
-            pMapping->buttonasaxis[ axis ] = iSDLButton;
-            pMapping->rbuttonasaxis[ iSDLButton ] = axis;
-        }
-        else
-        {
-            SDL_assert( !"How did we get here?" );
-        }
-    }
-    else if ( szJoystickButton[0] == 'h' )
-    {
-        int hat = SDL_atoi( &szJoystickButton[1] );
-        int mask = SDL_atoi( &szJoystickButton[3] );
-        if (hat >= 4) {
-            SDL_SetError("Hat index too large: %d", iSDLButton );
-        }
-
-        if ( button != SDL_CONTROLLER_BUTTON_INVALID )
-        {
-            int ridx;
-            pMapping->hatasbutton[ button ].hat = hat;
-            pMapping->hatasbutton[ button ].mask = mask;
-            ridx = (hat << 4) | mask;
-            pMapping->rhatasbutton[ ridx ] = button;
-        }
-        else if ( axis != SDL_CONTROLLER_AXIS_INVALID )
-        {
-            SDL_assert( !"Support hat as axis" );
-        }
-        else
-        {
-            SDL_assert( !"How did we get here?" );
-        }
-    }
-}
-
-
-/*
- * given a controller mapping string update our mapping object
- */
-static void
-SDL_PrivateGameControllerParseControllerConfigString( struct _SDL_ControllerMapping *pMapping, const char *pchString )
-{
-    char szGameButton[20];
-    char szJoystickButton[20];
-    SDL_bool bGameButton = SDL_TRUE;
-    int i = 0;
-    const char *pchPos = pchString;
-
-    SDL_memset( szGameButton, 0x0, sizeof(szGameButton) );
-    SDL_memset( szJoystickButton, 0x0, sizeof(szJoystickButton) );
-
-    while ( pchPos && *pchPos )
-    {
-        if ( *pchPos == ':' )
-        {
-            i = 0;
-            bGameButton = SDL_FALSE;
-        }
-        else if ( *pchPos == ' ' )
-        {
-
-        }
-        else if ( *pchPos == ',' )
-        {
-            i = 0;
-            bGameButton = SDL_TRUE;
-            SDL_PrivateGameControllerParseButton( szGameButton, szJoystickButton, pMapping );
-            SDL_memset( szGameButton, 0x0, sizeof(szGameButton) );
-            SDL_memset( szJoystickButton, 0x0, sizeof(szJoystickButton) );
-
-        }
-        else if ( bGameButton )
-        {
-            if ( i >=  sizeof(szGameButton))
-            {
-                SDL_SetError( "Button name too large: %s", szGameButton );
-                return;
-            }
-            szGameButton[i] = *pchPos;
-            i++;
-        }
-        else
-        {
-            if ( i >=  sizeof(szJoystickButton))
-            {
-                SDL_SetError( "Joystick button name too large: %s", szJoystickButton );
-                return;
-            }
-            szJoystickButton[i] = *pchPos;
-            i++;
-        }
-        pchPos++;
-    }
-
-    SDL_PrivateGameControllerParseButton( szGameButton, szJoystickButton, pMapping );
-
-}
-
-/*
- * Make a new button mapping struct
- */
-void SDL_PrivateLoadButtonMapping( struct _SDL_ControllerMapping *pMapping, SDL_JoystickGUID guid, const char *pchName, const char *pchMapping )
-{
-    int j;
-
-    pMapping->guid = guid;
-    pMapping->name = pchName;
-
-    /* set all the button mappings to non defaults */
-    for ( j = 0; j < SDL_CONTROLLER_AXIS_MAX; j++ )
-    {
-        pMapping->axes[j] = -1;
-        pMapping->buttonasaxis[j] = -1;
-    }
-    for ( j = 0; j < SDL_CONTROLLER_BUTTON_MAX; j++ )
-    {
-        pMapping->buttons[j] = -1;
-        pMapping->axesasbutton[j] = -1;
-        pMapping->hatasbutton[j].hat = -1;
-    }
-
-    for ( j = 0; j < k_nMaxReverseEntries; j++ )
-    {
-        pMapping->raxes[j] = SDL_CONTROLLER_AXIS_INVALID;
-        pMapping->rbuttonasaxis[j] = SDL_CONTROLLER_AXIS_INVALID;
-        pMapping->rbuttons[j] = SDL_CONTROLLER_BUTTON_INVALID;
-        pMapping->raxesasbutton[j] = SDL_CONTROLLER_BUTTON_INVALID;
-    }
-
-    for (j = 0; j < k_nMaxHatEntries; j++)
-    {
-        pMapping->rhatasbutton[j] = SDL_CONTROLLER_BUTTON_INVALID;
-    }
-
-    SDL_PrivateGameControllerParseControllerConfigString( pMapping, pchMapping );
-}
-
-
-/*
- * grab the guid string from a mapping string
- */
-char *SDL_PrivateGetControllerGUIDFromMappingString( const char *pMapping )
-{
-    const char *pFirstComma = SDL_strchr( pMapping, ',' );
-    if ( pFirstComma )
-    {
-        char *pchGUID = SDL_malloc( pFirstComma - pMapping + 1 );
-        if ( !pchGUID )
-        {
-            SDL_OutOfMemory();
-            return NULL;
-        }
-        SDL_memcpy( pchGUID, pMapping, pFirstComma - pMapping );
-        pchGUID[ pFirstComma - pMapping ] = 0;
-        return pchGUID;
-    }
-    return NULL;
-}
-
-
-/*
- * grab the name string from a mapping string
- */
-char *SDL_PrivateGetControllerNameFromMappingString( const char *pMapping )
-{
-    const char *pFirstComma, *pSecondComma;
-    char *pchName;
-
-    pFirstComma = SDL_strchr( pMapping, ',' );
-    if ( !pFirstComma )
-        return NULL;
-
-    pSecondComma = SDL_strchr( pFirstComma + 1, ',' );
-    if ( !pSecondComma )
-        return NULL;
-
-    pchName = SDL_malloc( pSecondComma - pFirstComma );
-    if ( !pchName )
-    {
-        SDL_OutOfMemory();
-        return NULL;
-    }
-    SDL_memcpy( pchName, pFirstComma + 1, pSecondComma - pFirstComma );
-    pchName[ pSecondComma - pFirstComma - 1 ] = 0;
-    return pchName;
-}
-
-
-/*
- * grab the button mapping string from a mapping string
- */
-char *SDL_PrivateGetControllerMappingFromMappingString( const char *pMapping )
-{
-    const char *pFirstComma, *pSecondComma;
-
-    pFirstComma = SDL_strchr( pMapping, ',' );
-    if ( !pFirstComma )
-        return NULL;
-
-    pSecondComma = SDL_strchr( pFirstComma + 1, ',' );
-    if ( !pSecondComma )
-        return NULL;
-
-    return SDL_strdup(pSecondComma + 1); /* mapping is everything after the 3rd comma */
-}
-
-void SDL_PrivateGameControllerRefreshMapping( ControllerMapping_t *pControllerMapping )
-{
-    SDL_GameController *gamecontrollerlist = SDL_gamecontrollers;
-    while ( gamecontrollerlist )
-    {
-        if ( !SDL_memcmp( &gamecontrollerlist->mapping.guid, &pControllerMapping->guid, sizeof(pControllerMapping->guid) ) )
-        {
-            SDL_Event event;
-            event.type = SDL_CONTROLLERDEVICEREMAPPED;
-            event.cdevice.which = gamecontrollerlist->joystick->instance_id;
-            SDL_PushEvent(&event);
-
-            /* Not really threadsafe.  Should this lock access within SDL_GameControllerEventWatcher? */
-            SDL_PrivateLoadButtonMapping(&gamecontrollerlist->mapping, pControllerMapping->guid, pControllerMapping->name, pControllerMapping->mapping);
-        }
-
-        gamecontrollerlist = gamecontrollerlist->next;
-    }
-}
-
-/*
- * Add or update an entry into the Mappings Database
- */
-int
-SDL_GameControllerAddMapping( const char *mappingString )
-{
-    char *pchGUID;
-    char *pchName;
-    char *pchMapping;
-    SDL_JoystickGUID jGUID;
-    ControllerMapping_t *pControllerMapping;
-#if defined(SDL_JOYSTICK_DINPUT) || defined(SDL_JOYSTICK_XINPUT)
-    SDL_bool is_xinput_mapping = SDL_FALSE;
-#endif
-
-    pchGUID = SDL_PrivateGetControllerGUIDFromMappingString( mappingString );
-    if (!pchGUID) {
-        return -1;
-    }
-#if defined(SDL_JOYSTICK_DINPUT) || defined(SDL_JOYSTICK_XINPUT)
-    if ( !SDL_strcasecmp( pchGUID, "xinput" ) ) {
-        is_xinput_mapping = SDL_TRUE;
-    }
-#endif
-    jGUID = SDL_JoystickGetGUIDFromString(pchGUID);
-    SDL_free(pchGUID);
-
-    pControllerMapping = SDL_PrivateGetControllerMappingForGUID(&jGUID);
-
-    pchName = SDL_PrivateGetControllerNameFromMappingString( mappingString );
-    if (!pchName) return -1;
-
-    pchMapping = SDL_PrivateGetControllerMappingFromMappingString( mappingString );
-    if (!pchMapping) {
-        SDL_free( pchName );
-        return -1;
-    }
-
-    if (pControllerMapping) {
-        /* Update existing mapping */
-        SDL_free( pControllerMapping->name );
-        pControllerMapping->name = pchName;
-        SDL_free( pControllerMapping->mapping );
-        pControllerMapping->mapping = pchMapping;
-        /* refresh open controllers */
-        SDL_PrivateGameControllerRefreshMapping( pControllerMapping );
-        return 0;
-    } else {
-        pControllerMapping = SDL_malloc( sizeof(*pControllerMapping) );
-        if (!pControllerMapping) {
-            SDL_free( pchName );
-            SDL_free( pchMapping );
-            return SDL_OutOfMemory();
-        }
-#if defined(SDL_JOYSTICK_DINPUT) || defined(SDL_JOYSTICK_XINPUT)
-        if ( is_xinput_mapping )
-        {
-            s_pXInputMapping = pControllerMapping;
-        }
-#endif
-        pControllerMapping->guid = jGUID;
-        pControllerMapping->name = pchName;
-        pControllerMapping->mapping = pchMapping;
-        pControllerMapping->next = s_pSupportedControllers;
-        s_pSupportedControllers = pControllerMapping;
-        return 1;
-    }
-}
-
-/*
- * Get the mapping string for this GUID
- */
-char *
-SDL_GameControllerMappingForGUID( SDL_JoystickGUID guid )
-{
-    char *pMappingString = NULL;
-    ControllerMapping_t *mapping = SDL_PrivateGetControllerMappingForGUID(&guid);
-    if (mapping) {
-        char pchGUID[33];
-        size_t needed;
-        SDL_JoystickGetGUIDString(guid, pchGUID, sizeof(pchGUID));
-        /* allocate enough memory for GUID + ',' + name + ',' + mapping + \0 */
-        needed = SDL_strlen(pchGUID) + 1 + SDL_strlen(mapping->name) + 1 + SDL_strlen(mapping->mapping) + 1;
-        pMappingString = SDL_malloc( needed );
-        SDL_snprintf( pMappingString, needed, "%s,%s,%s", pchGUID, mapping->name, mapping->mapping );
-    }
-    return pMappingString;
-}
-
-/*
- * Get the mapping string for this device
- */
-char *
-SDL_GameControllerMapping( SDL_GameController * gamecontroller )
-{
-    return SDL_GameControllerMappingForGUID( gamecontroller->mapping.guid );
-}
-
-static void
-SDL_GameControllerLoadHints()
-{
-    const char *hint = SDL_GetHint(SDL_HINT_GAMECONTROLLERCONFIG);
-    if ( hint && hint[0] ) {
-        size_t nchHints = SDL_strlen( hint );
-        char *pUserMappings = SDL_malloc( nchHints + 1 );
-        char *pTempMappings = pUserMappings;
-        SDL_memcpy( pUserMappings, hint, nchHints );
-        while ( pUserMappings ) {
-            char *pchNewLine = NULL;
-
-            pchNewLine = SDL_strchr( pUserMappings, '\n' );
-            if ( pchNewLine )
-                *pchNewLine = '\0';
-
-            SDL_GameControllerAddMapping( pUserMappings );
-
-            if ( pchNewLine )
-                pUserMappings = pchNewLine + 1;
-            else
-                pUserMappings = NULL;
-        }
-        SDL_free(pTempMappings);
-    }
-}
-
-/*
- * Initialize the game controller system, mostly load our DB of controller config mappings
- */
-int
-SDL_GameControllerInit(void)
-{
-    int i = 0;
-    const char *pMappingString = NULL;
-    s_pSupportedControllers = NULL;
-    pMappingString = s_ControllerMappings[i];
-    while ( pMappingString )
-    {
-        SDL_GameControllerAddMapping( pMappingString );
-
-        i++;
-        pMappingString = s_ControllerMappings[i];
-    }
-
-    /* load in any user supplied config */
-    SDL_GameControllerLoadHints();
-
-    /* watch for joy events and fire controller ones if needed */
-    SDL_AddEventWatch( SDL_GameControllerEventWatcher, NULL );
-
-    return (0);
-}
-
-
-/*
- * Get the implementation dependent name of a controller
- */
-const char *
-SDL_GameControllerNameForIndex(int device_index)
-{
-    ControllerMapping_t *pSupportedController =  SDL_PrivateGetControllerMapping(device_index);
-    if ( pSupportedController )
-    {
-        return pSupportedController->name;
-    }
-    return NULL;
-}
-
-
-/*
- * Return 1 if the joystick at this device index is a supported controller
- */
-SDL_bool
-SDL_IsGameController(int device_index)
-{
-    ControllerMapping_t *pSupportedController =  SDL_PrivateGetControllerMapping(device_index);
-    if ( pSupportedController )
-    {
-        return SDL_TRUE;
-    }
-
-    return SDL_FALSE;
-}
-
-/*
- * Open a controller for use - the index passed as an argument refers to
- * the N'th controller on the system.  This index is the value which will
- * identify this controller in future controller events.
- *
- * This function returns a controller identifier, or NULL if an error occurred.
- */
-SDL_GameController *
-SDL_GameControllerOpen(int device_index)
-{
-    SDL_GameController *gamecontroller;
-    SDL_GameController *gamecontrollerlist;
-    ControllerMapping_t *pSupportedController = NULL;
-
-    if ((device_index < 0) || (device_index >= SDL_NumJoysticks())) {
-        SDL_SetError("There are %d joysticks available", SDL_NumJoysticks());
-        return (NULL);
-    }
-
-    gamecontrollerlist = SDL_gamecontrollers;
-    /* If the controller is already open, return it */
-    while ( gamecontrollerlist )
-    {
-        if ( SDL_SYS_GetInstanceIdOfDeviceIndex(device_index) == gamecontrollerlist->joystick->instance_id ) {
-                gamecontroller = gamecontrollerlist;
-                ++gamecontroller->ref_count;
-                return (gamecontroller);
-        }
-        gamecontrollerlist = gamecontrollerlist->next;
-    }
-
-    /* Find a controller mapping */
-    pSupportedController =  SDL_PrivateGetControllerMapping(device_index);
-    if ( !pSupportedController ) {
-        SDL_SetError("Couldn't find mapping for device (%d)", device_index );
-        return (NULL);
-    }
-
-    /* Create and initialize the joystick */
-    gamecontroller = (SDL_GameController *) SDL_malloc((sizeof *gamecontroller));
-    if (gamecontroller == NULL) {
-        SDL_OutOfMemory();
-        return NULL;
-    }
-
-    SDL_memset(gamecontroller, 0, (sizeof *gamecontroller));
-    gamecontroller->joystick = SDL_JoystickOpen(device_index);
-    if ( !gamecontroller->joystick ) {
-        SDL_free(gamecontroller);
-        return NULL;
-    }
-
-    SDL_PrivateLoadButtonMapping( &gamecontroller->mapping, pSupportedController->guid, pSupportedController->name, pSupportedController->mapping );
-
-    /* Add joystick to list */
-    ++gamecontroller->ref_count;
-    /* Link the joystick in the list */
-    gamecontroller->next = SDL_gamecontrollers;
-    SDL_gamecontrollers = gamecontroller;
-
-    SDL_SYS_JoystickUpdate( gamecontroller->joystick );
-
-    return (gamecontroller);
-}
-
-/*
- * Manually pump for controller updates.
- */
-void
-SDL_GameControllerUpdate(void)
-{
-    /* Just for API completeness; the joystick API does all the work. */
-    SDL_JoystickUpdate();
-}
-
-
-/*
- * Get the current state of an axis control on a controller
- */
-Sint16
-SDL_GameControllerGetAxis(SDL_GameController * gamecontroller, SDL_GameControllerAxis axis)
-{
-    if ( !gamecontroller )
-        return 0;
-
-    if (gamecontroller->mapping.axes[axis] >= 0 )
-    {
-        Sint16 value = ( SDL_JoystickGetAxis( gamecontroller->joystick, gamecontroller->mapping.axes[axis]) );
-        switch (axis)
-        {
-            case SDL_CONTROLLER_AXIS_TRIGGERLEFT:
-            case SDL_CONTROLLER_AXIS_TRIGGERRIGHT:
-                /* Shift it to be 0 - 32767. */
-                value = value / 2 + 16384;
-            default:
-                break;
-        }
-        return value;
-    }
-    else if (gamecontroller->mapping.buttonasaxis[axis] >= 0 )
-    {
-        Uint8 value;
-        value = SDL_JoystickGetButton( gamecontroller->joystick, gamecontroller->mapping.buttonasaxis[axis] );
-        if ( value > 0 )
-            return 32767;
-        return 0;
-    }
-    return 0;
-}
-
-
-/*
- * Get the current state of a button on a controller
- */
-Uint8
-SDL_GameControllerGetButton(SDL_GameController * gamecontroller, SDL_GameControllerButton button)
-{
-    if ( !gamecontroller )
-        return 0;
-
-    if ( gamecontroller->mapping.buttons[button] >= 0 )
-    {
-        return ( SDL_JoystickGetButton( gamecontroller->joystick, gamecontroller->mapping.buttons[button] ) );
-    }
-    else if ( gamecontroller->mapping.axesasbutton[button] >= 0 )
-    {
-        Sint16 value;
-        value = SDL_JoystickGetAxis( gamecontroller->joystick, gamecontroller->mapping.axesasbutton[button] );
-        if ( ABS(value) > 32768/2 )
-            return 1;
-        return 0;
-    }
-    else if ( gamecontroller->mapping.hatasbutton[button].hat >= 0 )
-    {
-        Uint8 value;
-        value = SDL_JoystickGetHat( gamecontroller->joystick, gamecontroller->mapping.hatasbutton[button].hat );
-
-        if ( value & gamecontroller->mapping.hatasbutton[button].mask )
-            return 1;
-        return 0;
-    }
-
-    return 0;
-}
-
-/*
- * Return if the joystick in question is currently attached to the system,
- *  \return 0 if not plugged in, 1 if still present.
- */
-SDL_bool
-SDL_GameControllerGetAttached( SDL_GameController * gamecontroller )
-{
-    if ( !gamecontroller )
-        return SDL_FALSE;
-
-    return SDL_JoystickGetAttached(gamecontroller->joystick);
-}
-
-
-/*
- * Get the number of multi-dimensional axis controls on a joystick
- */
-const char *
-SDL_GameControllerName(SDL_GameController * gamecontroller)
-{
-    if ( !gamecontroller )
-        return NULL;
-
-    return (gamecontroller->mapping.name);
-}
-
-
-/*
- * Get the joystick for this controller
- */
-SDL_Joystick *SDL_GameControllerGetJoystick(SDL_GameController * gamecontroller)
-{
-    if ( !gamecontroller )
-        return NULL;
-
-    return gamecontroller->joystick;
-}
-
-/**
- * Get the SDL joystick layer binding for this controller axis mapping
- */
-SDL_GameControllerButtonBind SDL_GameControllerGetBindForAxis(SDL_GameController * gamecontroller, SDL_GameControllerAxis axis)
-{
-    SDL_GameControllerButtonBind bind;
-    SDL_memset( &bind, 0x0, sizeof(bind) );
-
-    if ( !gamecontroller || axis == SDL_CONTROLLER_AXIS_INVALID )
-        return bind;
-
-    if (gamecontroller->mapping.axes[axis] >= 0 )
-    {
-        bind.bindType = SDL_CONTROLLER_BINDTYPE_AXIS;
-        bind.value.button = gamecontroller->mapping.axes[axis];
-    }
-    else if (gamecontroller->mapping.buttonasaxis[axis] >= 0 )
-    {
-        bind.bindType = SDL_CONTROLLER_BINDTYPE_BUTTON;
-        bind.value.button = gamecontroller->mapping.buttonasaxis[axis];
-    }
-
-    return bind;
-}
-
-
-/**
- * Get the SDL joystick layer binding for this controller button mapping
- */
-SDL_GameControllerButtonBind SDL_GameControllerGetBindForButton(SDL_GameController * gamecontroller, SDL_GameControllerButton button)
-{
-    SDL_GameControllerButtonBind bind;
-    SDL_memset( &bind, 0x0, sizeof(bind) );
-
-    if ( !gamecontroller || button == SDL_CONTROLLER_BUTTON_INVALID )
-        return bind;
-
-    if ( gamecontroller->mapping.buttons[button] >= 0 )
-    {
-        bind.bindType = SDL_CONTROLLER_BINDTYPE_BUTTON;
-        bind.value.button = gamecontroller->mapping.buttons[button];
-    }
-    else if ( gamecontroller->mapping.axesasbutton[button] >= 0 )
-    {
-        bind.bindType = SDL_CONTROLLER_BINDTYPE_AXIS;
-        bind.value.axis = gamecontroller->mapping.axesasbutton[button];
-    }
-    else if ( gamecontroller->mapping.hatasbutton[button].hat >= 0 )
-    {
-        bind.bindType = SDL_CONTROLLER_BINDTYPE_HAT;
-        bind.value.hat.hat = gamecontroller->mapping.hatasbutton[button].hat;
-        bind.value.hat.hat_mask = gamecontroller->mapping.hatasbutton[button].mask;
-    }
-
-    return bind;
-}
-
-
-/*
- * Close a joystick previously opened with SDL_JoystickOpen()
- */
-void
-SDL_GameControllerClose(SDL_GameController * gamecontroller)
-{
-    SDL_GameController *gamecontrollerlist, *gamecontrollerlistprev;
-
-    if ( !gamecontroller )
-        return;
-
-    /* First decrement ref count */
-    if (--gamecontroller->ref_count > 0) {
-        return;
-    }
-
-    SDL_JoystickClose( gamecontroller->joystick );
-
-    gamecontrollerlist = SDL_gamecontrollers;
-    gamecontrollerlistprev = NULL;
-    while ( gamecontrollerlist )
-    {
-        if (gamecontroller == gamecontrollerlist)
-        {
-            if ( gamecontrollerlistprev )
-            {
-                /* unlink this entry */
-                gamecontrollerlistprev->next = gamecontrollerlist->next;
-            }
-            else
-            {
-                SDL_gamecontrollers = gamecontroller->next;
-            }
-
-            break;
-        }
-        gamecontrollerlistprev = gamecontrollerlist;
-        gamecontrollerlist = gamecontrollerlist->next;
-    }
-
-    SDL_free(gamecontroller);
-}
-
-
-/*
- * Quit the controller subsystem
- */
-void
-SDL_GameControllerQuit(void)
-{
-    ControllerMapping_t *pControllerMap;
-    while ( SDL_gamecontrollers )
-    {
-        SDL_gamecontrollers->ref_count = 1;
-        SDL_GameControllerClose(SDL_gamecontrollers);
-    }
-
-    while ( s_pSupportedControllers )
-    {
-        pControllerMap = s_pSupportedControllers;
-        s_pSupportedControllers = s_pSupportedControllers->next;
-        SDL_free( pControllerMap->name );
-        SDL_free( pControllerMap );
-    }
-
-    SDL_DelEventWatch( SDL_GameControllerEventWatcher, NULL );
-
-}
-
-/*
- * Event filter to transform joystick events into appropriate game controller ones
- */
-int
-SDL_PrivateGameControllerAxis(SDL_GameController * gamecontroller, SDL_GameControllerAxis axis, Sint16 value)
-{
-    int posted;
-
-    /* translate the event, if desired */
-    posted = 0;
-#if !SDL_EVENTS_DISABLED
-    if (SDL_GetEventState(SDL_CONTROLLERAXISMOTION) == SDL_ENABLE) {
-        SDL_Event event;
-        event.type = SDL_CONTROLLERAXISMOTION;
-        event.caxis.which = gamecontroller->joystick->instance_id;
-        event.caxis.axis = axis;
-        event.caxis.value = value;
-        posted = SDL_PushEvent(&event) == 1;
-    }
-#endif /* !SDL_EVENTS_DISABLED */
-    return (posted);
-}
-
-
-/*
- * Event filter to transform joystick events into appropriate game controller ones
- */
-int
-SDL_PrivateGameControllerButton(SDL_GameController * gamecontroller, SDL_GameControllerButton button, Uint8 state)
-{
-    int posted;
-#if !SDL_EVENTS_DISABLED
-    SDL_Event event;
-
-    if ( button == SDL_CONTROLLER_BUTTON_INVALID )
-        return (0);
-
-    switch (state) {
-    case SDL_PRESSED:
-        event.type = SDL_CONTROLLERBUTTONDOWN;
-        break;
-    case SDL_RELEASED:
-        event.type = SDL_CONTROLLERBUTTONUP;
-        break;
-    default:
-        /* Invalid state -- bail */
-        return (0);
-    }
-#endif /* !SDL_EVENTS_DISABLED */
-
-    /* translate the event, if desired */
-    posted = 0;
-#if !SDL_EVENTS_DISABLED
-    if (SDL_GetEventState(event.type) == SDL_ENABLE) {
-        event.cbutton.which = gamecontroller->joystick->instance_id;
-        event.cbutton.button = button;
-        event.cbutton.state = state;
-        posted = SDL_PushEvent(&event) == 1;
-    }
-#endif /* !SDL_EVENTS_DISABLED */
-    return (posted);
-}
-
-/*
- * Turn off controller events
- */
-int
-SDL_GameControllerEventState(int state)
-{
-#if SDL_EVENTS_DISABLED
-    return SDL_IGNORE;
-#else
-    const Uint32 event_list[] = {
-        SDL_CONTROLLERAXISMOTION, SDL_CONTROLLERBUTTONDOWN, SDL_CONTROLLERBUTTONUP,
-        SDL_CONTROLLERDEVICEADDED, SDL_CONTROLLERDEVICEREMOVED, SDL_CONTROLLERDEVICEREMAPPED,
-    };
-    unsigned int i;
-
-    switch (state) {
-    case SDL_QUERY:
-        state = SDL_IGNORE;
-        for (i = 0; i < SDL_arraysize(event_list); ++i) {
-            state = SDL_EventState(event_list[i], SDL_QUERY);
-            if (state == SDL_ENABLE) {
-                break;
-            }
-        }
-        break;
-    default:
-        for (i = 0; i < SDL_arraysize(event_list); ++i) {
-            SDL_EventState(event_list[i], state);
-        }
-        break;
-    }
-    return (state);
-#endif /* SDL_EVENTS_DISABLED */
-}
-
-/* vi: set ts=4 sw=4 expandtab: */
+/*
+  Simple DirectMedia Layer
+  Copyright (C) 1997-2013 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 "SDL_config.h"
+
+/* This is the game controller API for Simple DirectMedia Layer */
+
+#include "SDL_events.h"
+#include "SDL_assert.h"
+#include "SDL_sysjoystick.h"
+#include "SDL_hints.h"
+#include "SDL_gamecontrollerdb.h"
+
+#if !SDL_EVENTS_DISABLED
+#include "../events/SDL_events_c.h"
+#endif
+#define ABS(_x) ((_x) < 0 ? -(_x) : (_x))
+
+
+/* a list of currently opened game controllers */
+static SDL_GameController *SDL_gamecontrollers = NULL;
+
+/* keep track of the hat and mask value that transforms this hat movement into a button/axis press */
+struct _SDL_HatMapping
+{
+    int hat;
+    Uint8 mask;
+};
+
+#define k_nMaxReverseEntries 20
+
+/**
+ * We are encoding the "HAT" as 0xhm. where h == hat ID and m == mask
+ * MAX 4 hats supported
+ */
+#define k_nMaxHatEntries 0x3f + 1
+
+/* our in memory mapping db between joystick objects and controller mappings */
+struct _SDL_ControllerMapping
+{
+    SDL_JoystickGUID guid;
+    const char *name;
+
+    /* mapping of axis/button id to controller version */
+    int axes[SDL_CONTROLLER_AXIS_MAX];
+    int buttonasaxis[SDL_CONTROLLER_AXIS_MAX];
+
+    int buttons[SDL_CONTROLLER_BUTTON_MAX];
+    int axesasbutton[SDL_CONTROLLER_BUTTON_MAX];
+    struct _SDL_HatMapping hatasbutton[SDL_CONTROLLER_BUTTON_MAX];
+
+    /* reverse mapping, joystick indices to buttons */
+    SDL_GameControllerAxis raxes[k_nMaxReverseEntries];
+    SDL_GameControllerAxis rbuttonasaxis[k_nMaxReverseEntries];
+
+    SDL_GameControllerButton rbuttons[k_nMaxReverseEntries];
+    SDL_GameControllerButton raxesasbutton[k_nMaxReverseEntries];
+    SDL_GameControllerButton rhatasbutton[k_nMaxHatEntries];
+
+};
+
+
+/* our hard coded list of mapping support */
+typedef struct _ControllerMapping_t
+{
+    SDL_JoystickGUID guid;
+    char *name;
+    char *mapping;
+    struct _ControllerMapping_t *next;
+} ControllerMapping_t;
+
+static ControllerMapping_t *s_pSupportedControllers = NULL;
+#if defined(SDL_JOYSTICK_DINPUT) || defined(SDL_JOYSTICK_XINPUT)
+static ControllerMapping_t *s_pXInputMapping = NULL;
+#endif
+
+/* The SDL game controller structure */
+struct _SDL_GameController
+{
+    SDL_Joystick *joystick; /* underlying joystick device */
+    int ref_count;
+    Uint8 hatState[4]; /* the current hat state for this controller */
+    struct _SDL_ControllerMapping mapping; /* the mapping object for this controller */
+    struct _SDL_GameController *next; /* pointer to next game controller we have allocated */
+};
+
+
+int SDL_PrivateGameControllerAxis(SDL_GameController * gamecontroller, SDL_GameControllerAxis axis, Sint16 value);
+int SDL_PrivateGameControllerButton(SDL_GameController * gamecontroller, SDL_GameControllerButton button, Uint8 state);
+
+/*
+ * Event filter to fire controller events from joystick ones
+ */
+int SDL_GameControllerEventWatcher(void *userdata, SDL_Event * event)
+{
+    switch( event->type )
+    {
+    case SDL_JOYAXISMOTION:
+        {
+            SDL_GameController *controllerlist;
+
+            if ( event->jaxis.axis >= k_nMaxReverseEntries ) break;
+
+            controllerlist = SDL_gamecontrollers;
+            while ( controllerlist )
+            {
+                if ( controllerlist->joystick->instance_id == event->jaxis.which )
+                {
+                    if ( controllerlist->mapping.raxes[event->jaxis.axis] >= 0 ) /* simple axis to axis, send it through */
+                    {
+                        SDL_GameControllerAxis axis = controllerlist->mapping.raxes[event->jaxis.axis];
+                        Sint16 value = event->jaxis.value;
+                        switch (axis)
+                        {
+                            case SDL_CONTROLLER_AXIS_TRIGGERLEFT:
+                            case SDL_CONTROLLER_AXIS_TRIGGERRIGHT:
+                                /* Shift it to be 0 - 32767. */
+                                value = value / 2 + 16384;
+                            default:
+                                break;
+                        }
+                        SDL_PrivateGameControllerAxis( controllerlist, axis, value );
+                    }
+                    else if ( controllerlist->mapping.raxesasbutton[event->jaxis.axis] >= 0 ) /* simulate an axis as a button */
+                    {
+                        SDL_PrivateGameControllerButton( controllerlist, controllerlist->mapping.raxesasbutton[event->jaxis.axis], ABS(event->jaxis.value) > 32768/2 ? SDL_PRESSED : SDL_RELEASED );
+                    }
+                    break;
+                }
+                controllerlist = controllerlist->next;
+            }
+        }
+        break;
+    case SDL_JOYBUTTONDOWN:
+    case SDL_JOYBUTTONUP:
+        {
+            SDL_GameController *controllerlist;
+
+            if ( event->jbutton.button >= k_nMaxReverseEntries ) break;
+
+            controllerlist = SDL_gamecontrollers;
+            while ( controllerlist )
+            {
+                if ( controllerlist->joystick->instance_id == event->jbutton.which )
+                {
+                    if ( controllerlist->mapping.rbuttons[event->jbutton.button] >= 0 ) /* simple button as button */
+                    {
+                        SDL_PrivateGameControllerButton( controllerlist, controllerlist->mapping.rbuttons[event->jbutton.button], event->jbutton.state );
+                    }
+                    else if ( controllerlist->mapping.rbuttonasaxis[event->jbutton.button] >= 0 ) /* an button pretending to be an axis */
+                    {
+                        SDL_PrivateGameControllerAxis( controllerlist, controllerlist->mapping.rbuttonasaxis[event->jbutton.button], event->jbutton.state > 0 ? 32767 : 0 );
+                    }
+                    break;
+                }
+                controllerlist = controllerlist->next;
+            }
+        }
+        break;
+    case SDL_JOYHATMOTION:
+        {
+            SDL_GameController *controllerlist;
+
+            if ( event->jhat.hat >= 4 ) break;
+
+            controllerlist = SDL_gamecontrollers;
+            while ( controllerlist )
+            {
+                if ( controllerlist->joystick->instance_id == event->jhat.which )
+                {
+                    Uint8 bSame = controllerlist->hatState[event->jhat.hat] & event->jhat.value;
+                    /* Get list of removed bits (button release) */
+                    Uint8 bChanged = controllerlist->hatState[event->jhat.hat] ^ bSame;
+                    /* the hat idx in the high nibble */
+                    int bHighHat = event->jhat.hat << 4;
+
+                    if ( bChanged & SDL_HAT_DOWN )
+                        SDL_PrivateGameControllerButton( controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_DOWN], SDL_RELEASED );
+                    if ( bChanged & SDL_HAT_UP )
+                        SDL_PrivateGameControllerButton( controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_UP], SDL_RELEASED );
+                    if ( bChanged & SDL_HAT_LEFT )
+                        SDL_PrivateGameControllerButton( controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_LEFT], SDL_RELEASED );
+                    if ( bChanged & SDL_HAT_RIGHT )
+                        SDL_PrivateGameControllerButton( controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_RIGHT], SDL_RELEASED );
+
+                    /* Get list of added bits (button press) */
+                    bChanged = event->jhat.value ^ bSame;
+
+                    if ( bChanged & SDL_HAT_DOWN )
+                        SDL_PrivateGameControllerButton( controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_DOWN], SDL_PRESSED );
+                    if ( bChanged & SDL_HAT_UP )
+                        SDL_PrivateGameControllerButton( controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_UP], SDL_PRESSED );
+                    if ( bChanged & SDL_HAT_LEFT )
+                        SDL_PrivateGameControllerButton( controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_LEFT], SDL_PRESSED );
+                    if ( bChanged & SDL_HAT_RIGHT )
+                        SDL_PrivateGameControllerButton( controllerlist, controllerlist->mapping.rhatasbutton[bHighHat | SDL_HAT_RIGHT], SDL_PRESSED );
+
+                    /* update our state cache */
+                    controllerlist->hatState[event->jhat.hat] = event->jhat.value;
+
+                    break;
+                }
+                controllerlist = controllerlist->next;
+            }
+        }
+        break;
+    case SDL_JOYDEVICEADDED:
+        {
+            if ( SDL_IsGameController(event->jdevice.which ) )
+            {
+                SDL_Event deviceevent;
+                deviceevent.type = SDL_CONTROLLERDEVICEADDED;
+                deviceevent.cdevice.which = event->jdevice.which;
+                SDL_PushEvent(&deviceevent);
+            }
+        }
+        break;
+    case SDL_JOYDEVICEREMOVED:
+        {
+            SDL_GameController *controllerlist = SDL_gamecontrollers;
+            while ( controllerlist )
+            {
+                if ( controllerlist->joystick->instance_id == event->jdevice.which )
+                {
+                    SDL_Event deviceevent;
+                    deviceevent.type = SDL_CONTROLLERDEVICEREMOVED;
+                    deviceevent.cdevice.which = event->jdevice.which;
+                    SDL_PushEvent(&deviceevent);
+                    break;
+                }
+                controllerlist = controllerlist->next;
+            }
+        }
+        break;
+    default:
+        break;
+    }
+
+    return 1;
+}
+
+/*
+ * Helper function to scan the mappings database for a controller with the specified GUID
+ */
+ControllerMapping_t *SDL_PrivateGetControllerMappingForGUID(SDL_JoystickGUID *guid)
+{
+    ControllerMapping_t *pSupportedController = s_pSupportedControllers;
+    while ( pSupportedController )
+    {
+        if ( !SDL_memcmp( guid, &pSupportedController->guid, sizeof(*guid) ) )
+        {
+            return pSupportedController;
+        }
+        pSupportedController = pSupportedController->next;
+    }
+    return NULL;
+}
+
+/*
+ * Helper function to determine pre-calculated offset to certain joystick mappings
+ */
+ControllerMapping_t *SDL_PrivateGetControllerMapping(int device_index)
+{
+#if defined(SDL_JOYSTICK_DINPUT) || defined(SDL_JOYSTICK_XINPUT)
+    if ( SDL_SYS_IsXInputDeviceIndex(device_index) && s_pXInputMapping )
+    {
+        return s_pXInputMapping;
+    }
+    else
+#endif
+    {
+        SDL_JoystickGUID jGUID = SDL_JoystickGetDeviceGUID( device_index );
+        return SDL_PrivateGetControllerMappingForGUID(&jGUID);
+    }
+}
+
+static const char* map_StringForControllerAxis[] = {
+    "leftx",
+    "lefty",
+    "rightx",
+    "righty",
+    "lefttrigger",
+    "righttrigger",
+    NULL
+};
+
+/*
+ * convert a string to its enum equivalent
+ */
+SDL_GameControllerAxis SDL_GameControllerGetAxisFromString( const char *pchString )
+{
+    int entry;
+    if ( !pchString || !pchString[0] )
+        return SDL_CONTROLLER_AXIS_INVALID;
+
+    for ( entry = 0; map_StringForControllerAxis[entry]; ++entry)
+    {
+        if ( !SDL_strcasecmp( pchString, map_StringForControllerAxis[entry] ) )
+            return entry;
+    }
+    return SDL_CONTROLLER_AXIS_INVALID;
+}
+
+/*
+ * convert an enum to its string equivalent
+ */
+const char* SDL_GameControllerGetStringForAxis( SDL_GameControllerAxis axis )
+{
+    if (axis > SDL_CONTROLLER_AXIS_INVALID && axis < SDL_CONTROLLER_AXIS_MAX)
+    {
+        return map_StringForControllerAxis[axis];
+    }
+    return NULL;
+}
+
+static const char* map_StringForControllerButton[] = {
+    "a",
+    "b",
+    "x",
+    "y",
+    "back",
+    "guide",
+    "start",
+    "leftstick",
+    "rightstick",
+    "leftshoulder",
+    "rightshoulder",
+    "dpup",
+    "dpdown",
+    "dpleft",
+    "dpright",
+    NULL
+};
+
+/*
+ * convert a string to its enum equivalent
+ */
+SDL_GameControllerButton SDL_GameControllerGetButtonFromString( const char *pchString )
+{
+    int entry;
+    if ( !pchString || !pchString[0] )
+        return SDL_CONTROLLER_BUTTON_INVALID;
+
+    for ( entry = 0; map_StringForControllerButton[entry]; ++entry)
+    {
+        if ( !SDL_strcasecmp( pchString, map_StringForControllerButton[entry] ) )
+        return entry;
+    }
+    return SDL_CONTROLLER_BUTTON_INVALID;
+}
+
+/*
+ * convert an enum to its string equivalent
+ */
+const char* SDL_GameControllerGetStringForButton( SDL_GameControllerButton axis )
+{
+    if (axis > SDL_CONTROLLER_BUTTON_INVALID && axis < SDL_CONTROLLER_BUTTON_MAX)
+    {
+        return map_StringForControllerButton[axis];
+    }
+    return NULL;
+}
+
+/*
+ * given a controller button name and a joystick name update our mapping structure with it
+ */
+void SDL_PrivateGameControllerParseButton( const char *szGameButton, const char *szJoystickButton, struct _SDL_ControllerMapping *pMapping )
+{
+    int iSDLButton = 0;
+    SDL_GameControllerButton button;
+    SDL_GameControllerAxis axis;
+    button = SDL_GameControllerGetButtonFromString( szGameButton );
+    axis = SDL_GameControllerGetAxisFromString( szGameButton );
+    iSDLButton = SDL_atoi( &szJoystickButton[1] );
+
+    if ( szJoystickButton[0] == 'a' )
+    {
+        if ( iSDLButton >= k_nMaxReverseEntries )
+        {
+            SDL_SetError("Axis index too large: %d", iSDLButton );
+            return;
+        }
+        if ( axis != SDL_CONTROLLER_AXIS_INVALID )
+        {
+            pMapping->axes[ axis ] = iSDLButton;
+            pMapping->raxes[ iSDLButton ] = axis;
+        }
+        else if ( button != SDL_CONTROLLER_BUTTON_INVALID )
+        {
+            pMapping->axesasbutton[ button ] = iSDLButton;
+            pMapping->raxesasbutton[ iSDLButton ] = button;
+        }
+        else
+        {
+            SDL_assert( !"How did we get here?" );
+        }
+
+    }
+    else if ( szJoystickButton[0] == 'b' )
+    {
+        if ( iSDLButton >= k_nMaxReverseEntries )
+        {
+            SDL_SetError("Button index too large: %d", iSDLButton );
+            return;
+        }
+        if ( button != SDL_CONTROLLER_BUTTON_INVALID )
+        {
+            pMapping->buttons[ button ] = iSDLButton;
+            pMapping->rbuttons[ iSDLButton ] = button;
+        }
+        else if ( axis != SDL_CONTROLLER_AXIS_INVALID )
+        {
+            pMapping->buttonasaxis[ axis ] = iSDLButton;
+            pMapping->rbuttonasaxis[ iSDLButton ] = axis;
+        }
+        else
+        {
+            SDL_assert( !"How did we get here?" );
+        }
+    }
+    else if ( szJoystickButton[0] == 'h' )
+    {
+        int hat = SDL_atoi( &szJoystickButton[1] );
+        int mask = SDL_atoi( &szJoystickButton[3] );
+        if (hat >= 4) {
+            SDL_SetError("Hat index too large: %d", iSDLButton );
+        }
+
+        if ( button != SDL_CONTROLLER_BUTTON_INVALID )
+        {
+            int ridx;
+            pMapping->hatasbutton[ button ].hat = hat;
+            pMapping->hatasbutton[ button ].mask = mask;
+            ridx = (hat << 4) | mask;
+            pMapping->rhatasbutton[ ridx ] = button;
+        }
+        else if ( axis != SDL_CONTROLLER_AXIS_INVALID )
+        {
+            SDL_assert( !"Support hat as axis" );
+        }
+        else
+        {
+            SDL_assert( !"How did we get here?" );
+        }
+    }
+}
+
+
+/*
+ * given a controller mapping string update our mapping object
+ */
+static void
+SDL_PrivateGameControllerParseControllerConfigString( struct _SDL_ControllerMapping *pMapping, const char *pchString )
+{
+    char szGameButton[20];
+    char szJoystickButton[20];
+    SDL_bool bGameButton = SDL_TRUE;
+    int i = 0;
+    const char *pchPos = pchString;
+
+    SDL_memset( szGameButton, 0x0, sizeof(szGameButton) );
+    SDL_memset( szJoystickButton, 0x0, sizeof(szJoystickButton) );
+
+    while ( pchPos && *pchPos )
+    {
+        if ( *pchPos == ':' )
+        {
+            i = 0;
+            bGameButton = SDL_FALSE;
+        }
+        else if ( *pchPos == ' ' )
+        {
+
+        }
+        else if ( *pchPos == ',' )
+        {
+            i = 0;
+            bGameButton = SDL_TRUE;
+            SDL_PrivateGameControllerParseButton( szGameButton, szJoystickButton, pMapping );
+            SDL_memset( szGameButton, 0x0, sizeof(szGameButton) );
+            SDL_memset( szJoystickButton, 0x0, sizeof(szJoystickButton) );
+
+        }
+        else if ( bGameButton )
+        {
+            if ( i >=  sizeof(szGameButton))
+            {
+                SDL_SetError( "Button name too large: %s", szGameButton );
+                return;
+            }
+            szGameButton[i] = *pchPos;
+            i++;
+        }
+        else
+        {
+            if ( i >=  sizeof(szJoystickButton))
+            {
+                SDL_SetError( "Joystick button name too large: %s", szJoystickButton );
+                return;
+            }
+            szJoystickButton[i] = *pchPos;
+            i++;
+        }
+        pchPos++;
+    }
+
+    SDL_PrivateGameControllerParseButton( szGameButton, szJoystickButton, pMapping );
+
+}
+
+/*
+ * Make a new button mapping struct
+ */
+void SDL_PrivateLoadButtonMapping( struct _SDL_ControllerMapping *pMapping, SDL_JoystickGUID guid, const char *pchName, const char *pchMapping )
+{
+    int j;
+
+    pMapping->guid = guid;
+    pMapping->name = pchName;
+
+    /* set all the button mappings to non defaults */
+    for ( j = 0; j < SDL_CONTROLLER_AXIS_MAX; j++ )
+    {
+        pMapping->axes[j] = -1;
+        pMapping->buttonasaxis[j] = -1;
+    }
+    for ( j = 0; j < SDL_CONTROLLER_BUTTON_MAX; j++ )
+    {
+        pMapping->buttons[j] = -1;
+        pMapping->axesasbutton[j] = -1;
+        pMapping->hatasbutton[j].hat = -1;
+    }
+
+    for ( j = 0; j < k_nMaxReverseEntries; j++ )
+    {
+        pMapping->raxes[j] = SDL_CONTROLLER_AXIS_INVALID;
+        pMapping->rbuttonasaxis[j] = SDL_CONTROLLER_AXIS_INVALID;
+        pMapping->rbuttons[j] = SDL_CONTROLLER_BUTTON_INVALID;
+        pMapping->raxesasbutton[j] = SDL_CONTROLLER_BUTTON_INVALID;
+    }
+
+    for (j = 0; j < k_nMaxHatEntries; j++)
+    {
+        pMapping->rhatasbutton[j] = SDL_CONTROLLER_BUTTON_INVALID;
+    }
+
+    SDL_PrivateGameControllerParseControllerConfigString( pMapping, pchMapping );
+}
+
+
+/*
+ * grab the guid string from a mapping string
+ */
+char *SDL_PrivateGetControllerGUIDFromMappingString( const char *pMapping )
+{
+    const char *pFirstComma = SDL_strchr( pMapping, ',' );
+    if ( pFirstComma )
+    {
+        char *pchGUID = SDL_malloc( pFirstComma - pMapping + 1 );
+        if ( !pchGUID )
+        {
+            SDL_OutOfMemory();
+            return NULL;
+        }
+        SDL_memcpy( pchGUID, pMapping, pFirstComma - pMapping );
+        pchGUID[ pFirstComma - pMapping ] = 0;
+        return pchGUID;
+    }
+    return NULL;
+}
+
+
+/*
+ * grab the name string from a mapping string
+ */
+char *SDL_PrivateGetControllerNameFromMappingString( const char *pMapping )
+{
+    const char *pFirstComma, *pSecondComma;
+    char *pchName;
+
+    pFirstComma = SDL_strchr( pMapping, ',' );
+    if ( !pFirstComma )
+        return NULL;
+
+    pSecondComma = SDL_strchr( pFirstComma + 1, ',' );
+    if ( !pSecondComma )
+        return NULL;
+
+    pchName = SDL_malloc( pSecondComma - pFirstComma );
+    if ( !pchName )
+    {
+        SDL_OutOfMemory();
+        return NULL;
+    }
+    SDL_memcpy( pchName, pFirstComma + 1, pSecondComma - pFirstComma );
+    pchName[ pSecondComma - pFirstComma - 1 ] = 0;
+    return pchName;
+}
+
+
+/*
+ * grab the button mapping string from a mapping string
+ */
+char *SDL_PrivateGetControllerMappingFromMappingString( const char *pMapping )
+{
+    const char *pFirstComma, *pSecondComma;
+
+    pFirstComma = SDL_strchr( pMapping, ',' );
+    if ( !pFirstComma )
+        return NULL;
+
+    pSecondComma = SDL_strchr( pFirstComma + 1, ',' );
+    if ( !pSecondComma )
+        return NULL;
+
+    return SDL_strdup(pSecondComma + 1); /* mapping is everything after the 3rd comma */
+}
+
+void SDL_PrivateGameControllerRefreshMapping( ControllerMapping_t *pControllerMapping )
+{
+    SDL_GameController *gamecontrollerlist = SDL_gamecontrollers;
+    while ( gamecontrollerlist )
+    {
+        if ( !SDL_memcmp( &gamecontrollerlist->mapping.guid, &pControllerMapping->guid, sizeof(pControllerMapping->guid) ) )
+        {
+            SDL_Event event;
+            event.type = SDL_CONTROLLERDEVICEREMAPPED;
+            event.cdevice.which = gamecontrollerlist->joystick->instance_id;
+            SDL_PushEvent(&event);
+
+            /* Not really threadsafe.  Should this lock access within SDL_GameControllerEventWatcher? */
+            SDL_PrivateLoadButtonMapping(&gamecontrollerlist->mapping, pControllerMapping->guid, pControllerMapping->name, pControllerMapping->mapping);
+        }
+
+        gamecontrollerlist = gamecontrollerlist->next;
+    }
+}
+
+/*
+ * Add or update an entry into the Mappings Database
+ */
+int
+SDL_GameControllerAddMapping( const char *mappingString )
+{
+    char *pchGUID;
+    char *pchName;
+    char *pchMapping;
+    SDL_JoystickGUID jGUID;
+    ControllerMapping_t *pControllerMapping;
+#if defined(SDL_JOYSTICK_DINPUT) || defined(SDL_JOYSTICK_XINPUT)
+    SDL_bool is_xinput_mapping = SDL_FALSE;
+#endif
+
+    pchGUID = SDL_PrivateGetControllerGUIDFromMappingString( mappingString );
+    if (!pchGUID) {
+        return -1;
+    }
+#if defined(SDL_JOYSTICK_DINPUT) || defined(SDL_JOYSTICK_XINPUT)
+    if ( !SDL_strcasecmp( pchGUID, "xinput" ) ) {
+        is_xinput_mapping = SDL_TRUE;
+    }
+#endif
+    jGUID = SDL_JoystickGetGUIDFromString(pchGUID);
+    SDL_free(pchGUID);
+
+    pControllerMapping = SDL_PrivateGetControllerMappingForGUID(&jGUID);
+
+    pchName = SDL_PrivateGetControllerNameFromMappingString( mappingString );
+    if (!pchName) return -1;
+
+    pchMapping = SDL_PrivateGetControllerMappingFromMappingString( mappingString );
+    if (!pchMapping) {
+        SDL_free( pchName );
+        return -1;
+    }
+
+    if (pControllerMapping) {
+        /* Update existing mapping */
+        SDL_free( pControllerMapping->name );
+        pControllerMapping->name = pchName;
+        SDL_free( pControllerMapping->mapping );
+        pControllerMapping->mapping = pchMapping;
+        /* refresh open controllers */
+        SDL_PrivateGameControllerRefreshMapping( pControllerMapping );
+        return 0;
+    } else {
+        pControllerMapping = SDL_malloc( sizeof(*pControllerMapping) );
+        if (!pControllerMapping) {
+            SDL_free( pchName );
+            SDL_free( pchMapping );
+            return SDL_OutOfMemory();
+        }
+#if defined(SDL_JOYSTICK_DINPUT) || defined(SDL_JOYSTICK_XINPUT)
+        if ( is_xinput_mapping )
+        {
+            s_pXInputMapping = pControllerMapping;
+        }
+#endif
+        pControllerMapping->guid = jGUID;
+        pControllerMapping->name = pchName;
+        pControllerMapping->mapping = pchMapping;
+        pControllerMapping->next = s_pSupportedControllers;
+        s_pSupportedControllers = pControllerMapping;
+        return 1;
+    }
+}
+
+/*
+ * Get the mapping string for this GUID
+ */
+char *
+SDL_GameControllerMappingForGUID( SDL_JoystickGUID guid )
+{
+    char *pMappingString = NULL;
+    ControllerMapping_t *mapping = SDL_PrivateGetControllerMappingForGUID(&guid);
+    if (mapping) {
+        char pchGUID[33];
+        size_t needed;
+        SDL_JoystickGetGUIDString(guid, pchGUID, sizeof(pchGUID));
+        /* allocate enough memory for GUID + ',' + name + ',' + mapping + \0 */
+        needed = SDL_strlen(pchGUID) + 1 + SDL_strlen(mapping->name) + 1 + SDL_strlen(mapping->mapping) + 1;
+        pMappingString = SDL_malloc( needed );
+        SDL_snprintf( pMappingString, needed, "%s,%s,%s", pchGUID, mapping->name, mapping->mapping );
+    }
+    return pMappingString;
+}
+
+/*
+ * Get the mapping string for this device
+ */
+char *
+SDL_GameControllerMapping( SDL_GameController * gamecontroller )
+{
+    return SDL_GameControllerMappingForGUID( gamecontroller->mapping.guid );
+}
+
+static void
+SDL_GameControllerLoadHints()
+{
+    const char *hint = SDL_GetHint(SDL_HINT_GAMECONTROLLERCONFIG);
+    if ( hint && hint[0] ) {
+        size_t nchHints = SDL_strlen( hint );
+        char *pUserMappings = SDL_malloc( nchHints + 1 );
+        char *pTempMappings = pUserMappings;
+        SDL_memcpy( pUserMappings, hint, nchHints );
+        while ( pUserMappings ) {
+            char *pchNewLine = NULL;
+
+            pchNewLine = SDL_strchr( pUserMappings, '\n' );
+            if ( pchNewLine )
+                *pchNewLine = '\0';
+
+            SDL_GameControllerAddMapping( pUserMappings );
+
+            if ( pchNewLine )
+                pUserMappings = pchNewLine + 1;
+            else
+                pUserMappings = NULL;
+        }
+        SDL_free(pTempMappings);
+    }
+}
+
+/*
+ * Initialize the game controller system, mostly load our DB of controller config mappings
+ */
+int
+SDL_GameControllerInit(void)
+{
+    int i = 0;
+    const char *pMappingString = NULL;
+    s_pSupportedControllers = NULL;
+    pMappingString = s_ControllerMappings[i];
+    while ( pMappingString )
+    {
+        SDL_GameControllerAddMapping( pMappingString );
+
+        i++;
+        pMappingString = s_ControllerMappings[i];
+    }
+
+    /* load in any user supplied config */
+    SDL_GameControllerLoadHints();
+
+    /* watch for joy events and fire controller ones if needed */
+    SDL_AddEventWatch( SDL_GameControllerEventWatcher, NULL );
+
+    return (0);
+}
+
+
+/*
+ * Get the implementation dependent name of a controller
+ */
+const char *
+SDL_GameControllerNameForIndex(int device_index)
+{
+    ControllerMapping_t *pSupportedController =  SDL_PrivateGetControllerMapping(device_index);
+    if ( pSupportedController )
+    {
+        return pSupportedController->name;
+    }
+    return NULL;
+}
+
+
+/*
+ * Return 1 if the joystick at this device index is a supported controller
+ */
+SDL_bool
+SDL_IsGameController(int device_index)
+{
+    ControllerMapping_t *pSupportedController =  SDL_PrivateGetControllerMapping(device_index);
+    if ( pSupportedController )
+    {
+        return SDL_TRUE;
+    }
+
+    return SDL_FALSE;
+}
+
+/*
+ * Open a controller for use - the index passed as an argument refers to
+ * the N'th controller on the system.  This index is the value which will
+ * identify this controller in future controller events.
+ *
+ * This function returns a controller identifier, or NULL if an error occurred.
+ */
+SDL_GameController *
+SDL_GameControllerOpen(int device_index)
+{
+    SDL_GameController *gamecontroller;
+    SDL_GameController *gamecontrollerlist;
+    ControllerMapping_t *pSupportedController = NULL;
+
+    if ((device_index < 0) || (device_index >= SDL_NumJoysticks())) {
+        SDL_SetError("There are %d joysticks available", SDL_NumJoysticks());
+        return (NULL);
+    }
+
+    gamecontrollerlist = SDL_gamecontrollers;
+    /* If the controller is already open, return it */
+    while ( gamecontrollerlist )
+    {
+        if ( SDL_SYS_GetInstanceIdOfDeviceIndex(device_index) == gamecontrollerlist->joystick->instance_id ) {
+                gamecontroller = gamecontrollerlist;
+                ++gamecontroller->ref_count;
+                return (gamecontroller);
+        }
+        gamecontrollerlist = gamecontrollerlist->next;
+    }
+
+    /* Find a controller mapping */
+    pSupportedController =  SDL_PrivateGetControllerMapping(device_index);
+    if ( !pSupportedController ) {
+        SDL_SetError("Couldn't find mapping for device (%d)", device_index );
+        return (NULL);
+    }
+
+    /* Create and initialize the joystick */
+    gamecontroller = (SDL_GameController *) SDL_malloc((sizeof *gamecontroller));
+    if (gamecontroller == NULL) {
+        SDL_OutOfMemory();
+        return NULL;
+    }
+
+    SDL_memset(gamecontroller, 0, (sizeof *gamecontroller));
+    gamecontroller->joystick = SDL_JoystickOpen(device_index);
+    if ( !gamecontroller->joystick ) {
+        SDL_free(gamecontroller);
+        return NULL;
+    }
+
+    SDL_PrivateLoadButtonMapping( &gamecontroller->mapping, pSupportedController->guid, pSupportedController->name, pSupportedController->mapping );
+
+    /* Add joystick to list */
+    ++gamecontroller->ref_count;
+    /* Link the joystick in the list */
+    gamecontroller->next = SDL_gamecontrollers;
+    SDL_gamecontrollers = gamecontroller;
+
+    SDL_SYS_JoystickUpdate( gamecontroller->joystick );
+
+    return (gamecontroller);
+}
+
+/*
+ * Manually pump for controller updates.
+ */
+void
+SDL_GameControllerUpdate(void)
+{
+    /* Just for API completeness; the joystick API does all the work. */
+    SDL_JoystickUpdate();
+}
+
+
+/*
+ * Get the current state of an axis control on a controller
+ */
+Sint16
+SDL_GameControllerGetAxis(SDL_GameController * gamecontroller, SDL_GameControllerAxis axis)
+{
+    if ( !gamecontroller )
+        return 0;
+
+    if (gamecontroller->mapping.axes[axis] >= 0 )
+    {
+        Sint16 value = ( SDL_JoystickGetAxis( gamecontroller->joystick, gamecontroller->mapping.axes[axis]) );
+        switch (axis)
+        {
+            case SDL_CONTROLLER_AXIS_TRIGGERLEFT:
+            case SDL_CONTROLLER_AXIS_TRIGGERRIGHT:
+                /* Shift it to be 0 - 32767. */
+                value = value / 2 + 16384;
+            default:
+                break;
+        }
+        return value;
+    }
+    else if (gamecontroller->mapping.buttonasaxis[axis] >= 0 )
+    {
+        Uint8 value;
+        value = SDL_JoystickGetButton( gamecontroller->joystick, gamecontroller->mapping.buttonasaxis[axis] );
+        if ( value > 0 )
+            return 32767;
+        return 0;
+    }
+    return 0;
+}
+
+
+/*
+ * Get the current state of a button on a controller
+ */
+Uint8
+SDL_GameControllerGetButton(SDL_GameController * gamecontroller, SDL_GameControllerButton button)
+{
+    if ( !gamecontroller )
+        return 0;
+
+    if ( gamecontroller->mapping.buttons[button] >= 0 )
+    {
+        return ( SDL_JoystickGetButton( gamecontroller->joystick, gamecontroller->mapping.buttons[button] ) );
+    }
+    else if ( gamecontroller->mapping.axesasbutton[button] >= 0 )
+    {
+        Sint16 value;
+        value = SDL_JoystickGetAxis( gamecontroller->joystick, gamecontroller->mapping.axesasbutton[button] );
+        if ( ABS(value) > 32768/2 )
+            return 1;
+        return 0;
+    }
+    else if ( gamecontroller->mapping.hatasbutton[button].hat >= 0 )
+    {
+        Uint8 value;
+        value = SDL_JoystickGetHat( gamecontroller->joystick, gamecontroller->mapping.hatasbutton[button].hat );
+
+        if ( value & gamecontroller->mapping.hatasbutton[button].mask )
+            return 1;
+        return 0;
+    }
+
+    return 0;
+}
+
+/*
+ * Return if the joystick in question is currently attached to the system,
+ *  \return 0 if not plugged in, 1 if still present.
+ */
+SDL_bool
+SDL_GameControllerGetAttached( SDL_GameController * gamecontroller )
+{
+    if ( !gamecontroller )
+        return SDL_FALSE;
+
+    return SDL_JoystickGetAttached(gamecontroller->joystick);
+}
+
+
+/*
+ * Get the number of multi-dimensional axis controls on a joystick
+ */
+const char *
+SDL_GameControllerName(SDL_GameController * gamecontroller)
+{
+    if ( !gamecontroller )
+        return NULL;
+
+    return (gamecontroller->mapping.name);
+}
+
+
+/*
+ * Get the joystick for this controller
+ */
+SDL_Joystick *SDL_GameControllerGetJoystick(SDL_GameController * gamecontroller)
+{
+    if ( !gamecontroller )
+        return NULL;
+
+    return gamecontroller->joystick;
+}
+
+/**
+ * Get the SDL joystick layer binding for this controller axis mapping
+ */
+SDL_GameControllerButtonBind SDL_GameControllerGetBindForAxis(SDL_GameController * gamecontroller, SDL_GameControllerAxis axis)
+{
+    SDL_GameControllerButtonBind bind;
+    SDL_memset( &bind, 0x0, sizeof(bind) );
+
+    if ( !gamecontroller || axis == SDL_CONTROLLER_AXIS_INVALID )
+        return bind;
+
+    if (gamecontroller->mapping.axes[axis] >= 0 )
+    {
+        bind.bindType = SDL_CONTROLLER_BINDTYPE_AXIS;
+        bind.value.button = gamecontroller->mapping.axes[axis];
+    }
+    else if (gamecontroller->mapping.buttonasaxis[axis] >= 0 )
+    {
+        bind.bindType = SDL_CONTROLLER_BINDTYPE_BUTTON;
+        bind.value.button = gamecontroller->mapping.buttonasaxis[axis];
+    }
+
+    return bind;
+}
+
+
+/**
+ * Get the SDL joystick layer binding for this controller button mapping
+ */
+SDL_GameControllerButtonBind SDL_GameControllerGetBindForButton(SDL_GameController * gamecontroller, SDL_GameControllerButton button)
+{
+    SDL_GameControllerButtonBind bind;
+    SDL_memset( &bind, 0x0, sizeof(bind) );
+
+    if ( !gamecontroller || button == SDL_CONTROLLER_BUTTON_INVALID )
+        return bind;
+
+    if ( gamecontroller->mapping.buttons[button] >= 0 )
+    {
+        bind.bindType = SDL_CONTROLLER_BINDTYPE_BUTTON;
+        bind.value.button = gamecontroller->mapping.buttons[button];
+    }
+    else if ( gamecontroller->mapping.axesasbutton[button] >= 0 )
+    {
+        bind.bindType = SDL_CONTROLLER_BINDTYPE_AXIS;
+        bind.value.axis = gamecontroller->mapping.axesasbutton[button];
+    }
+    else if ( gamecontroller->mapping.hatasbutton[button].hat >= 0 )
+    {
+        bind.bindType = SDL_CONTROLLER_BINDTYPE_HAT;
+        bind.value.hat.hat = gamecontroller->mapping.hatasbutton[button].hat;
+        bind.value.hat.hat_mask = gamecontroller->mapping.hatasbutton[button].mask;
+    }
+
+    return bind;
+}
+
+
+/*
+ * Close a joystick previously opened with SDL_JoystickOpen()
+ */
+void
+SDL_GameControllerClose(SDL_GameController * gamecontroller)
+{
+    SDL_GameController *gamecontrollerlist, *gamecontrollerlistprev;
+
+    if ( !gamecontroller )
+        return;
+
+    /* First decrement ref count */
+    if (--gamecontroller->ref_count > 0) {
+        return;
+    }
+
+    SDL_JoystickClose( gamecontroller->joystick );
+
+    gamecontrollerlist = SDL_gamecontrollers;
+    gamecontrollerlistprev = NULL;
+    while ( gamecontrollerlist )
+    {
+        if (gamecontroller == gamecontrollerlist)
+        {
+            if ( gamecontrollerlistprev )
+            {
+                /* unlink this entry */
+                gamecontrollerlistprev->next = gamecontrollerlist->next;
+            }
+            else
+            {
+                SDL_gamecontrollers = gamecontroller->next;
+            }
+
+            break;
+        }
+        gamecontrollerlistprev = gamecontrollerlist;
+        gamecontrollerlist = gamecontrollerlist->next;
+    }
+
+    SDL_free(gamecontroller);
+}
+
+
+/*
+ * Quit the controller subsystem
+ */
+void
+SDL_GameControllerQuit(void)
+{
+    ControllerMapping_t *pControllerMap;
+    while ( SDL_gamecontrollers )
+    {
+        SDL_gamecontrollers->ref_count = 1;
+        SDL_GameControllerClose(SDL_gamecontrollers);
+    }
+
+    while ( s_pSupportedControllers )
+    {
+        pControllerMap = s_pSupportedControllers;
+        s_pSupportedControllers = s_pSupportedControllers->next;
+        SDL_free( pControllerMap->name );
+        SDL_free( pControllerMap );
+    }
+
+    SDL_DelEventWatch( SDL_GameControllerEventWatcher, NULL );
+
+}
+
+/*
+ * Event filter to transform joystick events into appropriate game controller ones
+ */
+int
+SDL_PrivateGameControllerAxis(SDL_GameController * gamecontroller, SDL_GameControllerAxis axis, Sint16 value)
+{
+    int posted;
+
+    /* translate the event, if desired */
+    posted = 0;
+#if !SDL_EVENTS_DISABLED
+    if (SDL_GetEventState(SDL_CONTROLLERAXISMOTION) == SDL_ENABLE) {
+        SDL_Event event;
+        event.type = SDL_CONTROLLERAXISMOTION;
+        event.caxis.which = gamecontroller->joystick->instance_id;
+        event.caxis.axis = axis;
+        event.caxis.value = value;
+        posted = SDL_PushEvent(&event) == 1;
+    }
+#endif /* !SDL_EVENTS_DISABLED */
+    return (posted);
+}
+
+
+/*
+ * Event filter to transform joystick events into appropriate game controller ones
+ */
+int
+SDL_PrivateGameControllerButton(SDL_GameController * gamecontroller, SDL_GameControllerButton button, Uint8 state)
+{
+    int posted;
+#if !SDL_EVENTS_DISABLED
+    SDL_Event event;
+
+    if ( button == SDL_CONTROLLER_BUTTON_INVALID )
+        return (0);
+
+    switch (state) {
+    case SDL_PRESSED:
+        event.type = SDL_CONTROLLERBUTTONDOWN;
+        break;
+    case SDL_RELEASED:
+        event.type = SDL_CONTROLLERBUTTONUP;
+        break;
+    default:
+        /* Invalid state -- bail */
+        return (0);
+    }
+#endif /* !SDL_EVENTS_DISABLED */
+
+    /* translate the event, if desired */
+    posted = 0;
+#if !SDL_EVENTS_DISABLED
+    if (SDL_GetEventState(event.type) == SDL_ENABLE) {
+        event.cbutton.which = gamecontroller->joystick->instance_id;
+        event.cbutton.button = button;
+        event.cbutton.state = state;
+        posted = SDL_PushEvent(&event) == 1;
+    }
+#endif /* !SDL_EVENTS_DISABLED */
+    return (posted);
+}
+
+/*
+ * Turn off controller events
+ */
+int
+SDL_GameControllerEventState(int state)
+{
+#if SDL_EVENTS_DISABLED
+    return SDL_IGNORE;
+#else
+    const Uint32 event_list[] = {
+        SDL_CONTROLLERAXISMOTION, SDL_CONTROLLERBUTTONDOWN, SDL_CONTROLLERBUTTONUP,
+        SDL_CONTROLLERDEVICEADDED, SDL_CONTROLLERDEVICEREMOVED, SDL_CONTROLLERDEVICEREMAPPED,
+    };
+    unsigned int i;
+
+    switch (state) {
+    case SDL_QUERY:
+        state = SDL_IGNORE;
+        for (i = 0; i < SDL_arraysize(event_list); ++i) {
+            state = SDL_EventState(event_list[i], SDL_QUERY);
+            if (state == SDL_ENABLE) {
+                break;
+            }
+        }
+        break;
+    default:
+        for (i = 0; i < SDL_arraysize(event_list); ++i) {
+            SDL_EventState(event_list[i], state);
+        }
+        break;
+    }
+    return (state);
+#endif /* SDL_EVENTS_DISABLED */
+}
+
+/* vi: set ts=4 sw=4 expandtab: */
--- a/src/main/winrt/SDL_winrt_main_NonXAML.cpp	Tue Mar 04 19:49:11 2014 -0500
+++ b/src/main/winrt/SDL_winrt_main_NonXAML.cpp	Sun Mar 09 11:06:11 2014 -0700
@@ -1,56 +1,56 @@
-
-#include <SDL_main.h>
-#include <wrl.h>
-
-/* At least one file in any SDL/WinRT app appears to require compilation
-   with C++/CX, otherwise a Windows Metadata file won't get created, and
-   an APPX0702 build error can appear shortly after linking.
-
-   The following set of preprocessor code forces this file to be compiled
-   as C++/CX, which appears to cause Visual C++ 2012's build tools to
-   create this .winmd file, and will help allow builds of SDL/WinRT apps
-   to proceed without error.
-
-   If other files in an app's project enable C++/CX compilation, then it might
-   be possible for SDL_winrt_main_NonXAML.cpp to be compiled without /ZW,
-   for Visual C++'s build tools to create a winmd file, and for the app to
-   build without APPX0702 errors.  In this case, if
-   SDL_WINRT_METADATA_FILE_AVAILABLE is defined as a C/C++ macro, then
-   the #error (to force C++/CX compilation) will be disabled.
-
-   Please note that /ZW can be specified on a file-by-file basis.  To do this,
-   right click on the file in Visual C++, click Properties, then change the
-   setting through the dialog that comes up.
-*/
-#ifndef SDL_WINRT_METADATA_FILE_AVAILABLE
-#ifndef __cplusplus_winrt
-#error SDL_winrt_main_NonXAML.cpp must be compiled with /ZW, otherwise build errors due to missing .winmd files can occur.
-#endif
-#endif
-
-/* Prevent MSVC++ from warning about threading models when defining our
-   custom WinMain.  The threading model will instead be set via a direct
-   call to Windows::Foundation::Initialize (rather than via an attributed
-   function).
-
-   To note, this warning (C4447) does not seem to come up unless this file
-   is compiled with C++/CX enabled (via the /ZW compiler flag).
-*/
-#ifdef _MSC_VER
-#pragma warning(disable:4447)
-#endif
-
-/* Make sure the function to initialize the Windows Runtime gets linked in. */
-#ifdef _MSC_VER
-#pragma comment(lib, "runtimeobject.lib")
-#endif
-
-int CALLBACK WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
-{
-    if (FAILED(Windows::Foundation::Initialize(RO_INIT_MULTITHREADED))) {
-        return 1;
-    }
-
-    SDL_WinRTRunApp(SDL_main, NULL);
-    return 0;
-}
+
+#include <SDL_main.h>
+#include <wrl.h>
+
+/* At least one file in any SDL/WinRT app appears to require compilation
+   with C++/CX, otherwise a Windows Metadata file won't get created, and
+   an APPX0702 build error can appear shortly after linking.
+
+   The following set of preprocessor code forces this file to be compiled
+   as C++/CX, which appears to cause Visual C++ 2012's build tools to
+   create this .winmd file, and will help allow builds of SDL/WinRT apps
+   to proceed without error.
+
+   If other files in an app's project enable C++/CX compilation, then it might
+   be possible for SDL_winrt_main_NonXAML.cpp to be compiled without /ZW,
+   for Visual C++'s build tools to create a winmd file, and for the app to
+   build without APPX0702 errors.  In this case, if
+   SDL_WINRT_METADATA_FILE_AVAILABLE is defined as a C/C++ macro, then
+   the #error (to force C++/CX compilation) will be disabled.
+
+   Please note that /ZW can be specified on a file-by-file basis.  To do this,
+   right click on the file in Visual C++, click Properties, then change the
+   setting through the dialog that comes up.
+*/
+#ifndef SDL_WINRT_METADATA_FILE_AVAILABLE
+#ifndef __cplusplus_winrt
+#error SDL_winrt_main_NonXAML.cpp must be compiled with /ZW, otherwise build errors due to missing .winmd files can occur.
+#endif
+#endif
+
+/* Prevent MSVC++ from warning about threading models when defining our
+   custom WinMain.  The threading model will instead be set via a direct
+   call to Windows::Foundation::Initialize (rather than via an attributed
+   function).
+
+   To note, this warning (C4447) does not seem to come up unless this file
+   is compiled with C++/CX enabled (via the /ZW compiler flag).
+*/
+#ifdef _MSC_VER
+#pragma warning(disable:4447)
+#endif
+
+/* Make sure the function to initialize the Windows Runtime gets linked in. */
+#ifdef _MSC_VER
+#pragma comment(lib, "runtimeobject.lib")
+#endif
+
+int CALLBACK WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
+{
+    if (FAILED(Windows::Foundation::Initialize(RO_INIT_MULTITHREADED))) {
+        return 1;
+    }
+
+    SDL_WinRTRunApp(SDL_main, NULL);
+    return 0;
+}
--- a/src/render/direct3d11/SDL_render_d3d11.cpp	Tue Mar 04 19:49:11 2014 -0500
+++ b/src/render/direct3d11/SDL_render_d3d11.cpp	Sun Mar 09 11:06:11 2014 -0700
@@ -64,18 +64,18 @@
 static const D3D11_FILTER SDL_D3D11_LINEAR_FILTER = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
 
 /* Vertex shader, common values */
-struct VertexShaderConstants
-{
-    DirectX::XMFLOAT4X4 model;
-    DirectX::XMFLOAT4X4 projectionAndView;
+struct VertexShaderConstants
+{
+    DirectX::XMFLOAT4X4 model;
+    DirectX::XMFLOAT4X4 projectionAndView;
 };
 
 /* Per-vertex data */
-struct VertexPositionColor
-{
-    DirectX::XMFLOAT3 pos;
-    DirectX::XMFLOAT2 tex;
-    DirectX::XMFLOAT4 color;
+struct VertexPositionColor
+{
+    DirectX::XMFLOAT3 pos;
+    DirectX::XMFLOAT2 tex;
+    DirectX::XMFLOAT4 color;
 };
 
 /* Per-texture data */
@@ -83,7 +83,7 @@
 {
     Microsoft::WRL::ComPtr<ID3D11Texture2D> mainTexture;
     Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> mainTextureResourceView;
-    Microsoft::WRL::ComPtr<ID3D11RenderTargetView> mainTextureRenderTargetView;
+    Microsoft::WRL::ComPtr<ID3D11RenderTargetView> mainTextureRenderTargetView;
     SDL_PixelFormat * pixelFormat;
     Microsoft::WRL::ComPtr<ID3D11Texture2D> stagingTexture;
     DirectX::XMINT2 lockedTexturePosition;
@@ -94,18 +94,18 @@
 typedef struct
 {
     Microsoft::WRL::ComPtr<ID3D11Device1> d3dDevice;
-    Microsoft::WRL::ComPtr<ID3D11DeviceContext1> d3dContext;
-    Microsoft::WRL::ComPtr<IDXGISwapChain1> swapChain;
-    Microsoft::WRL::ComPtr<ID3D11RenderTargetView> mainRenderTargetView;
-    Microsoft::WRL::ComPtr<ID3D11RenderTargetView> currentOffscreenRenderTargetView;
-    Microsoft::WRL::ComPtr<ID3D11InputLayout> inputLayout;
-    Microsoft::WRL::ComPtr<ID3D11Buffer> vertexBuffer;
-    Microsoft::WRL::ComPtr<ID3D11VertexShader> vertexShader;
-    Microsoft::WRL::ComPtr<ID3D11PixelShader> texturePixelShader;
-    Microsoft::WRL::ComPtr<ID3D11PixelShader> colorPixelShader;
-    Microsoft::WRL::ComPtr<ID3D11BlendState> blendModeBlend;
-    Microsoft::WRL::ComPtr<ID3D11BlendState> blendModeAdd;
-    Microsoft::WRL::ComPtr<ID3D11BlendState> blendModeMod;
+    Microsoft::WRL::ComPtr<ID3D11DeviceContext1> d3dContext;
+    Microsoft::WRL::ComPtr<IDXGISwapChain1> swapChain;
+    Microsoft::WRL::ComPtr<ID3D11RenderTargetView> mainRenderTargetView;
+    Microsoft::WRL::ComPtr<ID3D11RenderTargetView> currentOffscreenRenderTargetView;
+    Microsoft::WRL::ComPtr<ID3D11InputLayout> inputLayout;
+    Microsoft::WRL::ComPtr<ID3D11Buffer> vertexBuffer;
+    Microsoft::WRL::ComPtr<ID3D11VertexShader> vertexShader;
+    Microsoft::WRL::ComPtr<ID3D11PixelShader> texturePixelShader;
+    Microsoft::WRL::ComPtr<ID3D11PixelShader> colorPixelShader;
+    Microsoft::WRL::ComPtr<ID3D11BlendState> blendModeBlend;
+    Microsoft::WRL::ComPtr<ID3D11BlendState> blendModeAdd;
+    Microsoft::WRL::ComPtr<ID3D11BlendState> blendModeMod;
     Microsoft::WRL::ComPtr<ID3D11SamplerState> nearestPixelSampler;
     Microsoft::WRL::ComPtr<ID3D11SamplerState> linearSampler;
     D3D_FEATURE_LEVEL featureLevel;
@@ -120,11 +120,11 @@
     Microsoft::WRL::ComPtr<ID3D11Buffer> vertexShaderConstants;
 
     // Cached renderer properties.
-    DirectX::XMFLOAT2 windowSizeInDIPs;
+    DirectX::XMFLOAT2 windowSizeInDIPs;
     DirectX::XMFLOAT2 renderTargetSize;
     Windows::Graphics::Display::DisplayOrientations orientation;
 
-    // Transform used for display orientation.
+    // Transform used for display orientation.
     DirectX::XMFLOAT4X4 orientationTransform3D;
 } D3D11_RenderData;
 
@@ -134,123 +134,123 @@
    SDL's shaders are compiled into SDL itself, to simplify distribution.
 
    All Direct3D 11.x shaders were compiled with the following:
-
-   fxc /E"main" /T "<TYPE>" /Fo"<OUTPUT FILE>" "<INPUT FILE>"
-
-     Variables:
-     - <TYPE>: the type of shader.  A table of utilized shader types is
-       listed below.
-     - <OUTPUT FILE>: where to store compiled output
-     - <INPUT FILE>: where to read shader source code from
-
-     Shader types:
-     - ps_4_0_level_9_1: Pixel shader for Windows 8+, including Windows RT
-     - vs_4_0_level_9_1: Vertex shader for Windows 8+, including Windows RT
-     - ps_4_0_level_9_3: Pixel shader for Windows Phone 8
-     - vs_4_0_level_9_3: Vertex shader for Windows Phone 8
-   
-
-   Shader object code was converted to a list of DWORDs via the following
-   *nix style command (available separately from Windows + MSVC):
-
-     hexdump -v -e '6/4 "0x%08.8x, " "\n"' <FILE>
-  */
-#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
-#define D3D11_USE_SHADER_MODEL_4_0_level_9_3
-#else
-#define D3D11_USE_SHADER_MODEL_4_0_level_9_1
-#endif
-
-/* The texture-rendering pixel shader:
-
-    --- D3D11_PixelShader_Textures.hlsl ---
-    Texture2D theTexture : register(t0);
-    SamplerState theSampler : register(s0);
-
-    struct PixelShaderInput
-    {
-        float4 pos : SV_POSITION;
-        float2 tex : TEXCOORD0;
-        float4 color : COLOR0;
-    };
-
-    float4 main(PixelShaderInput input) : SV_TARGET
-    {
-        return theTexture.Sample(theSampler, input.tex) * input.color;
-    }
-*/
-#if defined(D3D11_USE_SHADER_MODEL_4_0_level_9_1)
-static const DWORD D3D11_PixelShader_Textures[] = {
-    0x43425844, 0x6299b59f, 0x155258f2, 0x873ab86a, 0xfcbb6dcd, 0x00000001,
-    0x00000330, 0x00000006, 0x00000038, 0x000000c0, 0x0000015c, 0x000001d8,
-    0x00000288, 0x000002fc, 0x396e6f41, 0x00000080, 0x00000080, 0xffff0200,
-    0x00000058, 0x00000028, 0x00280000, 0x00280000, 0x00280000, 0x00240001,
-    0x00280000, 0x00000000, 0xffff0200, 0x0200001f, 0x80000000, 0xb0030000,
-    0x0200001f, 0x80000000, 0xb00f0001, 0x0200001f, 0x90000000, 0xa00f0800,
-    0x03000042, 0x800f0000, 0xb0e40000, 0xa0e40800, 0x03000005, 0x800f0000,
-    0x80e40000, 0xb0e40001, 0x02000001, 0x800f0800, 0x80e40000, 0x0000ffff,
-    0x52444853, 0x00000094, 0x00000040, 0x00000025, 0x0300005a, 0x00106000,
-    0x00000000, 0x04001858, 0x00107000, 0x00000000, 0x00005555, 0x03001062,
-    0x00101032, 0x00000001, 0x03001062, 0x001010f2, 0x00000002, 0x03000065,
-    0x001020f2, 0x00000000, 0x02000068, 0x00000001, 0x09000045, 0x001000f2,
-    0x00000000, 0x00101046, 0x00000001, 0x00107e46, 0x00000000, 0x00106000,
-    0x00000000, 0x07000038, 0x001020f2, 0x00000000, 0x00100e46, 0x00000000,
-    0x00101e46, 0x00000002, 0x0100003e, 0x54415453, 0x00000074, 0x00000003,
-    0x00000001, 0x00000000, 0x00000003, 0x00000001, 0x00000000, 0x00000000,
-    0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
-    0x00000000, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
-    0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
-    0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46454452, 0x000000a8,
-    0x00000000, 0x00000000, 0x00000002, 0x0000001c, 0xffff0400, 0x00000100,
-    0x00000072, 0x0000005c, 0x00000003, 0x00000000, 0x00000000, 0x00000000,
-    0x00000000, 0x00000001, 0x00000001, 0x00000067, 0x00000002, 0x00000005,
-    0x00000004, 0xffffffff, 0x00000000, 0x00000001, 0x0000000d, 0x53656874,
-    0x6c706d61, 0x74007265, 0x65546568, 0x72757478, 0x694d0065, 0x736f7263,
-    0x2074666f, 0x20295228, 0x4c534c48, 0x61685320, 0x20726564, 0x706d6f43,
-    0x72656c69, 0x332e3920, 0x32392e30, 0x312e3030, 0x34383336, 0xababab00,
-    0x4e475349, 0x0000006c, 0x00000003, 0x00000008, 0x00000050, 0x00000000,
-    0x00000001, 0x00000003, 0x00000000, 0x0000000f, 0x0000005c, 0x00000000,
-    0x00000000, 0x00000003, 0x00000001, 0x00000303, 0x00000065, 0x00000000,
-    0x00000000, 0x00000003, 0x00000002, 0x00000f0f, 0x505f5653, 0x5449534f,
-    0x004e4f49, 0x43584554, 0x44524f4f, 0x4c4f4300, 0xab00524f, 0x4e47534f,
-    0x0000002c, 0x00000001, 0x00000008, 0x00000020, 0x00000000, 0x00000000,
-    0x00000003, 0x00000000, 0x0000000f, 0x545f5653, 0x45475241, 0xabab0054
+
+   fxc /E"main" /T "<TYPE>" /Fo"<OUTPUT FILE>" "<INPUT FILE>"
+
+     Variables:
+     - <TYPE>: the type of shader.  A table of utilized shader types is
+       listed below.
+     - <OUTPUT FILE>: where to store compiled output
+     - <INPUT FILE>: where to read shader source code from
+
+     Shader types:
+     - ps_4_0_level_9_1: Pixel shader for Windows 8+, including Windows RT
+     - vs_4_0_level_9_1: Vertex shader for Windows 8+, including Windows RT
+     - ps_4_0_level_9_3: Pixel shader for Windows Phone 8
+     - vs_4_0_level_9_3: Vertex shader for Windows Phone 8
+   
+
+   Shader object code was converted to a list of DWORDs via the following
+   *nix style command (available separately from Windows + MSVC):
+
+     hexdump -v -e '6/4 "0x%08.8x, " "\n"' <FILE>
+  */
+#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
+#define D3D11_USE_SHADER_MODEL_4_0_level_9_3
+#else
+#define D3D11_USE_SHADER_MODEL_4_0_level_9_1
+#endif
+
+/* The texture-rendering pixel shader:
+
+    --- D3D11_PixelShader_Textures.hlsl ---
+    Texture2D theTexture : register(t0);
+    SamplerState theSampler : register(s0);
+
+    struct PixelShaderInput
+    {
+        float4 pos : SV_POSITION;
+        float2 tex : TEXCOORD0;
+        float4 color : COLOR0;
+    };
+
+    float4 main(PixelShaderInput input) : SV_TARGET
+    {
+        return theTexture.Sample(theSampler, input.tex) * input.color;
+    }
+*/
+#if defined(D3D11_USE_SHADER_MODEL_4_0_level_9_1)
+static const DWORD D3D11_PixelShader_Textures[] = {
+    0x43425844, 0x6299b59f, 0x155258f2, 0x873ab86a, 0xfcbb6dcd, 0x00000001,
+    0x00000330, 0x00000006, 0x00000038, 0x000000c0, 0x0000015c, 0x000001d8,
+    0x00000288, 0x000002fc, 0x396e6f41, 0x00000080, 0x00000080, 0xffff0200,
+    0x00000058, 0x00000028, 0x00280000, 0x00280000, 0x00280000, 0x00240001,
+    0x00280000, 0x00000000, 0xffff0200, 0x0200001f, 0x80000000, 0xb0030000,
+    0x0200001f, 0x80000000, 0xb00f0001, 0x0200001f, 0x90000000, 0xa00f0800,
+    0x03000042, 0x800f0000, 0xb0e40000, 0xa0e40800, 0x03000005, 0x800f0000,
+    0x80e40000, 0xb0e40001, 0x02000001, 0x800f0800, 0x80e40000, 0x0000ffff,
+    0x52444853, 0x00000094, 0x00000040, 0x00000025, 0x0300005a, 0x00106000,
+    0x00000000, 0x04001858, 0x00107000, 0x00000000, 0x00005555, 0x03001062,
+    0x00101032, 0x00000001, 0x03001062, 0x001010f2, 0x00000002, 0x03000065,
+    0x001020f2, 0x00000000, 0x02000068, 0x00000001, 0x09000045, 0x001000f2,
+    0x00000000, 0x00101046, 0x00000001, 0x00107e46, 0x00000000, 0x00106000,
+    0x00000000, 0x07000038, 0x001020f2, 0x00000000, 0x00100e46, 0x00000000,
+    0x00101e46, 0x00000002, 0x0100003e, 0x54415453, 0x00000074, 0x00000003,
+    0x00000001, 0x00000000, 0x00000003, 0x00000001, 0x00000000, 0x00000000,
+    0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
+    0x00000000, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
+    0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
+    0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46454452, 0x000000a8,
+    0x00000000, 0x00000000, 0x00000002, 0x0000001c, 0xffff0400, 0x00000100,
+    0x00000072, 0x0000005c, 0x00000003, 0x00000000, 0x00000000, 0x00000000,
+    0x00000000, 0x00000001, 0x00000001, 0x00000067, 0x00000002, 0x00000005,
+    0x00000004, 0xffffffff, 0x00000000, 0x00000001, 0x0000000d, 0x53656874,
+    0x6c706d61, 0x74007265, 0x65546568, 0x72757478, 0x694d0065, 0x736f7263,
+    0x2074666f, 0x20295228, 0x4c534c48, 0x61685320, 0x20726564, 0x706d6f43,
+    0x72656c69, 0x332e3920, 0x32392e30, 0x312e3030, 0x34383336, 0xababab00,
+    0x4e475349, 0x0000006c, 0x00000003, 0x00000008, 0x00000050, 0x00000000,
+    0x00000001, 0x00000003, 0x00000000, 0x0000000f, 0x0000005c, 0x00000000,
+    0x00000000, 0x00000003, 0x00000001, 0x00000303, 0x00000065, 0x00000000,
+    0x00000000, 0x00000003, 0x00000002, 0x00000f0f, 0x505f5653, 0x5449534f,
+    0x004e4f49, 0x43584554, 0x44524f4f, 0x4c4f4300, 0xab00524f, 0x4e47534f,
+    0x0000002c, 0x00000001, 0x00000008, 0x00000020, 0x00000000, 0x00000000,
+    0x00000003, 0x00000000, 0x0000000f, 0x545f5653, 0x45475241, 0xabab0054
 };
 #elif defined(D3D11_USE_SHADER_MODEL_4_0_level_9_3)
 static const DWORD D3D11_PixelShader_Textures[] = {
-    0x43425844, 0x5876569a, 0x01b6c87e, 0x8447454f, 0xc7f3ef10, 0x00000001,
-    0x00000330, 0x00000006, 0x00000038, 0x000000c0, 0x0000015c, 0x000001d8,
-    0x00000288, 0x000002fc, 0x396e6f41, 0x00000080, 0x00000080, 0xffff0200,
-    0x00000058, 0x00000028, 0x00280000, 0x00280000, 0x00280000, 0x00240001,
-    0x00280000, 0x00000000, 0xffff0201, 0x0200001f, 0x80000000, 0xb0030000,
-    0x0200001f, 0x80000000, 0xb00f0001, 0x0200001f, 0x90000000, 0xa00f0800,
-    0x03000042, 0x800f0000, 0xb0e40000, 0xa0e40800, 0x03000005, 0x800f0000,
-    0x80e40000, 0xb0e40001, 0x02000001, 0x800f0800, 0x80e40000, 0x0000ffff,
-    0x52444853, 0x00000094, 0x00000040, 0x00000025, 0x0300005a, 0x00106000,
-    0x00000000, 0x04001858, 0x00107000, 0x00000000, 0x00005555, 0x03001062,
-    0x00101032, 0x00000001, 0x03001062, 0x001010f2, 0x00000002, 0x03000065,
-    0x001020f2, 0x00000000, 0x02000068, 0x00000001, 0x09000045, 0x001000f2,
-    0x00000000, 0x00101046, 0x00000001, 0x00107e46, 0x00000000, 0x00106000,
-    0x00000000, 0x07000038, 0x001020f2, 0x00000000, 0x00100e46, 0x00000000,
-    0x00101e46, 0x00000002, 0x0100003e, 0x54415453, 0x00000074, 0x00000003,
-    0x00000001, 0x00000000, 0x00000003, 0x00000001, 0x00000000, 0x00000000,
-    0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
-    0x00000000, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
-    0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
-    0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x46454452, 0x000000a8,
-    0x00000000, 0x00000000, 0x00000002, 0x0000001c, 0xffff0400, 0x00000100,
-    0x00000072, 0x0000005c, 0x00000003, 0x00000000, 0x00000000, 0x00000000,
-    0x00000000, 0x00000001, 0x00000001, 0x00000067, 0x00000002, 0x00000005,
-    0x00000004, 0xffffffff, 0x00000000, 0x00000001, 0x0000000d, 0x53656874,
-    0x6c706d61, 0x74007265, 0x65546568, 0x72757478, 0x694d0065, 0x736f7263,
-    0x2074666f, 0x20295228, 0x4c534c48, 0x61685320, 0x20726564, 0x706d6f43,
-    0x72656c69, 0x332e3920, 0x32392e30, 0x312e3030, 0x34383336, 0xababab00,
-    0x4e475349, 0x0000006c, 0x00000003, 0x00000008, 0x00000050, 0x00000000,
-    0x00000001, 0x00000003, 0x00000000, 0x0000000f, 0x0000005c, 0x00000000,
-    0x00000000, 0x00000003, 0x00000001, 0x00000303, 0x00000065, 0x00000000,
-    0x00000000, 0x00000003, 0x00000002, 0x00000f0f, 0x505f5653, 0x5449534f,
-    0x004e4f49, 0x43584554, 0x44524f4f, 0x4c4f4300, 0xab00524f, 0x4e47534f,
-    0x0000002c, 0x00000001, 0x00000008, 0x00000020, 0x00000000, 0x00000000,
+    0x43425844, 0x5876569a, 0x01b6c87e, 0x8447454f, 0xc7f3ef10, 0x00000001,
+    0x00000330, 0x00000006, 0x00000038, 0x000000c0, 0x0000015c, 0x000001d8,
+    0x00000288, 0x000002fc, 0x396e6f41, 0x00000080, 0x00000080, 0xffff0200,
+    0x00000058, 0x00000028, 0x00280000, 0x00280000, 0x00280000, 0x00240001,
+    0x00280000, 0x00000000, 0xffff0201, 0x0200001f, 0x80000000, 0xb0030000,
+    0x0200001f, 0x80000000, 0xb00f0001, 0x0200001f, 0x90000000, 0xa00f0800,
+    0x03000042, 0x800f0000, 0xb0e40000, 0xa0e40800, 0x03000005, 0x800f0000,
+    0x80e40000, 0xb0e40001, 0x02000001, 0x800f0800, 0x80e40000, 0x0000ffff,
+    0x52444853, 0x00000094, 0x00000040, 0x00000025, 0x0300005a, 0x00106000,
+    0x00000000, 0x04001858, 0x00107000, 0x00000000, 0x00005555, 0x03001062,
+    0x00101032, 0x00000001, 0x03001062, 0x001010f2, 0x00000002, 0x03000065,
+    0x001020f2, 0x00000000, 0x02000068, 0x00000001, 0x09000045, 0x001000f2,
+    0x00000000, 0x00101046, 0x00000001, 0x00107e46, 0x00000000, 0x00106000,
+    0x00000000, 0x07000038, 0x001020f2, 0x00000000, 0x00100e46, 0x00000000,
+    0x00101e46, 0x00000002, 0x0100003e, 0x54415453, 0x00000074, 0x00000003,
+    0x00000001, 0x00000000, 0x00000003, 0x00000001, 0x00000000, 0x00000000,
+    0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
+    0x00000000, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
+    0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,