Commits

Leonard Ritter committed 606c8b0

Replaced scons with premake

Comments (0)

Files changed (11)

 syntax:glob
 
-
 ./craftlike
 build
+gen
+Makefile
+*.make
 *.pyc
-options.conf
 *.item
 *.orig
 *.cfg
-.sconsign.dblite
 *.os
 *.so
 .cproject

SConstruct

-
-import os,sys 
-
-env = Environment()
-
-def modify_schema_targets(target, source, env):
-    target = []
-    for fname in source:
-        basename = os.path.splitext(fname.name)[0]
-        target.append(basename + '.dw.cpp')
-        target.append(basename + '.dw.hpp')
-    return target, source
-
-def compile_schema(target, source, env):
-    cpp_out_folder = os.path.dirname(target[0].path)
-    source_paths = ' '.join([f.path for f in source])
-    cmdline = 'dwsc --cpp-out=' + cpp_out_folder + ' ' + source_paths
-    print cmdline
-    return os.system(cmdline) 
-
-env['BUILDERS'].update({
-        'DWSchema' : Builder(
-            action = compile_schema,
-            emitter = modify_schema_targets,
-        )
-})
-
-#env['home_usr'] = os.path.expanduser('~/usr')
-#env['ENV']['PKG_CONFIG_PATH'] = env.Dir('$home_usr/lib/pkgconfig').abspath
-
-craftlike = env.SConscript(dirs=['src'],
-    variant_dir = 'build/$variant_dir',
-    duplicate=0, exports=['env'])
-env.Install('#', craftlike)
+
+project.name = "craftlike"
+project.config["Debug"].bindir = 'build/debug/bin'
+project.config["Debug"].libdir = 'build/debug/lib'
+project.config["Release"].bindir = 'build/release/bin'
+project.config["Release"].libdir = 'build/release/lib'
+
+package = newpackage()
+package.name = "craftlike"
+package.kind = "exe"
+package.config["Debug"].objdir = 'build/debug/craftlike/obj'
+package.config["Release"].objdir = 'build/release/craftlike/obj'
+package.language = "c++"
+-- package.libpaths = { findlib("SDL") }
+-- package.links = { "SDL", "SDL_image" }
+if (linux) then
+    package.buildoptions = { 
+        "`pkg-config --cflags gl sdl SDL_image`"
+    }
+end
+package.links = { "SDL", "SDL_image", "GL", "datenwerkpp" }
+package.prebuildcommands = { 
+    "dwsc --cpp-out=gen src/world.schema"
+}
+package.includepaths = {
+    "gen"
+}
+package.files = {
+    matchrecursive("gen/*.hpp", "gen/*.cpp"),
+    matchrecursive("src/*.hpp", "src/*.cpp"),
+    matchrecursive("src/*.h", "src/*.c")
+}
+

site_scons/README.txt

-This is a local copy of the SCons toolkit at http://bitbucket.org/paniq/sconstoolkit

site_scons/sconstk.py

-
-import sys
-import SCons.Script
-
-def Error(msg):
-    print >> sys.stderr, 'ERROR: ' + msg
-    SCons.Script.Exit(1)

site_scons/site_init.py

-################################################################################
-# build script which distinguishes between the platform we are building on,
-# (a combination of OS and toolkit) and the platform we are building for,
-# a combination of OS and architecture.
-#
-# it should be possible to build multiple objects for multiple targets at
-# the same time.
-#
-# here's a list of platforms we'd like to support:
-#
-#               | linux-gcc | linux-wine-msvc | win32-msvc | win32-mingw | darwin-xcode | darwin-gcc |
-# --------------+-----------+-----------------+------------+-------------+--------------+------------+
-# linux-x86     |     X     |                 |            |             |              |            |
-# --------------+-----------+-----------------+------------+-------------+--------------+------------+
-# linux-x86_64  |     X     |                 |            |             |              |            |
-# --------------+-----------+-----------------+------------+-------------+--------------+------------+
-# win32-x86     |     X     |        X        |     X      |      X      |              |            |
-# --------------+-----------+-----------------+------------+-------------+--------------+------------+
-# win32-x86_64  |     X     |        X        |     X      |      X      |              |            |
-# --------------+-----------+-----------------+------------+-------------+--------------+------------+
-# darwin-x86    |           |                 |            |             |      X       |      X     |
-# --------------+-----------+-----------------+------------+-------------+--------------+------------+
-# darwin-x86_64 |           |                 |            |             |      X       |      X     |
-# --------------+-----------+-----------------+------------+-------------+--------------+------------+
-# android-armv7 |     X     |                 |            |             |              |            |
-# --------------+-----------+-----------------+------------+-------------+--------------+------------+
-# ios-armv6     |           |                 |            |             |      X       |            |
-# --------------+-----------+-----------------+------------+-------------+--------------+------------+
-# ios-armv7     |           |                 |            |             |      X       |            |
-# --------------+-----------+-----------------+------------+-------------+--------------+------------+
-# ios-universal |           |                 |            |             |      X       |            |
-# --------------+-----------+-----------------+------------+-------------+--------------+------------+
-#
-# here is a list of objects we'd like to be able to build:
-# - executable
-# - static library
-# - shared library
-# - visual studio solution & projects
-# - xcode projects
-# - eclipse projects
-# - android projects
-# - wrapper makefiles
-#
-################################################################################
-
-import os
-import sys
-import platform
-import inspect
-import multiprocessing
-
-import SCons.Script
-from sconstk import *
-
-EmptyEnvironment = SCons.Script.Environment
-
-_global_variable_path = 'build.cfg'
-
-_toolchains = {
-    #~ 'linux-gcc',
-    #~ 'linux-wine-msvc',
-    #~ 'win32-msvc',
-    #~ 'win32-mingw',
-    #~ 'darwin-xcode',
-    #~ 'darwin-gcc',
-}
-
-_platforms = {
-    #~ 'linux-x86',
-    #~ 'linux-x86_64',
-    #~ 'win32-x86',
-    #~ 'win32-x86_64',
-    #~ 'darwin-x86',
-    #~ 'darwin-x86_64',
-    #~ 'android-armv7',
-    #~ 'ios-armv6',
-    #~ 'ios-armv7',
-    #~ 'ios-universal',
-}
-
-def add_toolchain(cls):
-    assert cls.name
-    _toolchains[cls.name] = cls
-    return cls
-    
-def add_platform(cls):
-    assert cls.name
-    _platforms[cls.name] = cls
-    return cls
-
-def platform_stats():
-    print "Machine: %s" % platform.machine()
-    print "Processor: %s" % platform.processor()
-    print "System: %s" % platform.system()
-    print "Release: %s" % platform.release()
-    print "Version: %s" % platform.version()
-
-def which(binpath):
-    for path in os.environ['PATH'].split(os.pathsep):
-        filepath = os.path.join(path, binpath)
-        if os.path.isfile(filepath):
-            return filepath
-    return None
-
-################################################################################
-# Platforms
-################################################################################
-
-class Configurable(object):
-    @classmethod
-    def plus_features(cls, **kargs):
-        features = cls.features.copy()
-        features.update(kargs)
-        return features
-
-class Platform(Configurable):
-    name = None
-    features = dict(
-        has_pkgconfig = False,
-        has_aptget = False,
-    )    
-    system = None
-    machine = None
-    machine_libdir = '/lib'
-
-class PlatformLinux(Platform):
-    base = Platform
-    
-    name = 'linux'
-    features = base.plus_features(
-        has_pkgconfig = True,
-        has_aptget = False,
-    )
-    system = "Linux"
-    
-    def __init__(self):
-        self.features = self.plus_features(
-            has_aptget = which('apt-get') or False
-        )
-
-@add_platform
-class PlatformLinux_x86(PlatformLinux):
-    name = PlatformLinux.name + '-x86'
-    machine = "i686"
-
-@add_platform
-class PlatformLinux_x86_64(PlatformLinux):
-    name = PlatformLinux.name + '-x86_64'
-    machine = "x86_64"
-    #machine_libdir = '/lib64'
-
-class PlatformWin32(Platform):
-    name = 'win32'
-    system = "Windows"
-
-@add_platform
-class PlatformWin32_x86(PlatformWin32):
-    name = PlatformWin32.name + '-x86'
-    machine = "x86"
-
-@add_platform
-class PlatformWin32_x86_64(PlatformWin32):
-    name = PlatformWin32.name + '-x86_64'
-
-class PlatformDarwin(Platform):
-    name = 'darwin'
-    system = 'Darwin'
-
-@add_platform
-class PlatformDarwin_x86(PlatformDarwin):
-    name = PlatformDarwin.name + '-x86'
-    machine = "i386"
-
-@add_platform
-class PlatformDarwin_x86_64(PlatformDarwin):
-    name = PlatformDarwin.name + '-x86_64'
-    machine = "x86_64" # just a guess
-
-@add_platform
-class PlatformAdobeAlchemy(Platform):
-    name = 'alchemy'
-
-@add_platform
-class PlatformAndroidARMv7(Platform):
-    name = 'android-armv7'
-
-def PlatformAuto():
-    machine = platform.machine()
-    system = platform.system()
-    for name,pf in _platforms.items():
-        if not inspect.isclass(pf):
-            continue
-        if machine != pf.machine:
-            continue
-        if system != pf.system:
-            continue
-        return pf()
-    platform_stats()
-    Error("The current platform can not be recognized, or is not supported yet.")
-    
-PlatformAuto.name = 'auto'
-add_platform(PlatformAuto)
-
-################################################################################
-# Toolchains
-################################################################################
-
-class Toolchain(Configurable):
-    name = None
-    features = dict(
-        has_pkgconfig = False,
-    )
-    platforms = {
-    }
-    libs = []
-    defines = []
-    flags = ''
-    debug_flags = ''
-    release_flags = ''
-    system = None
-    linkflags = ['']
-    
-    def get_platform_config(self, pf, default=None):
-        config = self.platforms.get(pf.__class__, default)
-        if config is None:
-            keys = sorted([p.name for p in self.platforms])
-            Error("%s toolchain only accepts platforms %r." % (
-                self.name, keys)
-            )
-        return config
-    
-    def configure(self, env, pf):
-        config = self.get_platform_config(pf)
-
-        env['platform'] = pf.name
-        env['toolchain'] = self.name
-
-        features = pf.features.copy()
-        for feature,enabled in self.features.items():
-            if features.has_key(feature):
-                features[feature] = features[feature] and enabled
-            else:
-                features[feature] = enabled
-        
-        for feature,enabled in features.items():
-            env[feature] = enabled
-        
-        env['machine_libdir'] = pf.machine_libdir
-        env.Append(
-            LIBS = self.libs,
-            CPPDEFINES = self.defines,
-        )
-        
-        env.Append(
-            LINKFLAGS = self.linkflags
-        )
-
-        env.MergeFlags(self.flags)
-
-        variant_dir = '/' + pf.name
-        if env['debug']:
-            variant_dir += '/debug'
-            env.MergeFlags(self.debug_flags)
-        else:
-            variant_dir += '/release'
-            env.MergeFlags(self.release_flags)
-        env['variant_dir'] = variant_dir
-        
-        platform_flags = config.get('flags', '')
-        env.MergeFlags(platform_flags)
-        env.Append(
-            LINKFLAGS = config.get('linkflags', [''])
-        )
-
-@add_toolchain
-class ToolchainGCC(Toolchain):
-    base = Toolchain
-    
-    name = 'gcc'
-    features = base.plus_features(
-        has_pkgconfig = True
-    )
-    debug_flags = '-g'
-    release_flags = '-O2'
-    
-@add_toolchain
-class ToolchainDarwinGCC(ToolchainGCC):
-    base = ToolchainGCC
-    
-    name = 'darwin' + base.name
-    system = 'Darwin'
-    flags = '-I/usr/X11R6/include'
-    linkflags = ['-L/usr/X11R6/lib']
-    platforms = {
-        PlatformDarwin_x86 : dict(
-            flags = '-m32',
-            linkflags = ['-m32'],
-        ),
-        PlatformDarwin_x86_64 : dict(
-            flags = '-m64 -fPIC',
-            linkflags = ['-m64'],
-        ),
-    }
-
-@add_toolchain
-class ToolchainLinuxGCC(ToolchainGCC):
-    base =  ToolchainGCC
-    
-    name = 'linux-' + base.name
-    features = base.plus_features(
-    )
-    system = 'Linux'
-    platforms = {
-        PlatformLinux_x86 : dict(
-            flags = '-m32',
-        ),
-        PlatformLinux_x86_64 : dict(
-            flags = '-m64 -fPIC',
-        ),
-    }
-
-@add_toolchain
-class ToolchainWindowsMSVC(Toolchain):
-    base = Toolchain
-    
-    name = 'win32-msvc'
-    system = 'Windows'
-    libs = ['Ws2_32']
-    features = base.plus_features(
-    )
-    
-    #debug_flags = '-g'
-    #release_flags = '-O2'
-    platforms = {
-        PlatformWin32_x86 : dict(
-        ),
-    }
-    
-@add_toolchain
-class ToolchainLinuxAdobeAlchemy(Toolchain):
-    base = Toolchain
-    
-    name = 'linux-alchemy'
-    features = base.plus_features(
-        has_pkgconfig = True
-    )
-    defines = [
-        'ADOBE_ALCHEMY',
-    ]
-    #debug_flags = '-g'
-    #release_flags = '-O2'
-    platforms = {
-        PlatformAdobeAlchemy : dict(
-        ),
-    }
-    
-    def configure(self, env, pf):
-        self.base.configure(self, env, pf)
-        ALCHEMY_HOME = os.environ.get('ALCHEMY_HOME',None)
-        if not ALCHEMY_HOME:
-            Error("ALCHEMY_HOME not set - have you executed "
-                "'source /path/to/alchemy-setup' before running scons?")
-        if not which('gcc').startswith(ALCHEMY_HOME):
-            Error("Path to gcc does not point to ALCHEMY_HOME - "
-                "have you executed 'alc-on' before running scons?")
-    
-def ToolchainAuto():
-    machine = platform.machine()
-    system = platform.system()
-    for name,tc in _toolchains.items():
-        if not inspect.isclass(tc):
-            continue
-        if system != tc.system:
-            continue
-        return tc()
-    platform_stats()
-    Error("The current toolchain can not be recognized, or is not supported yet.")
-
-ToolchainAuto.name = 'auto'
-add_toolchain(ToolchainAuto)
-
-################################################################################
-################################################################################
-
-def PrintCommandLine(s, target, src, env):
-    """s is the original command line, target and src are lists of target
-        and source nodes respectively, and env is the environment."""
-    if s == '<ignore>':
-        return
-    sys.stdout.write(s + u'\n')
-
-def Environment(*custom_args, **custom_kargs):
-    # setup variables
-    vars = Variables(_global_variable_path)
-    vars.AddVariables(
-        BoolVariable('debug', 
-            'Build with debug symbols (if no, optimize).',
-            False),
-        EnumVariable('toolchain',
-            'Tools to use for building.',
-            'auto',
-            allowed_values=sorted(_toolchains.keys())),
-        EnumVariable('platform',
-            'Target platform to build for.',
-            'auto',
-            allowed_values=sorted(_platforms.keys())),
-        EnumVariable('jobs',
-            'Number of jobs to use for building.',
-            min(max(multiprocessing.cpu_count(),1),8),
-            allowed_values=[str(s) for s in range(1,9)]),
-        PathVariable('destdir',
-            'Root path of installation.',
-            '',
-            PathVariable.PathAccept),
-        PathVariable('prefix',
-            'Prefix for all installed files, relative to "destdir".',
-            '/usr/local',
-            PathVariable.PathAccept),
-        PathVariable('bindir',
-            'Prefix for binary files, relative to "prefix".',
-            '/bin',
-            PathVariable.PathAccept),
-        PathVariable('libdir',
-            'Prefix for library files, relative to "prefix".',
-            '$machine_libdir',
-            PathVariable.PathAccept),
-        PathVariable('includedir',
-            'Prefix for include files, relative to "prefix".',
-            '/include',
-            PathVariable.PathAccept),
-        PathVariable('etcdir',
-            'Prefix for config files, relative to "destdir".',
-            '/usr/local/etc',
-            PathVariable.PathAccept),
-        PathVariable('sharedir',
-            'Prefix for shared resources, relative to "prefix".',
-            '/share',
-            PathVariable.PathAccept),
-        PathVariable('docdir',
-            'Prefix for documentation files, relative to "prefix".',
-            '/doc',
-            PathVariable.PathAccept),
-        BoolVariable('tidy', 
-            'Tidy build output.',
-            True),
-    )
-    
-    # setup args/kargs
-    args = custom_args
-    kargs= dict(
-        ENV = os.environ,
-        PRINT_CMD_LINE_FUNC = PrintCommandLine,
-    )
-    kargs.update(kargs)
-    
-    # create environment
-    env = EmptyEnvironment(*args, **kargs)
-    
-    # all tools
-    Tool("xplib")(env)
-    Tool("modular")(env)
-    
-    vars.Update(env)
-    
-    # check for unknown variables
-    unknown = vars.UnknownVariables()
-    if unknown:
-        Error("Unknown variables: %r" % unknown.keys())
-        
-    Help(vars.GenerateHelpText(env))
-    
-    # save options back to file
-    vars.Save(_global_variable_path, env)
-    
-    # try to parallelize builds as much as possible
-    SetOption('num_jobs', int(env['jobs']))
-
-    # monikers to absolute paths
-    env['install_dir'] = '$destdir$prefix'
-    env['install_bin_dir'] = '$install_dir$bindir'
-    env['install_lib_dir'] = '$install_dir$libdir'
-    env['install_include_dir'] = '$install_dir$includedir'
-    env['install_etc_dir'] = '$destdir$etcdir'
-    env['install_share_dir'] = '$install_dir$sharedir'
-    env['install_doc_dir'] = '$install_dir$docdir'
-    
-    # add installation target
-    env.Alias('install', [
-        '$destdir$prefix'
-    ])
-
-    toolchain = _toolchains[env['toolchain']]()
-    platform = _platforms[env['platform']]()
-    
-    toolchain.configure(env, platform)
-    
-    # configure Tidy build output
-    if env['tidy']:
-        if 0: # check for msvc compiler here
-            # MSVC compiler likes to print its own output and does not want
-            # to shut up - so we need to quiet down SCons completely.
-            env.Append(
-                SHCCCOMSTR = "<ignore>",
-                SHCXXCOMSTR = "<ignore>",
-                CCCOMSTR = "<ignore>",
-                CXXCOMSTR = "<ignore>",
-            )
-        else:
-            env.Append(
-                SHCCCOMSTR = "$SOURCE",
-                SHCXXCOMSTR = "$SOURCE",
-                CCCOMSTR = "$SOURCE",
-                CXXCOMSTR = "$SOURCE",
-            )
-        env.Append(
-            ARCOMSTR = "Archiving $TARGET",
-            RANLIBCOMSTR = "Indexing $TARGET",
-            SHLINKCOMSTR = "Linking $TARGET",
-            LINKCOMSTR = "Linking $TARGET",
-            INSTALLSTR = "$SOURCE => $TARGET",
-        )
-    
-    
-    if 'dump' in COMMAND_LINE_TARGETS:
-        print env.Dump()
-        print
-        platform_stats()
-        print
-        print "Toolchain: " + toolchain.name
-        print "Platform: " + platform.name
-        
-        Exit(0)
-    
-    return env

site_scons/site_tools/modular.py

-
-from sconstk import *
-
-def glob_sconscript_dirs(env, targets, sources):
-    targets = []
-    dirtype = type(env.Dir('.'))
-    for source in (sources or [env.Dir('.')]):
-        # include all subdirectory scripts
-        for filename in env.Glob(str(source) + '/*'):
-            if not isinstance(filename, dirtype):
-                continue
-            if str(filename).startswith('.'):
-                continue
-            script_path = env.Glob(str(filename) + '/SConscript')
-            if len(script_path):
-                targets += [filename]
-    
-    return targets
-
-MODULAR_BUILDERS = dict(
-    GlobSConscriptDirs = glob_sconscript_dirs,
-)
-
-def generate(env):
-    env.Append(
-        BUILDERS = MODULAR_BUILDERS
-    )
-    
-def exists(*args):
-    pass

site_scons/site_tools/tool_test.py

-
-def generate(env):
-    print "generate",env
-    
-def exists(*args):
-    pass
-

site_scons/site_tools/xplib.py

-
-import os
-from sconstk import *
-
-def pkg_config(env, target, source, MIN_VERSION=None, DEB_NAME=None, MANUAL=None):
-    source = source[0]
-    error_msg = None
-    missing = False
-    if env['has_pkgconfig']:
-        ret = os.system("pkg-config --exists %s" % source)
-        if ret:
-            missing = True
-            error_msg = "Dependency on %s not satisfied." % source
-        if missing and DEB_NAME:
-            if env.AptGet(DEB_NAME):
-                # check again
-                if os.system("pkg-config --exists %s" % source) == 0:
-                    # reset state
-                    missing = False
-                    error_msg = None
-        if MIN_VERSION and not missing:
-            ret = os.system("pkg-config --exists \'%s >= %s\'" % (source, 
-                MIN_VERSION))
-            if ret:
-                error_msg = "Dependency on %s (>= %s) not satisfied." % (
-                    source, MIN_VERSION)
-        if error_msg:
-            Error(error_msg)
-        env.ParseConfig("pkg-config %s --cflags --libs" % source)
-    elif MANUAL:
-        env.Append(**MANUAL)
-
-def apt_get(env, target, source):
-    if not env['has_aptget']:
-        return
-    deps = ' '.join(source)
-    print "Attempting to install dependencies '%s'..." % deps  
-    ret = os.system('sudo apt-get install %s' % deps)
-    return True if (ret == 0) else False
-
-XPLIB_BUILDERS = dict(
-    PkgConfig = pkg_config,
-    AptGet = apt_get,
-)
-
-def generate(env):
-    env.Append(
-        BUILDERS = XPLIB_BUILDERS
-    )
-    
-def exists(*args):
-    print 'exists',args

src/SConscript

-
-import os
-
-Import('*')
-
-env.DWSchema('world.schema')
-
-env.Append(
-    CPPPATH = [
-        '$home_usr/include',
-        '#build/$variant_dir',
-    ],
-    LIBPATH = [
-        '$home_usr/lib',
-    ],
-    RPATH = [
-        '$home_usr/lib',
-    ],
-    LIBS = [
-        'datenwerkpp',
-    ]
-)
-
-env.PkgConfig('sdl', DEB_NAME='libsdl1.2-dev', MANUAL=dict(
-    CPPPATH = [
-        '/usr/include/SDL',
-        '/usr/local/include/SDL'
-    ],
-    LIBS = [
-        'SDL'
-    ]
-))
-env.PkgConfig('SDL_image', DEB_NAME='libsdl-image1.2-dev', MANUAL=dict(
-    LIBS = [
-        'SDL_image'
-    ]
-))
-#env.PkgConfig('cairomm-1.0')
-#env.PkgConfig('librsvg-2.0')
-#env.PkgConfig('sigc++-2.0')
-env.PkgConfig('gl', MANUAL=dict(
-    LIBS = [
-        'GL'
-    ]
-))
-#env.PkgConfig('SDL_ttf')
-
-craftlike = env.Program('craftlike', env.Glob('*.cpp'))
-
-Return('craftlike')
+/* stbi-1.33 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c
+   when you control the images you're loading
+                                     no warranty implied; use at your own risk
+
+   QUICK NOTES:
+      Primarily of interest to game developers and other people who can
+          avoid problematic images and only need the trivial interface
+
+      JPEG baseline (no JPEG progressive)
+      PNG 8-bit only
+
+      TGA (not sure what subset, if a subset)
+      BMP non-1bpp, non-RLE
+      PSD (composited view only, no extra channels)
+
+      GIF (*comp always reports as 4-channel)
+      HDR (radiance rgbE format)
+      PIC (Softimage PIC)
+
+      - decode from memory or through FILE (define STBI_NO_STDIO to remove code)
+      - decode from arbitrary I/O callbacks
+      - overridable dequantizing-IDCT, YCbCr-to-RGB conversion (define STBI_SIMD)
+
+   Latest revisions:
+      1.33 (2011-07-14) minor fixes suggested by Dave Moore
+      1.32 (2011-07-13) info support for all filetypes (SpartanJ)
+      1.31 (2011-06-19) a few more leak fixes, bug in PNG handling (SpartanJ)
+      1.30 (2011-06-11) added ability to load files via io callbacks (Ben Wenger)
+      1.29 (2010-08-16) various warning fixes from Aurelien Pocheville 
+      1.28 (2010-08-01) fix bug in GIF palette transparency (SpartanJ)
+      1.27 (2010-08-01) cast-to-uint8 to fix warnings (Laurent Gomila)
+                        allow trailing 0s at end of image data (Laurent Gomila)
+      1.26 (2010-07-24) fix bug in file buffering for PNG reported by SpartanJ
+
+   See end of file for full revision history.
+
+   TODO:
+      stbi_info support for BMP,PSD,HDR,PIC
+
+
+ ============================    Contributors    =========================
+              
+ Image formats                                Optimizations & bugfixes
+    Sean Barrett (jpeg, png, bmp)                Fabian "ryg" Giesen
+    Nicolas Schulz (hdr, psd)                                                 
+    Jonathan Dummer (tga)                     Bug fixes & warning fixes           
+    Jean-Marc Lienher (gif)                      Marc LeBlanc               
+    Tom Seddon (pic)                             Christpher Lloyd           
+    Thatcher Ulrich (psd)                        Dave Moore                 
+                                                 Won Chun                   
+                                                 the Horde3D community      
+ Extensions, features                            Janez Zemva                
+    Jetro Lauha (stbi_info)                      Jonathan Blow              
+    James "moose2000" Brown (iPhone PNG)         Laurent Gomila                             
+    Ben "Disch" Wenger (io callbacks)            Aruelien Pocheville
+    Martin "SpartanJ" Golini                     Ryamond Barbiero
+                                                 David Woo
+                                                 
+
+ If your name should be here but isn't, let Sean know.
+
+*/
+
+#ifndef STBI_INCLUDE_STB_IMAGE_H
+#define STBI_INCLUDE_STB_IMAGE_H
+
+// To get a header file for this, either cut and paste the header,
+// or create stb_image.h, #define STBI_HEADER_FILE_ONLY, and
+// then include stb_image.c from it.
+
+////   begin header file  ////////////////////////////////////////////////////
+//
+// Limitations:
+//    - no jpeg progressive support
+//    - non-HDR formats support 8-bit samples only (jpeg, png)
+//    - no delayed line count (jpeg) -- IJG doesn't support either
+//    - no 1-bit BMP
+//    - GIF always returns *comp=4
+//
+// Basic usage (see HDR discussion below):
+//    int x,y,n;
+//    unsigned char *data = stbi_load(filename, &x, &y, &n, 0);
+//    // ... process data if not NULL ... 
+//    // ... x = width, y = height, n = # 8-bit components per pixel ...
+//    // ... replace '0' with '1'..'4' to force that many components per pixel
+//    // ... but 'n' will always be the number that it would have been if you said 0
+//    stbi_image_free(data)
+//
+// Standard parameters:
+//    int *x       -- outputs image width in pixels
+//    int *y       -- outputs image height in pixels
+//    int *comp    -- outputs # of image components in image file
+//    int req_comp -- if non-zero, # of image components requested in result
+//
+// The return value from an image loader is an 'unsigned char *' which points
+// to the pixel data. The pixel data consists of *y scanlines of *x pixels,
+// with each pixel consisting of N interleaved 8-bit components; the first
+// pixel pointed to is top-left-most in the image. There is no padding between
+// image scanlines or between pixels, regardless of format. The number of
+// components N is 'req_comp' if req_comp is non-zero, or *comp otherwise.
+// If req_comp is non-zero, *comp has the number of components that _would_
+// have been output otherwise. E.g. if you set req_comp to 4, you will always
+// get RGBA output, but you can check *comp to easily see if it's opaque.
+//
+// An output image with N components has the following components interleaved
+// in this order in each pixel:
+//
+//     N=#comp     components
+//       1           grey
+//       2           grey, alpha
+//       3           red, green, blue
+//       4           red, green, blue, alpha
+//
+// If image loading fails for any reason, the return value will be NULL,
+// and *x, *y, *comp will be unchanged. The function stbi_failure_reason()
+// can be queried for an extremely brief, end-user unfriendly explanation
+// of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid
+// compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly
+// more user-friendly ones.
+//
+// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized.
+//
+// ===========================================================================
+//
+// iPhone PNG support:
+//
+// By default we convert iphone-formatted PNGs back to RGB; nominally they
+// would silently load as BGR, except the existing code should have just
+// failed on such iPhone PNGs. But you can disable this conversion by
+// by calling stbi_convert_iphone_png_to_rgb(0), in which case
+// you will always just get the native iphone "format" through.
+//
+// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per
+// pixel to remove any premultiplied alpha *only* if the image file explicitly
+// says there's premultiplied data (currently only happens in iPhone images,
+// and only if iPhone convert-to-rgb processing is on).
+//
+// ===========================================================================
+//
+// HDR image support   (disable by defining STBI_NO_HDR)
+//
+// stb_image now supports loading HDR images in general, and currently
+// the Radiance .HDR file format, although the support is provided
+// generically. You can still load any file through the existing interface;
+// if you attempt to load an HDR file, it will be automatically remapped to
+// LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;
+// both of these constants can be reconfigured through this interface:
+//
+//     stbi_hdr_to_ldr_gamma(2.2f);
+//     stbi_hdr_to_ldr_scale(1.0f);
+//
+// (note, do not use _inverse_ constants; stbi_image will invert them
+// appropriately).
+//
+// Additionally, there is a new, parallel interface for loading files as
+// (linear) floats to preserve the full dynamic range:
+//
+//    float *data = stbi_loadf(filename, &x, &y, &n, 0);
+// 
+// If you load LDR images through this interface, those images will
+// be promoted to floating point values, run through the inverse of
+// constants corresponding to the above:
+//
+//     stbi_ldr_to_hdr_scale(1.0f);
+//     stbi_ldr_to_hdr_gamma(2.2f);
+//
+// Finally, given a filename (or an open file or memory block--see header
+// file for details) containing image data, you can query for the "most
+// appropriate" interface to use (that is, whether the image is HDR or
+// not), using:
+//
+//     stbi_is_hdr(char *filename);
+//
+// ===========================================================================
+//
+// I/O callbacks
+//
+// I/O callbacks allow you to read from arbitrary sources, like packaged
+// files or some other source. Data read from callbacks are processed
+// through a small internal buffer (currently 128 bytes) to try to reduce
+// overhead. 
+//
+// The three functions you must define are "read" (reads some bytes of data),
+// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end).
+
+
+#ifndef STBI_NO_STDIO
+
+#if defined(_MSC_VER) && _MSC_VER >= 0x1400
+#define _CRT_SECURE_NO_WARNINGS // suppress bogus warnings about fopen()
+#endif
+
+#include <stdio.h>
+#endif
+
+#define STBI_VERSION 1
+
+enum
+{
+   STBI_default = 0, // only used for req_comp
+
+   STBI_grey       = 1,
+   STBI_grey_alpha = 2,
+   STBI_rgb        = 3,
+   STBI_rgb_alpha  = 4
+};
+
+typedef unsigned char stbi_uc;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// PRIMARY API - works on images of any type
+//
+
+//
+// load image by filename, open file, or memory buffer
+//
+
+extern stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
+
+#ifndef STBI_NO_STDIO
+extern stbi_uc *stbi_load            (char const *filename,     int *x, int *y, int *comp, int req_comp);
+extern stbi_uc *stbi_load_from_file  (FILE *f,                  int *x, int *y, int *comp, int req_comp);
+// for stbi_load_from_file, file pointer is left pointing immediately after image
+#endif
+
+typedef struct
+{
+   int      (*read)  (void *user,char *data,int size);   // fill 'data' with 'size' bytes.  return number of bytes actually read 
+   void     (*skip)  (void *user,unsigned n);            // skip the next 'n' bytes
+   int      (*eof)   (void *user);                       // returns nonzero if we are at end of file/data
+} stbi_io_callbacks;
+
+extern stbi_uc *stbi_load_from_callbacks  (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp);
+
+#ifndef STBI_NO_HDR
+   extern float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
+
+   #ifndef STBI_NO_STDIO
+   extern float *stbi_loadf            (char const *filename,   int *x, int *y, int *comp, int req_comp);
+   extern float *stbi_loadf_from_file  (FILE *f,                int *x, int *y, int *comp, int req_comp);
+   #endif
+   
+   extern float *stbi_loadf_from_callbacks  (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp);
+
+   extern void   stbi_hdr_to_ldr_gamma(float gamma);
+   extern void   stbi_hdr_to_ldr_scale(float scale);
+
+   extern void   stbi_ldr_to_hdr_gamma(float gamma);
+   extern void   stbi_ldr_to_hdr_scale(float scale);
+#endif // STBI_NO_HDR
+
+// stbi_is_hdr is always defined
+extern int    stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user);
+extern int    stbi_is_hdr_from_memory(stbi_uc const *buffer, int len);
+#ifndef STBI_NO_STDIO
+extern int      stbi_is_hdr          (char const *filename);
+extern int      stbi_is_hdr_from_file(FILE *f);
+#endif // STBI_NO_STDIO
+
+
+// get a VERY brief reason for failure
+// NOT THREADSAFE
+extern const char *stbi_failure_reason  (void); 
+
+// free the loaded image -- this is just free()
+extern void     stbi_image_free      (void *retval_from_stbi_load);
+
+// get image dimensions & components without fully decoding
+extern int      stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
+extern int      stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp);
+
+#ifndef STBI_NO_STDIO
+extern int      stbi_info            (char const *filename,     int *x, int *y, int *comp);
+extern int      stbi_info_from_file  (FILE *f,                  int *x, int *y, int *comp);
+
+#endif
+
+
+
+// for image formats that explicitly notate that they have premultiplied alpha,
+// we just return the colors as stored in the file. set this flag to force
+// unpremultiplication. results are undefined if the unpremultiply overflow.
+extern void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply);
+
+// indicate whether we should process iphone images back to canonical format,
+// or just pass them through "as-is"
+extern void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert);
+
+
+// ZLIB client - used by PNG, available for other purposes
+
+extern char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen);
+extern char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen);
+extern int   stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
+
+extern char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen);
+extern int   stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
+
+
+// define faster low-level operations (typically SIMD support)
+#ifdef STBI_SIMD
+typedef void (*stbi_idct_8x8)(stbi_uc *out, int out_stride, short data[64], unsigned short *dequantize);
+// compute an integer IDCT on "input"
+//     input[x] = data[x] * dequantize[x]
+//     write results to 'out': 64 samples, each run of 8 spaced by 'out_stride'
+//                             CLAMP results to 0..255
+typedef void (*stbi_YCbCr_to_RGB_run)(stbi_uc *output, stbi_uc const  *y, stbi_uc const *cb, stbi_uc const *cr, int count, int step);
+// compute a conversion from YCbCr to RGB
+//     'count' pixels
+//     write pixels to 'output'; each pixel is 'step' bytes (either 3 or 4; if 4, write '255' as 4th), order R,G,B
+//     y: Y input channel
+//     cb: Cb input channel; scale/biased to be 0..255
+//     cr: Cr input channel; scale/biased to be 0..255
+
+extern void stbi_install_idct(stbi_idct_8x8 func);
+extern void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func);
+#endif // STBI_SIMD
+
+
+#ifdef __cplusplus
+}
+#endif
+
+//
+//
+////   end header file   /////////////////////////////////////////////////////
+#endif // STBI_INCLUDE_STB_IMAGE_H
+
+#ifndef STBI_HEADER_FILE_ONLY
+
+#ifndef STBI_NO_HDR
+#include <math.h>  // ldexp
+#include <string.h> // strcmp, strtok
+#endif
+
+#ifndef STBI_NO_STDIO
+#include <stdio.h>
+#endif
+#include <stdlib.h>
+#include <memory.h>
+#include <assert.h>
+#include <stdarg.h>
+
+#ifndef _MSC_VER
+   #ifdef __cplusplus
+   #define stbi_inline inline
+   #else
+   #define stbi_inline
+   #endif
+#else
+   #define stbi_inline __forceinline
+#endif
+
+
+// implementation:
+typedef unsigned char  uint8;
+typedef unsigned short uint16;
+typedef   signed short  int16;
+typedef unsigned int   uint32;
+typedef   signed int    int32;
+typedef unsigned int   uint;
+
+// should produce compiler error if size is wrong
+typedef unsigned char validate_uint32[sizeof(uint32)==4 ? 1 : -1];
+
+#if defined(STBI_NO_STDIO) && !defined(STBI_NO_WRITE)
+#define STBI_NO_WRITE
+#endif
+
+#define STBI_NOTUSED(v)  (void)sizeof(v)
+
+#ifdef _MSC_VER
+#define STBI_HAS_LROTL
+#endif
+
+#ifdef STBI_HAS_LROTL
+   #define stbi_lrot(x,y)  _lrotl(x,y)
+#else
+   #define stbi_lrot(x,y)  (((x) << (y)) | ((x) >> (32 - (y))))
+#endif
+
+///////////////////////////////////////////////
+//
+//  stbi struct and start_xxx functions
+
+// stbi structure is our basic context used by all images, so it
+// contains all the IO context, plus some basic image information
+typedef struct
+{
+   uint32 img_x, img_y;
+   int img_n, img_out_n;
+   
+   stbi_io_callbacks io;
+   void *io_user_data;
+
+   int read_from_callbacks;
+   int buflen;
+   uint8 buffer_start[128];
+
+   uint8 *img_buffer, *img_buffer_end;
+   uint8 *img_buffer_original;
+} stbi;
+
+
+static void refill_buffer(stbi *s);
+
+// initialize a memory-decode context
+static void start_mem(stbi *s, uint8 const *buffer, int len)
+{
+   s->io.read = NULL;
+   s->read_from_callbacks = 0;
+   s->img_buffer = s->img_buffer_original = (uint8 *) buffer;
+   s->img_buffer_end = (uint8 *) buffer+len;
+}
+
+// initialize a callback-based context
+static void start_callbacks(stbi *s, stbi_io_callbacks *c, void *user)
+{
+   s->io = *c;
+   s->io_user_data = user;
+   s->buflen = sizeof(s->buffer_start);
+   s->read_from_callbacks = 1;
+   s->img_buffer_original = s->buffer_start;
+   refill_buffer(s);
+}
+
+#ifndef STBI_NO_STDIO
+
+static int stdio_read(void *user, char *data, int size)
+{
+   return (int) fread(data,1,size,(FILE*) user);
+}
+
+static void stdio_skip(void *user, unsigned n)
+{
+   fseek((FILE*) user, n, SEEK_CUR);
+}
+
+static int stdio_eof(void *user)
+{
+   return feof((FILE*) user);
+}
+
+static stbi_io_callbacks stbi_stdio_callbacks =
+{
+   stdio_read,
+   stdio_skip,
+   stdio_eof,
+};
+
+static void start_file(stbi *s, FILE *f)
+{
+   start_callbacks(s, &stbi_stdio_callbacks, (void *) f);
+}
+
+//static void stop_file(stbi *s) { }
+
+#endif // !STBI_NO_STDIO
+
+static void stbi_rewind(stbi *s)
+{
+   // conceptually rewind SHOULD rewind to the beginning of the stream,
+   // but we just rewind to the beginning of the initial buffer, because
+   // we only use it after doing 'test', which only ever looks at at most 92 bytes
+   s->img_buffer = s->img_buffer_original;
+}
+
+static int      stbi_jpeg_test(stbi *s);
+static stbi_uc *stbi_jpeg_load(stbi *s, int *x, int *y, int *comp, int req_comp);
+static int      stbi_jpeg_info(stbi *s, int *x, int *y, int *comp);
+static int      stbi_png_test(stbi *s);
+static stbi_uc *stbi_png_load(stbi *s, int *x, int *y, int *comp, int req_comp);
+static int      stbi_png_info(stbi *s, int *x, int *y, int *comp);
+static int      stbi_bmp_test(stbi *s);
+static stbi_uc *stbi_bmp_load(stbi *s, int *x, int *y, int *comp, int req_comp);
+static int      stbi_tga_test(stbi *s);
+static stbi_uc *stbi_tga_load(stbi *s, int *x, int *y, int *comp, int req_comp);
+static int      stbi_tga_info(stbi *s, int *x, int *y, int *comp);
+static int      stbi_psd_test(stbi *s);
+static stbi_uc *stbi_psd_load(stbi *s, int *x, int *y, int *comp, int req_comp);
+static int      stbi_hdr_test(stbi *s);
+static float   *stbi_hdr_load(stbi *s, int *x, int *y, int *comp, int req_comp);
+static int      stbi_pic_test(stbi *s);
+static stbi_uc *stbi_pic_load(stbi *s, int *x, int *y, int *comp, int req_comp);
+static int      stbi_gif_test(stbi *s);
+static stbi_uc *stbi_gif_load(stbi *s, int *x, int *y, int *comp, int req_comp);
+static int      stbi_gif_info(stbi *s, int *x, int *y, int *comp);
+
+
+// this is not threadsafe
+static const char *failure_reason;
+
+const char *stbi_failure_reason(void)
+{
+   return failure_reason;
+}
+
+static int e(const char *str)
+{
+   failure_reason = str;
+   return 0;
+}
+
+// e - error
+// epf - error returning pointer to float
+// epuc - error returning pointer to unsigned char
+
+#ifdef STBI_NO_FAILURE_STRINGS
+   #define e(x,y)  0
+#elif defined(STBI_FAILURE_USERMSG)
+   #define e(x,y)  e(y)
+#else
+   #define e(x,y)  e(x)
+#endif
+
+#define epf(x,y)   ((float *) (e(x,y)?NULL:NULL))
+#define epuc(x,y)  ((unsigned char *) (e(x,y)?NULL:NULL))
+
+void stbi_image_free(void *retval_from_stbi_load)
+{
+   free(retval_from_stbi_load);
+}
+
+#ifndef STBI_NO_HDR
+static float   *ldr_to_hdr(stbi_uc *data, int x, int y, int comp);
+static stbi_uc *hdr_to_ldr(float   *data, int x, int y, int comp);
+#endif
+
+static unsigned char *stbi_load_main(stbi *s, int *x, int *y, int *comp, int req_comp)
+{
+   if (stbi_jpeg_test(s)) return stbi_jpeg_load(s,x,y,comp,req_comp);
+   if (stbi_png_test(s))  return stbi_png_load(s,x,y,comp,req_comp);
+   if (stbi_bmp_test(s))  return stbi_bmp_load(s,x,y,comp,req_comp);
+   if (stbi_gif_test(s))  return stbi_gif_load(s,x,y,comp,req_comp);
+   if (stbi_psd_test(s))  return stbi_psd_load(s,x,y,comp,req_comp);
+   if (stbi_pic_test(s))  return stbi_pic_load(s,x,y,comp,req_comp);
+
+   #ifndef STBI_NO_HDR
+   if (stbi_hdr_test(s)) {
+      float *hdr = stbi_hdr_load(s, x,y,comp,req_comp);
+      return hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);
+   }
+   #endif
+
+   // test tga last because it's a crappy test!
+   if (stbi_tga_test(s))
+      return stbi_tga_load(s,x,y,comp,req_comp);
+   return epuc("unknown image type", "Image not of any known type, or corrupt");
+}
+
+#ifndef STBI_NO_STDIO
+unsigned char *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp)
+{
+   FILE *f = fopen(filename, "rb");
+   unsigned char *result;
+   if (!f) return epuc("can't fopen", "Unable to open file");
+   result = stbi_load_from_file(f,x,y,comp,req_comp);
+   fclose(f);
+   return result;
+}
+
+unsigned char *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
+{
+   stbi s;
+   start_file(&s,f);
+   return stbi_load_main(&s,x,y,comp,req_comp);
+}
+#endif //!STBI_NO_STDIO
+
+unsigned char *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
+{
+   stbi s;
+   start_mem(&s,buffer,len);
+   return stbi_load_main(&s,x,y,comp,req_comp);
+}
+
+unsigned char *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
+{
+   stbi s;
+   start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
+   return stbi_load_main(&s,x,y,comp,req_comp);
+}
+
+#ifndef STBI_NO_HDR
+
+float *stbi_loadf_main(stbi *s, int *x, int *y, int *comp, int req_comp)
+{
+   unsigned char *data;
+   #ifndef STBI_NO_HDR
+   if (stbi_hdr_test(s))
+      return stbi_hdr_load(s,x,y,comp,req_comp);
+   #endif
+   data = stbi_load_main(s, x, y, comp, req_comp);
+   if (data)
+      return ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
+   return epf("unknown image type", "Image not of any known type, or corrupt");
+}
+
+float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
+{
+   stbi s;
+   start_mem(&s,buffer,len);
+   return stbi_loadf_main(&s,x,y,comp,req_comp);
+}
+
+float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
+{
+   stbi s;
+   start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
+   return stbi_loadf_main(&s,x,y,comp,req_comp);
+}
+
+#ifndef STBI_NO_STDIO
+float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)
+{
+   FILE *f = fopen(filename, "rb");
+   float *result;
+   if (!f) return epf("can't fopen", "Unable to open file");
+   result = stbi_loadf_from_file(f,x,y,comp,req_comp);
+   fclose(f);
+   return result;
+}
+
+float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
+{
+   stbi s;
+   start_file(&s,f);
+   return stbi_loadf_main(&s,x,y,comp,req_comp);
+}
+#endif // !STBI_NO_STDIO
+
+#endif // !STBI_NO_HDR
+
+// these is-hdr-or-not is defined independent of whether STBI_NO_HDR is
+// defined, for API simplicity; if STBI_NO_HDR is defined, it always
+// reports false!
+
+int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)
+{
+   #ifndef STBI_NO_HDR
+   stbi s;
+   start_mem(&s,buffer,len);
+   return stbi_hdr_test(&s);
+   #else
+   STBI_NOTUSED(buffer);
+   STBI_NOTUSED(len);
+   return 0;
+   #endif
+}
+
+#ifndef STBI_NO_STDIO
+extern int      stbi_is_hdr          (char const *filename)
+{
+   FILE *f = fopen(filename, "rb");
+   int result=0;
+   if (f) {
+      result = stbi_is_hdr_from_file(f);
+      fclose(f);
+   }
+   return result;
+}
+
+extern int      stbi_is_hdr_from_file(FILE *f)
+{
+   #ifndef STBI_NO_HDR
+   stbi s;
+   start_file(&s,f);
+   return stbi_hdr_test(&s);
+   #else
+   return 0;
+   #endif
+}
+#endif // !STBI_NO_STDIO
+
+extern int      stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user)
+{
+   #ifndef STBI_NO_HDR
+   stbi s;
+   start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
+   return stbi_hdr_test(&s);
+   #else
+   return 0;
+   #endif
+}
+
+#ifndef STBI_NO_HDR
+static float h2l_gamma_i=1.0f/2.2f, h2l_scale_i=1.0f;
+static float l2h_gamma=2.2f, l2h_scale=1.0f;
+
+void   stbi_hdr_to_ldr_gamma(float gamma) { h2l_gamma_i = 1/gamma; }
+void   stbi_hdr_to_ldr_scale(float scale) { h2l_scale_i = 1/scale; }
+
+void   stbi_ldr_to_hdr_gamma(float gamma) { l2h_gamma = gamma; }
+void   stbi_ldr_to_hdr_scale(float scale) { l2h_scale = scale; }
+#endif
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// Common code used by all image loaders
+//
+
+enum
+{
+   SCAN_load=0,
+   SCAN_type,
+   SCAN_header
+};
+
+static void refill_buffer(stbi *s)
+{
+   int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen);
+   if (n == 0) {
+      // at end of file, treat same as if from memory
+      s->read_from_callbacks = 0;
+      s->img_buffer = s->img_buffer_end-1;
+      *s->img_buffer = 0;
+   } else {
+      s->img_buffer = s->buffer_start;
+      s->img_buffer_end = s->buffer_start + n;
+   }
+}
+
+stbi_inline static int get8(stbi *s)
+{
+   if (s->img_buffer < s->img_buffer_end)
+      return *s->img_buffer++;
+   if (s->read_from_callbacks) {
+      refill_buffer(s);
+      return *s->img_buffer++;
+   }
+   return 0;
+}
+
+stbi_inline static int at_eof(stbi *s)
+{
+   if (s->io.read) {
+      if (!(s->io.eof)(s->io_user_data)) return 0;
+      // if feof() is true, check if buffer = end
+      // special case: we've only got the special 0 character at the end
+      if (s->read_from_callbacks == 0) return 1;
+   }
+
+   return s->img_buffer >= s->img_buffer_end;   
+}
+
+stbi_inline static uint8 get8u(stbi *s)
+{
+   return (uint8) get8(s);
+}
+
+static void skip(stbi *s, int n)
+{
+   if (s->io.read) {
+      int blen = s->img_buffer_end - s->img_buffer;
+      if (blen < n) {
+         s->img_buffer = s->img_buffer_end;
+         (s->io.skip)(s->io_user_data, n - blen);
+         return;
+      }
+   }
+   s->img_buffer += n;
+}
+
+static int getn(stbi *s, stbi_uc *buffer, int n)
+{
+   if (s->io.read) {
+      int blen = s->img_buffer_end - s->img_buffer;
+      if (blen < n) {
+         int res, count;
+
+         memcpy(buffer, s->img_buffer, blen);
+         
+         count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen);
+         res = (count == (n-blen));
+         s->img_buffer = s->img_buffer_end;
+         return res;
+      }
+   }
+
+   if (s->img_buffer+n <= s->img_buffer_end) {
+      memcpy(buffer, s->img_buffer, n);
+      s->img_buffer += n;
+      return 1;
+   } else
+      return 0;
+}
+
+static int get16(stbi *s)
+{
+   int z = get8(s);
+   return (z << 8) + get8(s);
+}
+
+static uint32 get32(stbi *s)
+{
+   uint32 z = get16(s);
+   return (z << 16) + get16(s);
+}
+
+static int get16le(stbi *s)
+{
+   int z = get8(s);
+   return z + (get8(s) << 8);
+}
+
+static uint32 get32le(stbi *s)
+{
+   uint32 z = get16le(s);
+   return z + (get16le(s) << 16);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  generic converter from built-in img_n to req_comp
+//    individual types do this automatically as much as possible (e.g. jpeg
+//    does all cases internally since it needs to colorspace convert anyway,
+//    and it never has alpha, so very few cases ). png can automatically
+//    interleave an alpha=255 channel, but falls back to this for other cases
+//
+//  assume data buffer is malloced, so malloc a new one and free that one
+//  only failure mode is malloc failing
+
+static uint8 compute_y(int r, int g, int b)
+{
+   return (uint8) (((r*77) + (g*150) +  (29*b)) >> 8);
+}
+
+static unsigned char *convert_format(unsigned char *data, int img_n, int req_comp, uint x, uint y)
+{
+   int i,j;
+   unsigned char *good;
+
+   if (req_comp == img_n) return data;
+   assert(req_comp >= 1 && req_comp <= 4);
+
+   good = (unsigned char *) malloc(req_comp * x * y);
+   if (good == NULL) {
+      free(data);
+      return epuc("outofmem", "Out of memory");
+   }
+
+   for (j=0; j < (int) y; ++j) {
+      unsigned char *src  = data + j * x * img_n   ;
+      unsigned char *dest = good + j * x * req_comp;
+
+      #define COMBO(a,b)  ((a)*8+(b))
+      #define CASE(a,b)   case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)
+      // convert source image with img_n components to one with req_comp components;
+      // avoid switch per pixel, so use switch per scanline and massive macros
+      switch (COMBO(img_n, req_comp)) {
+         CASE(1,2) dest[0]=src[0], dest[1]=255; break;
+         CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break;
+         CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break;
+         CASE(2,1) dest[0]=src[0]; break;
+         CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break;
+         CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break;
+         CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break;
+         CASE(3,1) dest[0]=compute_y(src[0],src[1],src[2]); break;
+         CASE(3,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = 255; break;
+         CASE(4,1) dest[0]=compute_y(src[0],src[1],src[2]); break;
+         CASE(4,2) dest[0]=compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break;
+         CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break;
+         default: assert(0);
+      }
+      #undef CASE
+   }
+
+   free(data);
+   return good;
+}
+
+#ifndef STBI_NO_HDR
+static float   *ldr_to_hdr(stbi_uc *data, int x, int y, int comp)
+{
+   int i,k,n;
+   float *output = (float *) malloc(x * y * comp * sizeof(float));
+   if (output == NULL) { free(data); return epf("outofmem", "Out of memory"); }
+   // compute number of non-alpha components
+   if (comp & 1) n = comp; else n = comp-1;
+   for (i=0; i < x*y; ++i) {
+      for (k=0; k < n; ++k) {
+         output[i*comp + k] = (float) pow(data[i*comp+k]/255.0f, l2h_gamma) * l2h_scale;
+      }
+      if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f;
+   }
+   free(data);
+   return output;
+}
+
+#define float2int(x)   ((int) (x))
+static stbi_uc *hdr_to_ldr(float   *data, int x, int y, int comp)
+{
+   int i,k,n;
+   stbi_uc *output = (stbi_uc *) malloc(x * y * comp);
+   if (output == NULL) { free(data); return epuc("outofmem", "Out of memory"); }
+   // compute number of non-alpha components
+   if (comp & 1) n = comp; else n = comp-1;
+   for (i=0; i < x*y; ++i) {
+      for (k=0; k < n; ++k) {
+         float z = (float) pow(data[i*comp+k]*h2l_scale_i, h2l_gamma_i) * 255 + 0.5f;
+         if (z < 0) z = 0;
+         if (z > 255) z = 255;
+         output[i*comp + k] = (uint8) float2int(z);
+      }
+      if (k < comp) {
+         float z = data[i*comp+k] * 255 + 0.5f;
+         if (z < 0) z = 0;
+         if (z > 255) z = 255;
+         output[i*comp + k] = (uint8) float2int(z);
+      }
+   }
+   free(data);
+   return output;
+}
+#endif
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  "baseline" JPEG/JFIF decoder (not actually fully baseline implementation)
+//
+//    simple implementation
+//      - channel subsampling of at most 2 in each dimension
+//      - doesn't support delayed output of y-dimension
+//      - simple interface (only one output format: 8-bit interleaved RGB)
+//      - doesn't try to recover corrupt jpegs
+//      - doesn't allow partial loading, loading multiple at once
+//      - still fast on x86 (copying globals into locals doesn't help x86)
+//      - allocates lots of intermediate memory (full size of all components)
+//        - non-interleaved case requires this anyway
+//        - allows good upsampling (see next)
+//    high-quality
+//      - upsampled channels are bilinearly interpolated, even across blocks
+//      - quality integer IDCT derived from IJG's 'slow'
+//    performance
+//      - fast huffman; reasonable integer IDCT
+//      - uses a lot of intermediate memory, could cache poorly
+//      - load http://nothings.org/remote/anemones.jpg 3 times on 2.8Ghz P4
+//          stb_jpeg:   1.34 seconds (MSVC6, default release build)
+//          stb_jpeg:   1.06 seconds (MSVC6, processor = Pentium Pro)
+//          IJL11.dll:  1.08 seconds (compiled by intel)
+//          IJG 1998:   0.98 seconds (MSVC6, makefile provided by IJG)
+//          IJG 1998:   0.95 seconds (MSVC6, makefile + proc=PPro)
+
+// huffman decoding acceleration
+#define FAST_BITS   9  // larger handles more cases; smaller stomps less cache
+
+typedef struct
+{
+   uint8  fast[1 << FAST_BITS];
+   // weirdly, repacking this into AoS is a 10% speed loss, instead of a win
+   uint16 code[256];
+   uint8  values[256];
+   uint8  size[257];
+   unsigned int maxcode[18];
+   int    delta[17];   // old 'firstsymbol' - old 'firstcode'
+} huffman;
+
+typedef struct
+{
+   #ifdef STBI_SIMD
+   unsigned short dequant2[4][64];
+   #endif
+   stbi *s;
+   huffman huff_dc[4];
+   huffman huff_ac[4];
+   uint8 dequant[4][64];
+
+// sizes for components, interleaved MCUs
+   int img_h_max, img_v_max;
+   int img_mcu_x, img_mcu_y;
+   int img_mcu_w, img_mcu_h;
+
+// definition of jpeg image component
+   struct
+   {
+      int id;
+      int h,v;
+      int tq;
+      int hd,ha;
+      int dc_pred;
+
+      int x,y,w2,h2;
+      uint8 *data;
+      void *raw_data;
+      uint8 *linebuf;
+   } img_comp[4];
+
+   uint32         code_buffer; // jpeg entropy-coded buffer
+   int            code_bits;   // number of valid bits
+   unsigned char  marker;      // marker seen while filling entropy buffer
+   int            nomore;      // flag if we saw a marker so must stop
+
+   int scan_n, order[4];
+   int restart_interval, todo;
+} jpeg;
+
+static int build_huffman(huffman *h, int *count)
+{
+   int i,j,k=0,code;
+   // build size list for each symbol (from JPEG spec)
+   for (i=0; i < 16; ++i)
+      for (j=0; j < count[i]; ++j)
+         h->size[k++] = (uint8) (i+1);
+   h->size[k] = 0;
+
+   // compute actual symbols (from jpeg spec)
+   code = 0;
+   k = 0;
+   for(j=1; j <= 16; ++j) {
+      // compute delta to add to code to compute symbol id
+      h->delta[j] = k - code;
+      if (h->size[k] == j) {
+         while (h->size[k] == j)
+            h->code[k++] = (uint16) (code++);
+         if (code-1 >= (1 << j)) return e("bad code lengths","Corrupt JPEG");
+      }
+      // compute largest code + 1 for this size, preshifted as needed later
+      h->maxcode[j] = code << (16-j);
+      code <<= 1;
+   }
+   h->maxcode[j] = 0xffffffff;
+
+   // build non-spec acceleration table; 255 is flag for not-accelerated
+   memset(h->fast, 255, 1 << FAST_BITS);
+   for (i=0; i < k; ++i) {
+      int s = h->size[i];
+      if (s <= FAST_BITS) {
+         int c = h->code[i] << (FAST_BITS-s);
+         int m = 1 << (FAST_BITS-s);
+         for (j=0; j < m; ++j) {
+            h->fast[c+j] = (uint8) i;
+         }
+      }
+   }
+   return 1;
+}
+
+static void grow_buffer_unsafe(jpeg *j)
+{
+   do {
+      int b = j->nomore ? 0 : get8(j->s);
+      if (b == 0xff) {
+         int c = get8(j->s);
+         if (c != 0) {
+            j->marker = (unsigned char) c;
+            j->nomore = 1;
+            return;
+         }
+      }
+      j->code_buffer |= b << (24 - j->code_bits);
+      j->code_bits += 8;
+   } while (j->code_bits <= 24);
+}
+
+// (1 << n) - 1
+static uint32 bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535};
+
+// decode a jpeg huffman value from the bitstream
+stbi_inline static int decode(jpeg *j, huffman *h)
+{
+   unsigned int temp;
+   int c,k;
+
+   if (j->code_bits < 16) grow_buffer_unsafe(j);
+
+   // look at the top FAST_BITS and determine what symbol ID it is,
+   // if the code is <= FAST_BITS
+   c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);
+   k = h->fast[c];
+   if (k < 255) {
+      int s = h->size[k];
+      if (s > j->code_bits)
+         return -1;
+      j->code_buffer <<= s;
+      j->code_bits -= s;
+      return h->values[k];
+   }
+
+   // naive test is to shift the code_buffer down so k bits are
+   // valid, then test against maxcode. To speed this up, we've
+   // preshifted maxcode left so that it has (16-k) 0s at the
+   // end; in other words, regardless of the number of bits, it
+   // wants to be compared against something shifted to have 16;
+   // that way we don't need to shift inside the loop.
+   temp = j->code_buffer >> 16;
+   for (k=FAST_BITS+1 ; ; ++k)
+      if (temp < h->maxcode[k])
+         break;
+   if (k == 17) {
+      // error! code not found
+      j->code_bits -= 16;
+      return -1;
+   }
+
+   if (k > j->code_bits)
+      return -1;
+
+   // convert the huffman code to the symbol id
+   c = ((j->code_buffer >> (32 - k)) & bmask[k]) + h->delta[k];
+   assert((((j->code_buffer) >> (32 - h->size[c])) & bmask[h->size[c]]) == h->code[c]);
+
+   // convert the id to a symbol
+   j->code_bits -= k;
+   j->code_buffer <<= k;
+   return h->values[c];
+}
+
+// combined JPEG 'receive' and JPEG 'extend', since baseline
+// always extends everything it receives.
+stbi_inline static int extend_receive(jpeg *j, int n)
+{
+   unsigned int m = 1 << (n-1);
+   unsigned int k;
+   if (j->code_bits < n) grow_buffer_unsafe(j);
+
+   #if 1
+   k = stbi_lrot(j->code_buffer, n);
+   j->code_buffer = k & ~bmask[n];
+   k &= bmask[n];
+   j->code_bits -= n;
+   #else
+   k = (j->code_buffer >> (32 - n)) & bmask[n];
+   j->code_bits -= n;
+   j->code_buffer <<= n;
+   #endif
+   // the following test is probably a random branch that won't
+   // predict well. I tried to table accelerate it but failed.
+   // maybe it's compiling as a conditional move?
+   if (k < m)
+      return (-1 << n) + k + 1;
+   else
+      return k;
+}
+
+// given a value that's at position X in the zigzag stream,
+// where does it appear in the 8x8 matrix coded as row-major?
+static uint8 dezigzag[64+15] =
+{
+    0,  1,  8, 16,  9,  2,  3, 10,
+   17, 24, 32, 25, 18, 11,  4,  5,
+   12, 19, 26, 33, 40, 48, 41, 34,
+   27, 20, 13,  6,  7, 14, 21, 28,
+   35, 42, 49, 56, 57, 50, 43, 36,
+   29, 22, 15, 23, 30, 37, 44, 51,
+   58, 59, 52, 45, 38, 31, 39, 46,
+   53, 60, 61, 54, 47, 55, 62, 63,
+   // let corrupt input sample past end
+   63, 63, 63, 63, 63, 63, 63, 63,
+   63, 63, 63, 63, 63, 63, 63
+};
+
+// decode one 64-entry block--
+static int decode_block(jpeg *j, short data[64], huffman *hdc, huffman *hac, int b)
+{
+   int diff,dc,k;
+   int t = decode(j, hdc);
+   if (t < 0) return e("bad huffman code","Corrupt JPEG");
+
+   // 0 all the ac values now so we can do it 32-bits at a time
+   memset(data,0,64*sizeof(data[0]));
+
+   diff = t ? extend_receive(j, t) : 0;
+   dc = j->img_comp[b].dc_pred + diff;
+   j->img_comp[b].dc_pred = dc;
+   data[0] = (short) dc;
+
+   // decode AC components, see JPEG spec
+   k = 1;
+   do {
+      int r,s;
+      int rs = decode(j, hac);
+      if (rs < 0) return e("bad huffman code","Corrupt JPEG");
+      s = rs & 15;
+      r = rs >> 4;
+      if (s == 0) {
+         if (rs != 0xf0) break; // end block
+         k += 16;
+      } else {
+         k += r;
+         // decode into unzigzag'd location
+         data[dezigzag[k++]] = (short) extend_receive(j,s);
+      }
+   } while (k < 64);
+   return 1;
+}
+
+// take a -128..127 value and clamp it and convert to 0..255
+stbi_inline static uint8 clamp(int x)
+{
+   // trick to use a single test to catch both cases
+   if ((unsigned int) x > 255) {
+      if (x < 0) return 0;
+      if (x > 255) return 255;
+   }
+   return (uint8) x;
+}
+
+#define f2f(x)  (int) (((x) * 4096 + 0.5))
+#define fsh(x)  ((x) << 12)
+
+// derived from jidctint -- DCT_ISLOW
+#define IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7)       \
+   int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \
+   p2 = s2;                                    \
+   p3 = s6;                                    \
+   p1 = (p2+p3) * f2f(0.5411961f);             \
+   t2 = p1 + p3*f2f(-1.847759065f);            \
+   t3 = p1 + p2*f2f( 0.765366865f);            \
+   p2 = s0;                                    \
+   p3 = s4;                                    \
+   t0 = fsh(p2+p3);                            \
+   t1 = fsh(p2-p3);                            \
+   x0 = t0+t3;                                 \
+   x3 = t0-t3;                                 \
+   x1 = t1+t2;                                 \
+   x2 = t1-t2;                                 \
+   t0 = s7;                                    \
+   t1 = s5;                                    \
+   t2 = s3;                                    \
+   t3 = s1;                                    \
+   p3 = t0+t2;                                 \
+   p4 = t1+t3;                                 \
+   p1 = t0+t3;                                 \
+   p2 = t1+t2;                                 \
+   p5 = (p3+p4)*f2f( 1.175875602f);            \
+   t0 = t0*f2f( 0.298631336f);                 \
+   t1 = t1*f2f( 2.053119869f);                 \
+   t2 = t2*f2f( 3.072711026f);                 \
+   t3 = t3*f2f( 1.501321110f);                 \
+   p1 = p5 + p1*f2f(-0.899976223f);            \
+   p2 = p5 + p2*f2f(-2.562915447f);            \
+   p3 = p3*f2f(-1.961570560f);                 \
+   p4 = p4*f2f(-0.390180644f);                 \
+   t3 += p1+p4;                                \
+   t2 += p2+p3;                                \
+   t1 += p2+p4;                                \
+   t0 += p1+p3;
+
+#ifdef STBI_SIMD
+typedef unsigned short stbi_dequantize_t;
+#else
+typedef uint8 stbi_dequantize_t;
+#endif
+
+// .344 seconds on 3*anemones.jpg
+static void idct_block(uint8 *out, int out_stride, short data[64], stbi_dequantize_t *dequantize)
+{
+   int i,val[64],*v=val;
+   stbi_dequantize_t *dq = dequantize;
+   uint8 *o;
+   short *d = data;
+
+   // columns
+   for (i=0; i < 8; ++i,++d,++dq, ++v) {
+      // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing
+      if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0
+           && d[40]==0 && d[48]==0 && d[56]==0) {
+         //    no shortcut                 0     seconds
+         //    (1|2|3|4|5|6|7)==0          0     seconds
+         //    all separate               -0.047 seconds
+         //    1 && 2|3 && 4|5 && 6|7:    -0.047 seconds
+         int dcterm = d[0] * dq[0] << 2;
+         v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
+      } else {
+         IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],
+                 d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56])
+         // constants scaled things up by 1<<12; let's bring them back
+         // down, but keep 2 extra bits of precision
+         x0 += 512; x1 += 512; x2 += 512; x3 += 512;
+         v[ 0] = (x0+t3) >> 10;
+         v[56] = (x0-t3) >> 10;
+         v[ 8] = (x1+t2) >> 10;
+         v[48] = (x1-t2) >> 10;
+         v[16] = (x2+t1) >> 10;
+         v[40] = (x2-t1) >> 10;
+         v[24] = (x3+t0) >> 10;
+         v[32] = (x3-t0) >> 10;
+      }
+   }
+
+   for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {
+      // no fast case since the first 1D IDCT spread components out
+      IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])
+      // constants scaled things up by 1<<12, plus we had 1<<2 from first
+      // loop, plus horizontal and vertical each scale by sqrt(8) so together
+      // we've got an extra 1<<3, so 1<<17 total we need to remove.
+      // so we want to round that, which means adding 0.5 * 1<<17,
+      // aka 65536. Also, we'll end up with -128 to 127 that we want
+      // to encode as 0..255 by adding 128, so we'll add that before the shift
+      x0 += 65536 + (128<<17);
+      x1 += 65536 + (128<<17);
+      x2 += 65536 + (128<<17);
+      x3 += 65536 + (128<<17);
+      // tried computing the shifts into temps, or'ing the temps to see
+      // if any were out of range, but that was slower
+      o[0] = clamp((x0+t3) >> 17);
+      o[7] = clamp((x0-t3) >> 17);
+      o[1] = clamp((x1+t2) >> 17);
+      o[6] = clamp((x1-t2) >> 17);
+      o[2] = clamp((x2+t1) >> 17);
+      o[5] = clamp((x2-t1) >> 17);
+      o[3] = clamp((x3+t0) >> 17);
+      o[4] = clamp((x3-t0) >> 17);
+   }
+}
+
+#ifdef STBI_SIMD
+static stbi_idct_8x8 stbi_idct_installed = idct_block;
+
+void stbi_install_idct(stbi_idct_8x8 func)
+{
+   stbi_idct_installed = func;
+}
+#endif
+
+#define MARKER_none  0xff
+// if there's a pending marker from the entropy stream, return that
+// otherwise, fetch from the stream and get a marker. if there's no
+// marker, return 0xff, which is never a valid marker value
+static uint8 get_marker(jpeg *j)
+{
+   uint8 x;
+   if (j->marker != MARKER_none) { x = j->marker; j->marker = MARKER_none; return x; }
+   x = get8u(j->s);
+   if (x != 0xff) return MARKER_none;
+   while (x == 0xff)
+      x = get8u(j->s);
+   return x;
+}
+
+// in each scan, we'll have scan_n components, and the order
+// of the components is specified by order[]
+#define RESTART(x)     ((x) >= 0xd0 && (x) <= 0xd7)
+
+// after a restart interval, reset the entropy decoder and
+// the dc prediction
+static void reset(jpeg *j)
+{
+   j->code_bits = 0;
+   j->code_buffer = 0;
+   j->nomore = 0;
+   j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0;
+   j->marker = MARKER_none;
+   j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;
+   // no more than 1<<31 MCUs if no restart_interal? that's plenty safe,
+   // since we don't even allow 1<<30 pixels
+}
+
+static int parse_entropy_coded_data(jpeg *z)
+{
+   reset(z);
+   if (z->scan_n == 1) {
+      int i,j;
+      #ifdef STBI_SIMD
+      __declspec(align(16))
+      #endif
+      short data[64];
+      int n = z->order[0];
+      // non-interleaved data, we just need to process one block at a time,
+      // in trivial scanline order
+      // number of blocks to do just depends on how many actual "pixels" this
+      // component has, independent of interleaved MCU blocking and such
+      int w = (z->img_comp[n].x+7) >> 3;
+      int h = (z->img_comp[n].y+7) >> 3;
+      for (j=0; j < h; ++j) {
+         for (i=0; i < w; ++i) {
+            if (!decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;
+            #ifdef STBI_SIMD
+            stbi_idct_installed(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);
+            #else
+            idct_block(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);
+            #endif
+            // every data block is an MCU, so countdown the restart interval
+            if (--z->todo <= 0) {
+               if (z->code_bits < 24) grow_buffer_unsafe(z);
+               // if it's NOT a restart, then just bail, so we get corrupt data
+               // rather than no data
+               if (!RESTART(z->marker)) return 1;
+               reset(z);
+            }
+         }
+      }
+   } else { // interleaved!
+      int i,j,k,x,y;
+      short data[64];
+      for (j=0; j < z->img_mcu_y; ++j) {