merge... need to remember to update first
authornemo
Sat, 17 Nov 2012 20:30:32 -0500
changeset 8058 bcebfc477459
parent 8054 39f8ea1a441f (current diff)
parent 8057 93e16240f178 (diff)
child 8059 07661fb20586
merge... need to remember to update first
misc/quazip/CMakeLists.txt
misc/quazip/JlCompress.cpp
misc/quazip/JlCompress.h
misc/quazip/crypt.h
misc/quazip/doc/faq.dox
misc/quazip/doc/index.dox
misc/quazip/doc/usage.dox
misc/quazip/ioapi.h
misc/quazip/qioapi.cpp
misc/quazip/quaadler32.cpp
misc/quazip/quaadler32.h
misc/quazip/quachecksum32.h
misc/quazip/quacrc32.cpp
misc/quazip/quacrc32.h
misc/quazip/quazip.cpp
misc/quazip/quazip.h
misc/quazip/quazip.pri
misc/quazip/quazip.pro
misc/quazip/quazip_global.h
misc/quazip/quazipfile.cpp
misc/quazip/quazipfile.h
misc/quazip/quazipfileinfo.h
misc/quazip/quazipnewinfo.cpp
misc/quazip/quazipnewinfo.h
misc/quazip/unzip.c
misc/quazip/unzip.h
misc/quazip/zconf.h
misc/quazip/zip.c
misc/quazip/zip.h
misc/quazip/zlib.h
--- a/CMakeLists.txt	Sat Nov 17 20:27:49 2012 -0500
+++ b/CMakeLists.txt	Sat Nov 17 20:30:32 2012 -0500
@@ -247,6 +247,10 @@
 #main engine
 add_subdirectory(hedgewars)
 
+# physfs library
+add_subdirectory(misc/physfs)
+add_subdirectory(misc/physfs/extras)
+
 #Android related build scripts
 if(ANDROID)
     #run cmake -DANDROID=1 to enable this
@@ -256,7 +260,6 @@
 #TODO: when ANDROID, BUILD_ENGINE_LIBRARY should be set
 if(NOT (BUILD_ENGINE_LIBRARY OR ANDROID))
     add_subdirectory(bin)
-    add_subdirectory(misc/quazip)
     add_subdirectory(QTfrontend)
     add_subdirectory(share)
     add_subdirectory(tools)
--- a/QTfrontend/CMakeLists.txt	Sat Nov 17 20:27:49 2012 -0500
+++ b/QTfrontend/CMakeLists.txt	Sat Nov 17 20:30:32 2012 -0500
@@ -15,16 +15,6 @@
     include(${QT_USE_FILE})
 endif()
 
-# Check if we need zlib
-check_library_exists("${QT_QTCORE_LIBRARY}" inflateInit2_ ${QT_LIBRARY_DIR} QT_PROVIDES_ZLIB_FUNCTIONS)
-
-if(NOT QT_PROVIDES_ZLIB_FUNCTIONS)
-    find_package(ZLIB REQUIRED)
-
-    set(HW_LINK_LIBS ${ZLIB_LIBRARIES} ${HW_LINK_LIBS})
-endif()
-
-
 # Configure for SDL
 find_package(SDL REQUIRED)
 find_package(SDL_mixer REQUIRED)
@@ -43,7 +33,8 @@
 include_directories(${SDL_INCLUDE_DIR})
 include_directories(${SDLMIXER_INCLUDE_DIR})
 include_directories(${FFMPEG_INCLUDE_DIR})
-include_directories(${CMAKE_SOURCE_DIR}/misc/quazip)
+include_directories(${CMAKE_SOURCE_DIR}/misc/physfs/src)
+include_directories(${CMAKE_SOURCE_DIR}/misc/physfs/extras)
 if(UNIX)
     # HACK: in freebsd cannot find iconv.h included via SDL.h
     include_directories("/usr/local/include")
@@ -176,7 +167,8 @@
 
 
 set(HW_LINK_LIBS
-    quazip
+    physfs
+    physfsrwops
     ${QT_LIBRARIES}
     ${SDL_LIBRARY}
     ${SDLMIXER_LIBRARY}
@@ -200,7 +192,7 @@
 
 
 if (CROSSAPPLE)
-    add_dependencies(hedgewars quazip)
+
 else()
     target_link_libraries(hedgewars ${HW_LINK_LIBS})
 endif()
--- a/QTfrontend/campaign.cpp	Sat Nov 17 20:27:49 2012 -0500
+++ b/QTfrontend/campaign.cpp	Sat Nov 17 20:30:32 2012 -0500
@@ -56,7 +56,7 @@
 
 QStringList getCampMissionList(QString & campaign)
 {
-    QSettings campfile(DataManager::instance().findFileForRead("Missions/Campaign/" + campaign + "/campaign.ini"), QSettings::IniFormat, 0);
+    QSettings campfile("physfs://Missions/Campaign/" + campaign + "/campaign.ini", QSettings::IniFormat, 0);
     campfile.setIniCodec("UTF-8");
     unsigned int mNum = campfile.value("MissionNum", 0).toInt();
     
@@ -77,7 +77,7 @@
 
 QString getCampaignScript(QString campaign, unsigned int mNum)
 {
-    QSettings campfile(DataManager::instance().findFileForRead("Missions/Campaign/" + campaign + "/campaign.ini"), QSettings::IniFormat, 0);
+    QSettings campfile("physfs://Missions/Campaign/" + campaign + "/campaign.ini", QSettings::IniFormat, 0);
     campfile.setIniCodec("UTF-8");
     return campfile.value(QString("Mission %1/Script").arg(mNum)).toString();
 }
--- a/QTfrontend/hwform.cpp	Sat Nov 17 20:27:49 2012 -0500
+++ b/QTfrontend/hwform.cpp	Sat Nov 17 20:30:32 2012 -0500
@@ -122,9 +122,7 @@
     , hwnet(0)
 {
     // set music track
-    SDLInteraction::instance().setMusicTrack(
-        DataManager::instance().findFileForRead("Music/main_theme.ogg")
-    );
+    SDLInteraction::instance().setMusicTrack("/Music/main_theme.ogg");
 
 #ifdef USE_XFIRE
     xfire_init();
--- a/QTfrontend/main.cpp	Sat Nov 17 20:27:49 2012 -0500
+++ b/QTfrontend/main.cpp	Sat Nov 17 20:30:32 2012 -0500
@@ -33,6 +33,7 @@
 #include "newnetclient.h"
 
 #include "DataManager.h"
+#include "FileEngine.h"
 
 #ifdef _WIN32
 #include <Shlobj.h>
@@ -106,6 +107,8 @@
 {
     HWApplication app(argc, argv);
 
+    FileEngineHandler engine(argv[0]);
+
     app.setAttribute(Qt::AA_DontShowIconsInMenus,false);
 
     QStringList arguments = app.arguments();
@@ -147,7 +150,7 @@
         custom_config = true;
     }
 
-    app.setStyle(new QPlastiqueStyle);
+    app.setStyle(new QPlastiqueStyle());
 
     QDateTime now = QDateTime::currentDateTime();
     srand(now.toTime_t());
@@ -218,21 +221,23 @@
         return 1;
     }
 
-    DataManager & dataMgr = DataManager::instance();
+    // setup PhysFS
+    engine.mount(datadir->absolutePath());
+    engine.mount(cfgdir->absolutePath() + "/Data");
+    engine.mount(cfgdir->absolutePath(), "/config");
+    engine.setWriteDir(cfgdir->absolutePath());
+    engine.mountPacks();
 
     QTranslator Translator;
     {
-        QSettings settings(cfgdir->absolutePath() + "/hedgewars.ini", QSettings::IniFormat);
+        QSettings settings("physfs://config/hedgewars.ini", QSettings::IniFormat);
         QString cc = settings.value("misc/locale", QString()).toString();
         if(cc.isEmpty())
             cc = QLocale::system().name();
 
         // load locale file into translator
-        Translator.load(
-            dataMgr.findFileForRead(
-                QString("Locale/hedgewars_" + cc)
-            )
-        );
+        if(!Translator.load(QString("physfs://Locale/hedgewars_%1").arg(cc)))
+            qWarning("Failed to install translation");
         app.installTranslator(&Translator);
     }
 
@@ -274,7 +279,7 @@
     }
 
     // load external stylesheet if there is any
-    QFile extFile(dataMgr.findFileForRead("css/" + fname));
+    QFile extFile("physfs://css/" + fname);
 
     QFile resFile(":/res/css/" + fname);
 
--- a/QTfrontend/model/GameStyleModel.cpp	Sat Nov 17 20:27:49 2012 -0500
+++ b/QTfrontend/model/GameStyleModel.cpp	Sat Nov 17 20:30:32 2012 -0500
@@ -55,8 +55,7 @@
     {
         script = script.remove(".lua", Qt::CaseInsensitive);
 
-        QFile scriptCfgFile(DataManager::instance().findFileForRead(
-                            QString("Scripts/Multiplayer/%2.cfg").arg(script)));
+        QFile scriptCfgFile(QString("physfs://Scripts/Multiplayer/%2.cfg").arg(script));
 
         QString name = script;
         name = name.replace("_", " ");
--- a/QTfrontend/model/HatModel.cpp	Sat Nov 17 20:27:49 2012 -0500
+++ b/QTfrontend/model/HatModel.cpp	Sat Nov 17 20:30:32 2012 -0500
@@ -46,9 +46,7 @@
 
     DataManager & dataMgr = DataManager::instance();
 
-    QPixmap hhpix = QPixmap(
-                        dataMgr.findFileForRead("Graphics/Hedgehog/Idle.png")
-                    ).copy(0, 0, 32, 32);
+    QPixmap hhpix = QPixmap("physfs://Graphics/Hedgehog/Idle.png").copy(0, 0, 32, 32);
 
     // my reserved hats
     QStringList hatsList = dataMgr.entryList(
@@ -76,11 +74,9 @@
 
         QString str = hatsList.at(i);
         str = str.remove(QRegExp("\\.png$"));
-        QPixmap pix(
-            dataMgr.findFileForRead(
-                "Graphics/Hats/" + QString(isReserved?"Reserved/":"") + str +
-                ".png"
-            )
+        QPixmap pix(            
+                "physfs://Graphics/Hats/" + QString(isReserved?"Reserved/":"") + str +
+                ".png"           
         );
 
         // rename properly
--- a/QTfrontend/model/MapModel.cpp	Sat Nov 17 20:27:49 2012 -0500
+++ b/QTfrontend/model/MapModel.cpp	Sat Nov 17 20:30:32 2012 -0500
@@ -62,10 +62,8 @@
     // add mission/static maps to lists
     foreach (QString map, maps)
     {
-        mapCfgFile.setFileName(
-            datamgr.findFileForRead(QString("Maps/%1/map.cfg").arg(map)));
-        mapLuaFile.setFileName(
-            datamgr.findFileForRead(QString("Maps/%1/map.lua").arg(map)));
+        mapCfgFile.setFileName(QString("physfs://Maps/%1/map.cfg").arg(map));
+        mapLuaFile.setFileName(QString("physfs://Maps/%1/map.lua").arg(map));
 
 
         if (mapCfgFile.open(QFile::ReadOnly))
--- a/QTfrontend/model/ThemeModel.cpp	Sat Nov 17 20:27:49 2012 -0500
+++ b/QTfrontend/model/ThemeModel.cpp	Sat Nov 17 20:30:32 2012 -0500
@@ -66,8 +66,7 @@
     foreach (QString theme, themes)
     {
         // themes without icon are supposed to be hidden
-        QString iconpath =
-            datamgr.findFileForRead(QString("Themes/%1/icon.png").arg(theme));
+        QString iconpath = QString("physfs://Themes/%1/icon.png").arg(theme);
 
         if (!QFile::exists(iconpath))
             continue;
@@ -79,10 +78,11 @@
 
         // load and set icon
         QIcon icon(iconpath);
+
         dataset.insert(Qt::DecorationRole, icon);
 
         // load and set preview icon
-        QIcon preview(datamgr.findFileForRead(QString("Themes/%1/icon@2x.png").arg(theme)));
+        QIcon preview(QString("physfs://Themes/%1/icon@2x.png").arg(theme));
         dataset.insert(Qt::UserRole, preview);
 
         m_data.append(dataset);
--- a/QTfrontend/team.cpp	Sat Nov 17 20:27:49 2012 -0500
+++ b/QTfrontend/team.cpp	Sat Nov 17 20:30:32 2012 -0500
@@ -169,7 +169,7 @@
 
 bool HWTeam::loadFromFile()
 {
-    QSettings teamfile(cfgdir->absolutePath() + "/Teams/" + m_name + ".hwt", QSettings::IniFormat, 0);
+    QSettings teamfile(QString("physfs://config/Teams/%1.hwt").arg(m_name), QSettings::IniFormat, 0);
     teamfile.setIniCodec("UTF-8");
     m_name = teamfile.value("Team/Name", m_name).toString();
     m_grave = teamfile.value("Team/Grave", "Statue").toString();
@@ -202,7 +202,7 @@
 
 bool HWTeam::fileExists()
 {
-    QFile f(cfgdir->absolutePath() + "/Teams/" + m_name + ".hwt");
+    QFile f(QString("physfs://config/Teams/%1.hwt").arg(m_name));
     return f.exists();
 }
 
@@ -210,7 +210,7 @@
 {
     if(m_isNetTeam)
         return false;
-    QFile cfgfile(cfgdir->absolutePath() + "/Teams/" + m_name + ".hwt");
+    QFile cfgfile(QString("physfs://config/Teams/%1.hwt").arg(m_name));
     cfgfile.remove();
     return true;
 }
@@ -219,11 +219,11 @@
 {
     if (OldTeamName != m_name)
     {
-        QFile cfgfile(cfgdir->absolutePath() + "/Teams/" + OldTeamName + ".hwt");
+        QFile cfgfile(QString("physfs://config/Teams/%1.hwt").arg(OldTeamName));
         cfgfile.remove();
         OldTeamName = m_name;
     }
-    QSettings teamfile(cfgdir->absolutePath() + "/Teams/" + m_name + ".hwt", QSettings::IniFormat, 0);
+    QSettings teamfile(QString("physfs://config/Teams/%1.hwt").arg(m_name), QSettings::IniFormat, 0);
     teamfile.setIniCodec("UTF-8");
     teamfile.setValue("Team/Name", m_name);
     teamfile.setValue("Team/Grave", m_grave);
--- a/QTfrontend/ui/mouseoverfilter.cpp	Sat Nov 17 20:27:49 2012 -0500
+++ b/QTfrontend/ui/mouseoverfilter.cpp	Sat Nov 17 20:30:32 2012 -0500
@@ -41,8 +41,7 @@
         QTabWidget * tab = dynamic_cast<QTabWidget*>(dist);
         if (HWForm::config->isFrontendSoundEnabled() && (button || textfield || checkbox || droplist || slider || tab))
         {
-            DataManager & dataMgr = DataManager::instance();
-            SDLInteraction::instance().playSoundFile(dataMgr.findFileForRead("Sounds/steps.ogg"));
+            SDLInteraction::instance().playSoundFile("/Sounds/steps.ogg");
         }
 
         return true;
--- a/QTfrontend/ui/page/pagedata.cpp	Sat Nov 17 20:27:49 2012 -0500
+++ b/QTfrontend/ui/page/pagedata.cpp	Sat Nov 17 20:30:32 2012 -0500
@@ -31,9 +31,7 @@
 #include "databrowser.h"
 #include "hwconsts.h"
 #include "DataManager.h"
-
-#include "quazip.h"
-#include "quazipfile.h"
+#include "FileEngine.h"
 
 QLayout * PageDataDownload::bodyLayoutDefinition()
 {
@@ -74,7 +72,7 @@
     else
         finalUrl = url;
 
-    if(url.path().endsWith(".zip"))
+    if(url.path().endsWith(".hwp"))
     {
         qWarning() << "Download Request" << url.toString();
         QString fileName = QFileInfo(url.toString()).fileName();
@@ -128,7 +126,6 @@
 
     if(reply)
     {
-        QByteArray fileContents = reply->readAll();
         QProgressBar *progressBar = progressBars.value(reply, 0);
 
         if(progressBar)
@@ -137,7 +134,24 @@
             progressBar->deleteLater();
         }
 
-        extractDataPack(&fileContents);
+        QDir extractDir(*cfgdir);
+        extractDir.cd("Data");
+
+        QString fileName = extractDir.filePath(QFileInfo(reply->url().path()).fileName());
+
+        QFile out(fileName);
+        if(!out.open(QFile::WriteOnly))
+        {
+            qWarning() << "out.open():" << out.errorString();
+            return ;
+        }
+
+        out.write(reply->readAll());
+
+        out.close();
+
+        // now mount it
+        FileEngineHandler::mount(fileName);
     }
 }
 
@@ -162,83 +176,6 @@
     request(QUrl("http://hedgewars.org/content.html"));
 }
 
-bool PageDataDownload::extractDataPack(QByteArray * buf)
-{
-    QBuffer buffer;
-    buffer.setBuffer(buf);
-
-    QuaZip zip;
-    zip.setIoDevice(&buffer);
-    if(!zip.open(QuaZip::mdUnzip))
-    {
-        qWarning("testRead(): zip.open(): %d", zip.getZipError());
-        return false;
-    }
-
-    QuaZipFile file(&zip);
-
-    QDir extractDir(*cfgdir);
-    extractDir.cd("Data");
-
-    for(bool more = zip.goToFirstFile(); more; more = zip.goToNextFile())
-    {
-        if(!file.open(QIODevice::ReadOnly))
-        {
-            qWarning("file.open(): %d", file.getZipError());
-            return false;
-        }
-
-
-        QString fileName = file.getActualFileName();
-        QString filePath = extractDir.filePath(fileName);
-        if (fileName.endsWith("/"))
-        {
-            QFileInfo fi(filePath);
-            QDir().mkpath(fi.filePath());
-        }
-        else
-        {
-            qDebug() << "Extracting" << filePath;
-            QFile out(filePath);
-            if(!out.open(QFile::WriteOnly))
-            {
-                qWarning() << "out.open():" << out.errorString();
-                return false;
-            }
-
-            out.write(file.readAll());
-
-            out.close();
-
-            if(file.getZipError() != UNZ_OK)
-            {
-                qWarning("file.getFileName(): %d", file.getZipError());
-                return false;
-            }
-
-            if(!file.atEnd())
-            {
-                qWarning("read all but not EOF");
-                return false;
-            }
-
-            m_contentDownloaded = true;
-        }
-
-        file.close();
-
-        if(file.getZipError()!=UNZ_OK)
-        {
-            qWarning("file.close(): %d", file.getZipError());
-            return false;
-        }
-    }
-
-    zip.close();
-
-    return true;
-}
-
 
 void PageDataDownload::onPageLeave()
 {
--- a/QTfrontend/ui/page/pagedata.h	Sat Nov 17 20:27:49 2012 -0500
+++ b/QTfrontend/ui/page/pagedata.h	Sat Nov 17 20:30:32 2012 -0500
@@ -48,8 +48,6 @@
 
         bool m_contentDownloaded; ///< true if something was downloaded since last page leave
 
-        bool extractDataPack(QByteArray * buf);
-
     private slots:
         void request(const QUrl &url);
 
--- a/QTfrontend/ui/page/pageeditteam.cpp	Sat Nov 17 20:27:49 2012 -0500
+++ b/QTfrontend/ui/page/pageeditteam.cpp	Sat Nov 17 20:30:32 2012 -0500
@@ -270,7 +270,7 @@
 
     foreach (QString file, list)
     {
-        QPixmap pix(dataMgr.findFileForRead("Graphics/Graves/" + file));
+        QPixmap pix("physfs://Graphics/Graves/" + file);
         if ((pix.height() > 32) || pix.width() > 32)
             pix = pix.copy(0, 0, 32, 32);
         QIcon icon(pix);
@@ -297,7 +297,7 @@
         list.removeAt(idx);
 
     // add the default flag
-    QPixmap hwFlag(dataMgr.findFileForRead("Graphics/Flags/hedgewars.png"));
+    QPixmap hwFlag("physfs://Graphics/Flags/hedgewars.png");
     CBFlag->addItem(QIcon(hwFlag.copy(0, 0, 22, 15)), "Hedgewars", "hedgewars");
 
     // add seperator after
@@ -308,7 +308,7 @@
     // add all country flags
     foreach (const QString & file, list)
     {
-        QIcon icon(QPixmap(dataMgr.findFileForRead("Graphics/Flags/" + file)));
+        QIcon icon(QPixmap("physfs://Graphics/Flags/" + file));
 
         QString flag = QString(file).remove(pngSuffix);
 
@@ -337,8 +337,7 @@
 
 void PageEditTeam::CBFort_activated(const QString & fortname)
 {
-    DataManager & dataMgr = DataManager::instance();
-    QPixmap pix(dataMgr.findFileForRead("Forts/" + fortname + "L.png"));
+    QPixmap pix("physfs://Forts/" + fortname + "L.png");
     FortPreview->setPixmap(pix);
 }
 
@@ -360,10 +359,8 @@
                        );
 
     if (!list.isEmpty())
-        SDLInteraction::instance().playSoundFile(
-            dataMgr.findFileForRead(voiceDir + "/" +
-                                    list[rand() % list.size()])
-        );
+        SDLInteraction::instance().playSoundFile("physfs://" + voiceDir + "/" +
+                                    list[rand() % list.size()]);
 }
 
 void PageEditTeam::createTeam(const QString & name, const QString & playerHash)
--- a/QTfrontend/ui/page/pagetraining.cpp	Sat Nov 17 20:27:49 2012 -0500
+++ b/QTfrontend/ui/page/pagetraining.cpp	Sat Nov 17 20:30:32 2012 -0500
@@ -125,17 +125,15 @@
     if (loc.isEmpty())
         loc = QLocale::system().name();
 
-    QString infoFile = dataMgr.findFileForRead(
-                           QString("Locale/missions_" + loc + ".txt"));
+    QString infoFile = QString("physfs://Locale/missions_" + loc + ".txt");
 
     // if file is non-existant try with language only
     if (!QFile::exists(infoFile))
-        infoFile = dataMgr.findFileForRead(QString(
-                                               "Locale/missions_" + loc.remove(QRegExp("_.*$")) + ".txt"));
+        infoFile = QString("physfs://Locale/missions_" + loc.remove(QRegExp("_.*$")) + ".txt");
 
     // fallback if file for current locale is non-existant
     if (!QFile::exists(infoFile))
-        infoFile = dataMgr.findFileForRead(QString("Locale/missions_en.txt"));
+        infoFile = QString("physfs://Locale/missions_en.txt");
 
 
     // preload mission info for current locale
@@ -186,15 +184,12 @@
 
 void PageTraining::updateInfo()
 {
-    DataManager & dataMgr = DataManager::instance();
-
     if (lstMissions->currentItem())
     {
         // TODO also use .pngs in userdata folder
-        QString thumbFile = dataMgr.findFileForRead(
-                                "Graphics/Missions/Training/" +
+        QString thumbFile =     "physfs://Graphics/Missions/Training/" +
                                 lstMissions->currentItem()->data(Qt::UserRole).toString() +
-                                "@2x.png");
+                                "@2x.png";
 
         if (QFile::exists(thumbFile))
             btnPreview->setIcon(QIcon(thumbFile));
--- a/QTfrontend/ui/widget/chatwidget.cpp	Sat Nov 17 20:27:49 2012 -0500
+++ b/QTfrontend/ui/widget/chatwidget.cpp	Sat Nov 17 20:30:32 2012 -0500
@@ -64,7 +64,7 @@
     if (orgStyleSheet.isEmpty())
     {
         // load external stylesheet if there is any
-        QFile extFile(DataManager::instance().findFileForRead("css/chat.css"));
+        QFile extFile("physfs://css/chat.css");
 
         QFile resFile(":/res/css/chat.css");
 
@@ -194,12 +194,10 @@
 
         foreach (QString vp, vpList)
         {
-            m_helloSounds.append(DataManager::instance().findFileForRead(
-                               QString("Sounds/voices/%1/Hello.ogg").arg(vp)));
+            m_helloSounds.append(QString("physfs://Sounds/voices/%1/Hello.ogg").arg(vp));
         }
 
-        m_hilightSound = DataManager::instance().findFileForRead(
-                             "Sounds/beep.ogg");
+        m_hilightSound = "physfs://Sounds/beep.ogg";
 
     }
 
@@ -762,8 +760,7 @@
 
 void HWChatWidget::saveStyleSheet()
 {
-    QString dest =
-        DataManager::instance().findFileForWrite("css/chat.css");
+    QString dest = "physfs://css/chat.css";
 
     QFile file(dest);
     if (file.open(QIODevice::WriteOnly | QIODevice::Text))
--- a/QTfrontend/ui/widget/mapContainer.cpp	Sat Nov 17 20:27:49 2012 -0500
+++ b/QTfrontend/ui/widget/mapContainer.cpp	Sat Nov 17 20:30:32 2012 -0500
@@ -606,10 +606,7 @@
             break;
         default:
             QPixmap mapImage;
-            bool success = mapImage.load(
-                DataManager::instance().findFileForRead(
-                    "Maps/" + m_mapInfo.name + "/preview.png")
-            );
+            bool success = mapImage.load("physfs://Maps/" + m_mapInfo.name + "/preview.png");
 
             if(!success)
             {
--- a/QTfrontend/ui/widget/qpushbuttonwithsound.cpp	Sat Nov 17 20:27:49 2012 -0500
+++ b/QTfrontend/ui/widget/qpushbuttonwithsound.cpp	Sat Nov 17 20:30:32 2012 -0500
@@ -36,8 +36,6 @@
     if ( !isSoundEnabled || !HWForm::config->isFrontendSoundEnabled())
         return;
 
-    DataManager & dataMgr = DataManager::instance();
-
     if (this->isEnabled())
-        SDLInteraction::instance().playSoundFile(dataMgr.findFileForRead("Sounds/roperelease.ogg"));
+        SDLInteraction::instance().playSoundFile("/Sounds/roperelease.ogg");
 }
--- a/QTfrontend/util/DataManager.cpp	Sat Nov 17 20:27:49 2012 -0500
+++ b/QTfrontend/util/DataManager.cpp	Sat Nov 17 20:30:32 2012 -0500
@@ -39,12 +39,6 @@
 
 DataManager::DataManager()
 {
-    m_userData = new QDir(cfgdir->absolutePath());
-    if (!m_userData->cd("Data"))
-        m_userData = NULL;
-
-    m_defaultData = new QDir(datadir->absolutePath());
-
     m_hatModel = NULL;
     m_mapModel = NULL;
     m_themeModel = NULL;
@@ -66,20 +60,8 @@
     const QStringList & nameFilters
 ) const
 {
-    QStringList result;
-
-    if (m_userData != NULL)
-    {
-        QDir tmpDir(*m_userData);
-        if (tmpDir.cd(subDirectory))
-            result.append(tmpDir.entryList(nameFilters, filters));
-    }
-
-    QDir tmpDir(*m_defaultData);
-    if (tmpDir.cd(subDirectory))
-        result.append(tmpDir.entryList(nameFilters, filters));
-
-    result.removeDuplicates();
+    QDir tmpDir(QString("physfs://%1").arg(subDirectory));
+    QStringList result = tmpDir.entryList(nameFilters, filters);
 
     // sort case-insensitive
     QMap<QString, QString> sortedFileNames;
@@ -92,40 +74,6 @@
     return result;
 }
 
-
-QString DataManager::findFileForRead(
-    const QString & relativeDataFilePath) const
-{
-    QString path;
-
-    if (m_userData != NULL)
-        path = m_userData->absolutePath()+"/"+relativeDataFilePath;
-
-    if ((!path.isEmpty()) && (!QFile::exists(path)))
-        path = m_defaultData->absolutePath()+"/"+relativeDataFilePath;
-
-    return path;
-}
-
-
-QString DataManager::findFileForWrite(
-    const QString & relativeDataFilePath) const
-{
-    if (m_userData != NULL)
-    {
-        QString path = m_userData->absolutePath()+"/"+relativeDataFilePath;
-
-        // create folders if needed
-        QDir tmp;
-        tmp.mkpath(QFileInfo(path).absolutePath());
-
-        return path;
-    }
-
-
-    return "";
-}
-
 GameStyleModel * DataManager::gameStyleModel()
 {
     if (m_gameStyleModel == NULL) {
--- a/QTfrontend/util/DataManager.h	Sat Nov 17 20:27:49 2012 -0500
+++ b/QTfrontend/util/DataManager.h	Sat Nov 17 20:30:32 2012 -0500
@@ -70,28 +70,6 @@
                              ) const;
 
         /**
-         * @brief Returns the path for the desires data file.
-         *
-         * Use this method if you want to read an existing data file.
-         *
-         * @param relativeDataFilePath relative path of the data file.
-         * @return real path to the file.
-         */
-        QString findFileForRead(const QString & relativeDataFilePath) const;
-
-
-        /**
-         * @brief Returns the path for the data file that is to be written.
-         *
-         * Use this method if you want to create or write into a data file.
-         *
-         * @param relativeDataFilePath relative path of data file write path.
-         * @return destination of path data file.
-         */
-        QString findFileForWrite(const QString & relativeDataFilePath) const;
-
-
-        /**
          * @brief Returns pointer to a model of available game styles.
          *
          * The model is updated automatically on data reload.
@@ -152,9 +130,6 @@
          */
         DataManager();
 
-        QDir * m_defaultData; ///< directory of the installed data
-        QDir * m_userData;    ///< directory of custom data in the user's directory
-
         GameStyleModel * m_gameStyleModel; ///< game style model instance
         HatModel * m_hatModel; ///< hat model instance
         MapModel * m_mapModel; ///< map model instance
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/QTfrontend/util/FileEngine.cpp	Sat Nov 17 20:30:32 2012 -0500
@@ -0,0 +1,306 @@
+/* borrowed from https://github.com/skhaz/qt-physfs-wrapper
+ * TODO: add copyright header, determine license
+ */
+
+
+#include "hwpacksmounter.h"
+#include "FileEngine.h"
+
+
+const QString FileEngineHandler::scheme = "physfs:/";
+
+FileEngine::FileEngine(const QString& filename)
+: _handler(NULL)
+, _flags(0)
+{
+    setFileName(filename);
+}
+
+FileEngine::~FileEngine()
+{
+    close();
+}
+
+bool FileEngine::open(QIODevice::OpenMode openMode)
+{
+    close();
+
+    if (openMode & QIODevice::WriteOnly) {
+        _handler = PHYSFS_openWrite(_filename.toUtf8().constData());
+        _flags = QAbstractFileEngine::WriteOwnerPerm | QAbstractFileEngine::WriteUserPerm | QAbstractFileEngine::FileType;
+    }
+
+    else if (openMode & QIODevice::ReadOnly) {
+        _handler = PHYSFS_openRead(_filename.toUtf8().constData());
+    }
+
+    else if (openMode & QIODevice::Append) {
+        _handler = PHYSFS_openAppend(_filename.toUtf8().constData());
+    }
+
+    else {
+        qWarning("Bad file open mode: %d", (int)openMode);
+    }
+
+    if (!_handler) {
+        qWarning("Failed to open %s, reason: %s", _filename.toUtf8().constData(), PHYSFS_getLastError());
+        return false;
+    }
+
+    return true;
+}
+
+bool FileEngine::close()
+{
+    if (isOpened()) {
+        int result = PHYSFS_close(_handler);
+        _handler = NULL;
+        return result != 0;
+    }
+
+    return true;
+}
+
+bool FileEngine::flush()
+{
+    return PHYSFS_flush(_handler) != 0;
+}
+
+qint64 FileEngine::size() const
+{
+    return _size;
+}
+
+qint64 FileEngine::pos() const
+{
+    return PHYSFS_tell(_handler);
+}
+
+bool FileEngine::seek(qint64 pos)
+{
+    return PHYSFS_seek(_handler, pos) != 0;
+}
+
+bool FileEngine::isSequential() const
+{
+    return false;
+}
+
+bool FileEngine::remove()
+{
+    return PHYSFS_delete(_filename.toUtf8().constData()) != 0;
+}
+
+bool FileEngine::mkdir(const QString &dirName, bool createParentDirectories) const
+{
+    Q_UNUSED(createParentDirectories);
+    return PHYSFS_mkdir(dirName.toUtf8().constData()) != 0;
+}
+
+bool FileEngine::rmdir(const QString &dirName, bool recurseParentDirectories) const
+{
+    Q_UNUSED(recurseParentDirectories);
+    return PHYSFS_delete(dirName.toUtf8().constData()) != 0;
+}
+
+bool FileEngine::caseSensitive() const
+{
+    return true;
+}
+
+bool FileEngine::isRelativePath() const
+{
+    return true;
+}
+
+QAbstractFileEngineIterator * FileEngine::beginEntryList(QDir::Filters filters, const QStringList &filterNames)
+{
+    return new FileEngineIterator(filters, filterNames, entryList(filters, filterNames));
+}
+
+QStringList FileEngine::entryList(QDir::Filters filters, const QStringList &filterNames) const
+{
+    Q_UNUSED(filters);
+
+    QString file;
+    QStringList result;
+    char **files = PHYSFS_enumerateFiles(_filename.toUtf8().constData());
+
+    for (char **i = files; *i != NULL; i++) {
+        file = QString::fromUtf8(*i);
+
+        if (filterNames.isEmpty() || QDir::match(filterNames, file)) {
+            result << file;
+        }
+    }
+
+    PHYSFS_freeList(files);
+
+    return result;
+}
+
+QAbstractFileEngine::FileFlags FileEngine::fileFlags(FileFlags type) const
+{
+    return type & _flags;
+}
+
+QString FileEngine::fileName(FileName file) const
+{
+    if (file == QAbstractFileEngine::AbsolutePathName)
+        return PHYSFS_getWriteDir();
+
+    return QString("physfs://%1").arg(_filename);
+}
+
+QDateTime FileEngine::fileTime(FileTime time) const
+{
+
+    switch (time)
+    {
+        case QAbstractFileEngine::ModificationTime:
+        default:
+            return _datetime;
+            break;
+    };
+}
+
+void FileEngine::setFileName(const QString &file)
+{
+    if(file.startsWith(FileEngineHandler::scheme))
+        _filename = file.mid(FileEngineHandler::scheme.size());
+    else
+        _filename = file;
+
+    PHYSFS_Stat stat;
+    if (PHYSFS_stat(_filename.toUtf8().constData(), &stat) != 0) {
+        _size = stat.filesize;
+        _datetime = QDateTime::fromTime_t(stat.modtime);
+//        _flags |= QAbstractFileEngine::WriteUserPerm;
+        _flags |= QAbstractFileEngine::ReadUserPerm;
+        _flags |= QAbstractFileEngine::ExistsFlag;
+
+        switch (stat.filetype)
+        {
+            case PHYSFS_FILETYPE_REGULAR:
+                _flags |= QAbstractFileEngine::FileType;
+                break;
+
+            case PHYSFS_FILETYPE_DIRECTORY:
+                _flags |= QAbstractFileEngine::DirectoryType;
+                break;
+            case PHYSFS_FILETYPE_SYMLINK:
+                _flags |= QAbstractFileEngine::LinkType;
+                break;
+            default: ;
+        }
+    }
+}
+
+bool FileEngine::atEnd() const
+{
+    return PHYSFS_eof(_handler) != 0;
+}
+
+qint64 FileEngine::read(char *data, qint64 maxlen)
+{
+    return PHYSFS_readBytes(_handler, data, maxlen);
+}
+
+qint64 FileEngine::write(const char *data, qint64 len)
+{
+    return PHYSFS_writeBytes(_handler, data, len);
+}
+
+bool FileEngine::isOpened() const
+{
+    return _handler != NULL;
+}
+
+QFile::FileError FileEngine::error() const
+{
+    return QFile::UnspecifiedError;
+}
+
+QString FileEngine::errorString() const
+{
+    return PHYSFS_getLastError();
+}
+
+bool FileEngine::supportsExtension(Extension extension) const
+{
+    return extension == QAbstractFileEngine::AtEndExtension;
+}
+
+
+
+FileEngineHandler::FileEngineHandler(char *argv0)
+{
+    PHYSFS_init(argv0);
+}
+
+FileEngineHandler::~FileEngineHandler()
+{
+    PHYSFS_deinit();
+}
+
+QAbstractFileEngine* FileEngineHandler::create(const QString &filename) const
+{
+    if (filename.startsWith(scheme))
+        return new FileEngine(filename.mid(scheme.size()));
+    else
+        return NULL;
+}
+
+void FileEngineHandler::mount(const QString &path)
+{
+    PHYSFS_mount(path.toUtf8().constData(), NULL, 1);
+}
+
+void FileEngineHandler::mount(const QString & path, const QString & mountPoint)
+{
+    PHYSFS_mount(path.toUtf8().constData(), mountPoint.toUtf8().constData(), 1);
+}
+
+void FileEngineHandler::setWriteDir(const QString &path)
+{
+    PHYSFS_setWriteDir(path.toUtf8().constData());
+}
+
+void FileEngineHandler::mountPacks()
+{
+    hedgewarsMountPackages();
+}
+
+
+FileEngineIterator::FileEngineIterator(QDir::Filters filters, const QStringList &nameFilters, const QStringList &entries)
+    : QAbstractFileEngineIterator(filters, nameFilters)
+{
+    m_entries = entries;
+
+    /* heck.. docs are unclear on this
+     * QDirIterator puts iterator before first entry
+     * but QAbstractFileEngineIterator example puts iterator on first entry
+     * though QDirIterator approach seems to be the right one
+     */
+
+    m_index = -1;
+}
+
+bool FileEngineIterator::hasNext() const
+{
+    return m_index < m_entries.size() - 1;
+}
+
+QString FileEngineIterator::next()
+{
+   if (!hasNext())
+       return QString();
+
+   ++m_index;
+   return currentFilePath();
+}
+
+QString FileEngineIterator::currentFileName() const
+{
+    return m_entries.at(m_index);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/QTfrontend/util/FileEngine.h	Sat Nov 17 20:30:32 2012 -0500
@@ -0,0 +1,88 @@
+#ifndef _FileEngine_h
+#define _FileEngine_h
+
+#include <QAbstractFileEngine>
+#include <QAbstractFileEngineHandler>
+#include <QAbstractFileEngineIterator>
+#include <QDateTime>
+
+#include "physfs.h"
+
+
+
+class FileEngine : public QAbstractFileEngine
+{
+    public:
+        FileEngine(const QString& filename);
+
+        virtual ~FileEngine();
+
+        virtual bool open(QIODevice::OpenMode openMode);
+        virtual bool close();
+        virtual bool flush();
+        virtual qint64 size() const;
+        virtual qint64 pos() const;
+        virtual bool seek(qint64 pos);
+        virtual bool isSequential() const;
+        virtual bool remove();
+        virtual bool mkdir(const QString &dirName, bool createParentDirectories) const;
+        virtual bool rmdir(const QString &dirName, bool recurseParentDirectories) const;
+        virtual bool caseSensitive() const;
+        virtual bool isRelativePath() const;
+        QAbstractFileEngineIterator *beginEntryList(QDir::Filters filters, const QStringList & filterNames);
+        virtual QStringList entryList(QDir::Filters filters, const QStringList &filterNames) const;
+        virtual FileFlags fileFlags(FileFlags type=FileInfoAll) const;
+        virtual QString fileName(FileName file=DefaultName) const;
+        virtual QDateTime fileTime(FileTime time) const;
+        virtual void setFileName(const QString &file);
+        bool atEnd() const;
+
+        virtual qint64 read(char *data, qint64 maxlen);
+        virtual qint64 write(const char *data, qint64 len);
+
+        bool isOpened() const;
+
+        QFile::FileError error() const;
+        QString errorString() const;
+
+        virtual bool supportsExtension(Extension extension) const;
+
+    private:
+        PHYSFS_file *_handler;
+        qint64 _size;
+        FileFlags _flags;
+        QString _filename;
+        QDateTime _datetime;
+};
+
+class FileEngineHandler : public QAbstractFileEngineHandler
+{
+    public:
+        FileEngineHandler(char * argv0);
+        ~FileEngineHandler();
+
+        QAbstractFileEngine *create(const QString &filename) const;
+
+        static void mount(const QString & path);
+        static void mount(const QString & path, const QString & mountPoint);
+        static void setWriteDir(const QString & path);
+        static void mountPacks();
+
+//    private:
+        static const QString scheme;
+};
+
+class FileEngineIterator : public QAbstractFileEngineIterator
+{
+public:
+        FileEngineIterator(QDir::Filters filters, const QStringList & nameFilters, const QStringList & entries);
+
+        bool hasNext() const;
+        QString next();
+        QString currentFileName() const;
+private:
+        QStringList m_entries;
+        int m_index;
+};
+
+#endif
--- a/QTfrontend/util/namegen.cpp	Sat Nov 17 20:27:49 2012 -0500
+++ b/QTfrontend/util/namegen.cpp	Sat Nov 17 20:30:32 2012 -0500
@@ -125,8 +125,7 @@
     QStringList list;
 
     // find .txt to load the names from
-    QFile * file = new QFile(DataManager::instance().findFileForRead(QString(
-                                 "Names/%1.txt").arg(filename)));
+    QFile * file = new QFile(QString("physfs://Names/%1.txt").arg(filename));
 
     if (file->exists() && file->open(QIODevice::ReadOnly | QIODevice::Text))
     {
@@ -154,8 +153,7 @@
     QStringList list;
 
     // find .cfg to load the dicts from
-    QFile * file = new QFile(DataManager::instance().findFileForRead(QString(
-                                 "Names/%1.cfg").arg(hatname)));
+    QFile * file = new QFile(QString("physfs://Names/%1.cfg").arg(hatname));
 
     if (file->exists() && file->open(QIODevice::ReadOnly | QIODevice::Text))
     {
@@ -183,8 +181,7 @@
     typesAvailable = false;
 
     // find .ini to load the names from
-    QFile * file = new QFile(
-        DataManager::instance().findFileForRead(QString("Names/types.ini")));
+    QFile * file = new QFile(QString("physfs://Names/types.ini"));
 
 
     if (file->exists() && file->open(QIODevice::ReadOnly | QIODevice::Text))
--- a/hedgewars/CMakeLists.txt	Sat Nov 17 20:27:49 2012 -0500
+++ b/hedgewars/CMakeLists.txt	Sat Nov 17 20:30:32 2012 -0500
@@ -54,6 +54,7 @@
     uLocale.pas
     uMisc.pas
     uMobile.pas
+    uPhysFSLayer.pas
     uRandom.pas
     uRender.pas
     uRenderUtils.pas
@@ -99,6 +100,9 @@
     endif (APPLE)
 endif(BUILD_ENGINE_LIBRARY)
 
+# doesn't work for some reason (doesn't find symbols)
+#set(pascal_flags "-k${LIBRARY_OUTPUT_PATH}/libphysfs.a" ${pascal_flags})
+
 IF(FPC)
     set(fpc_executable ${FPC})
 ELSE()
@@ -269,6 +273,10 @@
     add_dependencies(${engine_output_name} lua)
 endif()
 
+# compile physfs before engine
+add_dependencies(${engine_output_name} physfs)
+add_dependencies(${engine_output_name} physfsrwops)
+
 #when ffmpeg/libav is found we need to compile it before engine
 #TODO: convert avwrapper to .pas unit so we can skip this step
 if(${FFMPEG_FOUND})
--- a/hedgewars/SDLh.pas	Sat Nov 17 20:27:49 2012 -0500
+++ b/hedgewars/SDLh.pas	Sat Nov 17 20:30:32 2012 -0500
@@ -1004,7 +1004,7 @@
 function  TTF_RenderUTF8_Blended(font: PTTF_Font; const text: PChar; fg: TSDL_Color): PSDL_Surface; cdecl; external SDL_TTFLibName;
 function  TTF_RenderUTF8_Shaded(font: PTTF_Font; const text: PChar; fg, bg: TSDL_Color): PSDL_Surface; cdecl; external SDL_TTFLibName;
 
-function  TTF_OpenFont(const filename: PChar; size: LongInt): PTTF_Font; cdecl; external SDL_TTFLibName;
+function  TTF_OpenFontRW(src: PSDL_RWops; freesrc: LongBool; size: LongInt): PTTF_Font; cdecl; external SDL_TTFLibName;
 procedure TTF_SetFontStyle(font: PTTF_Font; style: LongInt); cdecl; external SDL_TTFLibName;
 
 (*  SDL_mixer  *)
@@ -1024,7 +1024,7 @@
 procedure Mix_FreeMusic(music: PMixMusic); cdecl; external SDL_MixerLibName;
 
 function  Mix_LoadWAV_RW(src: PSDL_RWops; freesrc: LongInt): PMixChunk; cdecl; external SDL_MixerLibName;
-function  Mix_LoadMUS(const filename: PChar): PMixMusic; cdecl; external SDL_MixerLibName;
+function  Mix_LoadMUS_RW(src: PSDL_RWops): PMixMusic; cdecl; external SDL_MixerLibName;
 
 function  Mix_Playing(channel: LongInt): LongInt; cdecl; external SDL_MixerLibName;
 function  Mix_PlayingMusic: LongInt; cdecl; external SDL_MixerLibName;
@@ -1048,9 +1048,9 @@
 procedure IMG_Quit; {$IFDEF SDL_IMAGE_NEWER}cdecl; external SDL_ImageLibName;{$ENDIF}
 
 function  IMG_Load(const _file: PChar): PSDL_Surface; cdecl; external SDL_ImageLibName;
-function  IMG_Load_RW(rwop: PSDL_RWops; freesrc: LongInt): PSDL_Surface; cdecl; external SDL_ImageLibName;
+function  IMG_Load_RW(rwop: PSDL_RWops; freesrc: LongBool): PSDL_Surface; cdecl; external SDL_ImageLibName;
 function  IMG_LoadPNG_RW(rwop: PSDL_RWops): PSDL_Surface; cdecl; external SDL_ImageLibName;
-function  IMG_LoadTyped_RW(rwop: PSDL_RWops; freesrc: LongInt; type_: PChar): PSDL_Surface; cdecl; external SDL_ImageLibName;
+function  IMG_LoadTyped_RW(rwop: PSDL_RWops; freesrc: LongBool; type_: PChar): PSDL_Surface; cdecl; external SDL_ImageLibName;
 
 (*  SDL_net  *)
 function  SDLNet_Init: LongInt; cdecl; external SDL_NetLibName;
--- a/hedgewars/hwengine.pas	Sat Nov 17 20:27:49 2012 -0500
+++ b/hedgewars/hwengine.pas	Sat Nov 17 20:30:32 2012 -0500
@@ -29,9 +29,10 @@
 program hwengine;
 {$ENDIF}
 
-uses SDLh, uMisc, uConsole, uGame, uConsts, uLand, uAmmos, uVisualGears, uGears, uStore, uWorld, uInputHandler,
-     uSound, uScript, uTeams, uStats, uIO, uLocale, uChat, uAI, uAIMisc, uAILandMarks, uLandTexture, uCollisions,
-     SysUtils, uTypes, uVariables, uCommands, uUtils, uCaptions, uDebug, uCommandHandlers, uLandPainted
+uses SDLh, uMisc, uConsole, uGame, uConsts, uLand, uAmmos, uVisualGears, uGears, uStore, uWorld, uInputHandler
+     , uSound, uScript, uTeams, uStats, uIO, uLocale, uChat, uAI, uAIMisc, uAILandMarks, uLandTexture, uCollisions
+     , SysUtils, uTypes, uVariables, uCommands, uUtils, uCaptions, uDebug, uCommandHandlers, uLandPainted
+     , uPhysFSLayer
      {$IFDEF USE_VIDEO_RECORDING}, uVideoRec {$ENDIF}
      {$IFDEF USE_TOUCH_INTERFACE}, uTouch {$ENDIF}
      {$IFDEF ANDROID}, GLUnit{$ENDIF}
@@ -343,16 +344,6 @@
     for i:= 0 to ParamCount do
         AddFileLog(inttostr(i) + ': ' + ParamStr(i));
 
-    for p:= Succ(Low(TPathType)) to High(TPathType) do
-        if (p <> ptMapCurrent) and (p <> ptData) then
-            UserPathz[p]:= UserPathPrefix + '/Data/' + Pathz[p];
-
-    UserPathz[ptData]:= UserPathPrefix + '/Data';
-
-    for p:= Succ(Low(TPathType)) to High(TPathType) do
-        if p <> ptMapCurrent then
-            Pathz[p]:= PathPrefix + '/' + Pathz[p];
-
     WriteToConsole('Init SDL... ');
     if not cOnlyStats then SDLTry(SDL_Init(SDL_INIT_VIDEO or SDL_INIT_NOPARACHUTE) >= 0, true);
     WriteLnToConsole(msgOK);
@@ -381,18 +372,15 @@
     InitKbdKeyTable();
     AddProgress();
 
-    LoadLocale(UserPathz[ptLocale] + '/en.txt');  // Do an initial load with english
-    LoadLocale(Pathz[ptLocale] + '/en.txt');  // Do an initial load with english
+    LoadLocale(cPathz[ptLocale] + '/en.txt');  // Do an initial load with english
     if cLocaleFName <> 'en.txt' then
         begin
         // Try two letter locale first before trying specific locale overrides
-        if (Length(cLocale) > 3) and (Copy(cLocale,1,2) <> 'en') then
+        if (Length(cLocale) > 3) and (Copy(cLocale, 1, 2) <> 'en') then
             begin
-            LoadLocale(UserPathz[ptLocale] + '/' + Copy(cLocale,1,2)+'.txt');
-            LoadLocale(Pathz[ptLocale] + '/' + Copy(cLocale,1,2)+'.txt')
+            LoadLocale(cPathz[ptLocale] + '/' + Copy(cLocale, 1, 2) + '.txt')
             end;
-        LoadLocale(UserPathz[ptLocale] + '/' + cLocaleFName);
-        LoadLocale(Pathz[ptLocale] + '/' + cLocaleFName)
+        LoadLocale(cPathz[ptLocale] + '/' + cLocaleFName)
         end
     else cLocale := 'en';
 
@@ -459,6 +447,7 @@
 
     if complete then
     begin
+        uPhysFSLayer.initModule;
 {$IFDEF ANDROID}GLUnit.initModule;{$ENDIF}
 {$IFDEF USE_TOUCH_INTERFACE}uTouch.initModule;{$ENDIF}
 {$IFDEF USE_VIDEO_RECORDING}uVideoRec.initModule;{$ENDIF}   //stub
@@ -510,6 +499,7 @@
 {$IFDEF USE_VIDEO_RECORDING}uVideoRec.freeModule;{$ENDIF}
 {$IFDEF USE_TOUCH_INTERFACE}uTouch.freeModule;{$ENDIF}  //stub
 {$IFDEF ANDROID}GLUnit.freeModule;{$ENDIF}
+        uPhysFSLayer.freeModule;
     end;
 
     uIO.freeModule;
--- a/hedgewars/uCommandHandlers.pas	Sat Nov 17 20:27:49 2012 -0500
+++ b/hedgewars/uCommandHandlers.pas	Sat Nov 17 20:30:32 2012 -0500
@@ -548,15 +548,9 @@
 if isDeveloperMode then
     begin
     if s = '' then
-        begin
-        UserPathz[ptMapCurrent]:= s;
-        Pathz[ptMapCurrent]:= s;
-        end
+        cPathz[ptMapCurrent]:= s
     else
-        begin
-        UserPathz[ptMapCurrent]:= UserPathz[ptMaps] + '/' + s;
-        Pathz[ptMapCurrent]:= Pathz[ptMaps] + '/' + s;
-        end;
+        cPathz[ptMapCurrent]:= cPathz[ptMaps] + '/' + s;
     InitStepsFlags:= InitStepsFlags or cifMap
     end;
 cMapName:= s;
@@ -567,8 +561,7 @@
 begin
 if isDeveloperMode then
     begin
-    UserPathz[ptCurrTheme]:= UserPathz[ptThemes] + '/' + s;
-    Pathz[ptCurrTheme]:= Pathz[ptThemes] + '/' + s;
+    cPathz[ptCurrTheme]:= cPathz[ptThemes] + '/' + s;
     Theme:= s;
     InitStepsFlags:= InitStepsFlags or cifTheme
     end
--- a/hedgewars/uLand.pas	Sat Nov 17 20:27:49 2012 -0500
+++ b/hedgewars/uLand.pas	Sat Nov 17 20:30:32 2012 -0500
@@ -426,10 +426,8 @@
 var f: textfile;
     s: shortstring;
 begin
-// unC0Rr - should this be passed from the GUI? I am not sure which layer does what
-s:= UserPathz[ptMapCurrent] + '/map.cfg';
-if not FileExists(s) then
-    s:= Pathz[ptMapCurrent] + '/map.cfg';
+s:= cPathz[ptMapCurrent] + '/map.cfg';
+
 WriteLnToConsole('Fetching map HH limit');
 {$I-}
 Assign(f, s);
@@ -437,7 +435,7 @@
 Reset(f);
 if IOResult <> 0 then
     begin
-    s:= Pathz[ptMissionMaps] + '/' + ExtractFileName(Pathz[ptMapCurrent]) + '/map.cfg';
+    s:= cPathz[ptMissionMaps] + '/' + ExtractFileName(cPathz[ptMapCurrent]) + '/map.cfg';
     Assign(f, s);
     Reset(f);
     end;
@@ -459,7 +457,7 @@
 tmpsurf:= LoadDataImage(ptMapCurrent, 'mask', ifAlpha or ifTransparent or ifIgnoreCaps);
 if tmpsurf = nil then
     begin
-    mapName:= ExtractFileName(Pathz[ptMapCurrent]);
+    mapName:= ExtractFileName(cPathz[ptMapCurrent]);
     tmpsurf:= LoadDataImage(ptMissionMaps, mapName + '/mask', ifAlpha or ifTransparent or ifIgnoreCaps);
     end;
 
@@ -533,7 +531,7 @@
 tmpsurf:= LoadDataImage(ptMapCurrent, 'map', ifAlpha or ifTransparent or ifIgnoreCaps);
 if tmpsurf = nil then
     begin
-    mapName:= ExtractFileName(Pathz[ptMapCurrent]);
+    mapName:= ExtractFileName(cPathz[ptMapCurrent]);
     tmpsurf:= LoadDataImage(ptMissionMaps, mapName + '/map', ifAlpha or ifCritical or ifTransparent or ifIgnoreCaps);
     end;
 // (bare) Sanity check. Considering possible LongInt comparisons as well as just how much system memoery it would take
@@ -581,7 +579,7 @@
 
 procedure GenMap;
 var x, y, w, c: Longword;
-    usermap, usermask, map, mask: shortstring;
+    map, mask: shortstring;
     maskOnly: boolean;
 begin
     hasBorder:= false;
@@ -594,14 +592,11 @@
     //    FillChar(Land,SizeOf(TCollisionArray),0);*)
 
     if (GameFlags and gfForts) = 0 then
-        if Pathz[ptMapCurrent] <> '' then
+        if cPathz[ptMapCurrent] <> '' then
             begin
-            usermap:= UserPathz[ptMapCurrent] + '/map.png';
-            usermask:= UserPathz[ptMapCurrent] + '/mask.png';
-            map:= Pathz[ptMapCurrent] + '/map.png';
-            mask:= Pathz[ptMapCurrent] + '/mask.png';
-            if (not(FileExists(usermap)) and FileExists(usermask)) or
-               (not(FileExists(map)) and FileExists(mask)) then
+            map:= cPathz[ptMapCurrent] + '/map.png';
+            mask:= cPathz[ptMapCurrent] + '/mask.png';
+            if (not(FileExists(map)) and FileExists(mask)) then
                 begin
                 maskOnly:= true;
                 LoadMask;
@@ -696,7 +691,7 @@
 if (GameFlags and gfDisableGirders) <> 0 then
     hasGirders:= false;
 
-if (GameFlags and gfForts = 0) and (maskOnly or (Pathz[ptMapCurrent] = '')) then
+if (GameFlags and gfForts = 0) and (maskOnly or (cPathz[ptMapCurrent] = '')) then
     AddObjects
     
 else
--- a/hedgewars/uLandObjects.pas	Sat Nov 17 20:27:49 2012 -0500
+++ b/hedgewars/uLandObjects.pas	Sat Nov 17 20:30:32 2012 -0500
@@ -30,8 +30,9 @@
 procedure AddOnLandObjects(Surface: PSDL_Surface);
 
 implementation
-uses uStore, uConsts, uConsole, uRandom, uSound, GLunit,
-     uTypes, uVariables, uUtils, uDebug, SysUtils;
+uses uStore, uConsts, uConsole, uRandom, uSound, GLunit
+     , uTypes, uVariables, uUtils, uDebug, SysUtils
+     , uPhysFSLayer;
 
 const MaxRects = 512;
       MAXOBJECTRECTS = 16;
@@ -399,7 +400,7 @@
 
 procedure ReadThemeInfo(var ThemeObjects: TThemeObjects; var SprayObjects: TSprayObjects);
 var s, key: shortstring;
-    f: textfile;
+    f: PFSFile;
     i: LongInt;
     ii, t: Longword;
     c2: TSDL_Color;
@@ -429,21 +430,17 @@
         end
     end;
 
-s:= UserPathz[ptCurrTheme] + '/' + cThemeCFGFilename;
-if not FileExists(s) then
-    s:= Pathz[ptCurrTheme] + '/' + cThemeCFGFilename;
+s:= cPathz[ptCurrTheme] + '/' + cThemeCFGFilename;
 WriteLnToConsole('Reading objects info...');
-Assign(f, s);
-{$I-}
-filemode:= 0; // readonly
-Reset(f);
+f:= pfsOpenRead(s);
+TryDo(f <> nil, 'Bad data or cannot access file ' + cThemeCFGFilename, true);
 
 ThemeObjects.Count:= 0;
 SprayObjects.Count:= 0;
 
-while not eof(f) do
+while not pfsEOF(f) do
     begin
-    Readln(f, s);
+    pfsReadLn(f, s);
     if Length(s) = 0 then
         continue;
     if s[1] = ';' then
@@ -738,9 +735,7 @@
         end
     end;
 
-Close(f);
-{$I+}
-TryDo(IOResult = 0, 'Bad data or cannot access file ' + cThemeCFGFilename, true);
+pfsClose(f);
 AddProgress;
 end;
 
--- a/hedgewars/uLocale.pas	Sat Nov 17 20:27:49 2012 -0500
+++ b/hedgewars/uLocale.pas	Sat Nov 17 20:30:32 2012 -0500
@@ -34,14 +34,14 @@
 {$ENDIF}
 
 implementation
-uses uRandom, uUtils, uVariables, uDebug;
+uses uRandom, uUtils, uVariables, uDebug, uPhysFSLayer;
 
 var trevt: array[TEventId] of array [0..Pred(MAX_EVENT_STRINGS)] of ansistring;
     trevt_n: array[TEventId] of integer;
 
 procedure LoadLocale(FileName: shortstring);
-var s: ansistring;
-    f: textfile;
+var s: shortstring;
+    f: pfsFile;
     a, b, c: LongInt;
     first: array[TEventId] of boolean;
     e: TEventId;
@@ -51,18 +51,14 @@
 for e:= Low(TEventId) to High(TEventId) do
     first[e]:= true;
 
-{$I-} // iochecks off
-Assign(f, FileName);
-filemode:= 0; // readonly
-Reset(f);
-if IOResult = 0 then
-    loaded:= true;
-TryDo(loaded, 'Cannot load locale "' + FileName + '"', false);
-if loaded then
+f:= pfsOpenRead(FileName);
+TryDo(f <> nil, 'Cannot load locale "' + FileName + '"', false);
+
+if f <> nil then
     begin
-    while not eof(f) do
+    while not pfsEof(f) do
         begin
-        readln(f, s);
+        pfsReadLn(f, s);
         if Length(s) = 0 then
             continue;
         if (s[1] < '0') or (s[1] > '9') then
@@ -99,9 +95,8 @@
                 trgoal[TGoalStrId(b)]:= s;
            end;
        end;
-   Close(f);
+   pfsClose(f);
    end;
-{$I+}
 end;
 
 function GetEventString(e: TEventId): ansistring;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hedgewars/uPhysFSLayer.pas	Sat Nov 17 20:30:32 2012 -0500
@@ -0,0 +1,117 @@
+unit uPhysFSLayer;
+
+{$LINKLIB ../bin/libphysfs.a}
+{$LINKLIB ../bin/libphysfsrwops.a}
+
+interface
+uses SDLh;
+
+procedure initModule;
+procedure freeModule;
+
+type PFSFile = pointer;
+
+function rwopsOpenRead(fname: shortstring): PSDL_RWops;
+function rwopsOpenWrite(fname: shortstring): PSDL_RWops;
+
+function pfsOpenRead(fname: shortstring): PFSFile;
+function pfsClose(f: PFSFile): boolean;
+
+procedure pfsReadLn(f: PFSFile; var s: shortstring);
+function pfsBlockRead(f: PFSFile; buf: pointer; size: Int64): Int64;
+function pfsEOF(f: PFSFile): boolean;
+
+function pfsExists(fname: shortstring): boolean;
+
+implementation
+uses uUtils, uVariables;
+
+function PHYSFS_init(argv0: PChar) : LongInt; cdecl; external;
+function PHYSFS_deinit() : LongInt; cdecl; external;
+function PHYSFSRWOPS_openRead(fname: PChar): PSDL_RWops; cdecl; external;
+function PHYSFSRWOPS_openWrite(fname: PChar): PSDL_RWops; cdecl; external;
+
+function PHYSFS_mount(newDir, mountPoint: PChar; appendToPath: LongBool) : LongInt; cdecl; external;
+function PHYSFS_openRead(fname: PChar): PFSFile; cdecl; external;
+function PHYSFS_eof(f: PFSFile): LongBool; cdecl; external;
+function PHYSFS_readBytes(f: PFSFile; buffer: pointer; len: Int64): Int64; cdecl; external;
+function PHYSFS_close(f: PFSFile): LongBool; cdecl; external;
+function PHYSFS_exists(fname: PChar): LongBool; cdecl; external;
+
+procedure hedgewarsMountPackages(); cdecl; external;
+
+function rwopsOpenRead(fname: shortstring): PSDL_RWops;
+begin
+    exit(PHYSFSRWOPS_openRead(Str2PChar(fname)));
+end;
+
+function rwopsOpenWrite(fname: shortstring): PSDL_RWops;
+begin
+    exit(PHYSFSRWOPS_openWrite(Str2PChar(fname)));
+end;
+
+function pfsOpenRead(fname: shortstring): PFSFile;
+begin
+    exit(PHYSFS_openRead(Str2PChar(fname)));
+end;
+
+function pfsEOF(f: PFSFile): boolean;
+begin
+    exit(PHYSFS_eof(f))
+end;
+
+function pfsClose(f: PFSFile): boolean;
+begin
+    exit(PHYSFS_close(f))
+end;
+
+function pfsExists(fname: shortstring): boolean;
+begin
+    exit(PHYSFS_exists(Str2PChar(fname)))
+end;
+
+
+procedure pfsReadLn(f: PFSFile; var s: shortstring);
+var c: char;
+begin
+s[0]:= #0;
+
+while (PHYSFS_readBytes(f, @c, 1) = 1) and (c <> #10) do
+    if (c <> #13) and (s[0] < #255) then
+        begin
+        inc(s[0]);
+        s[byte(s[0])]:= c
+        end
+end;
+
+function pfsBlockRead(f: PFSFile; buf: pointer; size: Int64): Int64;
+var r: Int64;
+begin
+    r:= PHYSFS_readBytes(f, buf, size);
+
+    if r <= 0 then
+        pfsBlockRead:= 0
+    else
+        pfsBlockRead:= r
+end;
+
+procedure initModule;
+var i: LongInt;
+begin
+    i:= PHYSFS_init(Str2PChar(ParamStr(0)));
+    AddFileLog('[PhysFS] init: ' + inttostr(i));
+
+    i:= PHYSFS_mount(Str2PChar(PathPrefix), nil, true);
+    AddFileLog('[PhysFS] mount ' + PathPrefix + ': ' + inttostr(i));
+    i:= PHYSFS_mount(Str2PChar(UserPathPrefix + '/Data'), nil, true);
+    AddFileLog('[PhysFS] mount ' + UserPathPrefix + '/Data: ' + inttostr(i));
+
+    hedgewarsMountPackages;
+end;
+
+procedure freeModule;
+begin
+    PHYSFS_deinit;
+end;
+
+end.
--- a/hedgewars/uScript.pas	Sat Nov 17 20:27:49 2012 -0500
+++ b/hedgewars/uScript.pas	Sat Nov 17 20:30:32 2012 -0500
@@ -81,7 +81,9 @@
     uLandGraphics,
     SDLh,
     SysUtils, 
-    uIO;
+    uIO,
+    uPhysFSLayer
+    ;
 
 var luaState : Plua_State;
     ScriptAmmoLoadout : shortstring;
@@ -1592,7 +1594,7 @@
         lua_pushnil(L);
         end
     else
-        lua_pushstring(L, str2pchar(Pathz[ptData]));
+        lua_pushstring(L, str2pchar(cPathz[ptData]));
     lc_getdatapath:= 1
 end;
 
@@ -1604,7 +1606,7 @@
         lua_pushnil(L);
         end
     else
-        lua_pushstring(L, str2pchar(UserPathz[ptData]));
+        lua_pushstring(L, str2pchar(cPathz[ptData]));
     lc_getuserdatapath:= 1
 end;
 
@@ -1792,6 +1794,18 @@
     lc_setaihintsongear:= 0
 end;
 
+
+function lc_hedgewarsscriptload(L : Plua_State) : LongInt; Cdecl;
+begin
+    if lua_gettop(L) <> 1 then
+        begin
+        LuaError('Lua: Wrong number of parameters passed to HedgewarsScriptLoad!');
+        lua_pushnil(L)
+        end
+    else
+        ScriptLoad(lua_tostring(L, 1));
+    lc_hedgewarsscriptload:= 0;
+end;
 ///////////////////
 
 procedure ScriptPrintStack;
@@ -1964,18 +1978,30 @@
 ScriptCall('onScreenResize');
 end;
 
+// custom script loader via physfs, passed to lua_load
+const BUFSIZE = 1024;
+var physfsReaderBuffer: pointer; external;
+function physfsReader(L: Plua_State; f: PFSFile; sz: Psize_t) : PChar; cdecl; external;
+
 
 procedure ScriptLoad(name : shortstring);
 var ret : LongInt;
       s : shortstring;
+      f : PFSFile;
+    buf : array[0..Pred(BUFSIZE)] of byte;
 begin
-s:= UserPathz[ptData] + '/' + name;
-if not FileExists(s) then
-    s:= Pathz[ptData] + '/' + name;
-if not FileExists(s) then
+s:= cPathz[ptData] + name;
+if not pfsExists(s) then
     exit;
 
-ret:= luaL_loadfile(luaState, Str2PChar(s));
+f:= pfsOpenRead(s);
+if f = nil then 
+    exit;
+
+physfsReaderBuffer:= @buf;
+ret:= lua_load(luaState, @physfsReader, f, Str2PChar(s));
+pfsClose(f);
+
 if ret <> 0 then
     begin
     LuaError('Lua: Failed to load ' + name + '(error ' + IntToStr(ret) + ')');
@@ -2393,6 +2419,7 @@
 lua_register(luaState, _P'TestRectForObstacle', @lc_testrectforobstacle);
 
 lua_register(luaState, _P'SetGearAIHints', @lc_setaihintsongear);
+lua_register(luaState, _P'HedgewarsScriptLoad', @lc_hedgewarsscriptload);
 
 
 ScriptClearStack; // just to be sure stack is empty
--- a/hedgewars/uSound.pas	Sat Nov 17 20:27:49 2012 -0500
+++ b/hedgewars/uSound.pas	Sat Nov 17 20:30:32 2012 -0500
@@ -106,7 +106,7 @@
 
 
 implementation
-uses uVariables, uConsole, uUtils, uCommands, uDebug;
+uses uVariables, uConsole, uUtils, uCommands, uDebug, uPhysFSLayer;
 
 const chanTPU = 32;
 var Volume: LongInt;
@@ -131,29 +131,17 @@
     if cLocale <> 'en' then
         begin
         locName:= name+'_'+cLocale;
-        path:= UserPathz[ptVoices] + '/' + locName;
+        path:= cPathz[ptVoices] + '/' + locName;
         if DirectoryExists(path) then
             name:= locName
         else
-            begin
-            path:= Pathz[ptVoices] + '/' + locName;
-            if DirectoryExists(path) then
-                name:= locName
-            else if Length(cLocale) > 3
-                then
+            if Length(cLocale) > 3 then
                 begin
                 locName:= name+'_'+Copy(cLocale,1,2);
-                path:= UserPathz[ptVoices] + '/' + locName;
+                path:= cPathz[ptVoices] + '/' + locName;
                 if DirectoryExists(path) then
                     name:= locName
-                else
-                    begin
-                    path:= Pathz[ptVoices] + '/' + locName;
-                    if DirectoryExists(path) then
-                        name:= locName
-                    end
                 end
-            end
         end;
 
     // If that fails, use the unmodified one
@@ -267,13 +255,11 @@
         begin
         if (voicepack^.chunks[snd] = nil) and (Soundz[snd].Path = ptVoices) and (Soundz[snd].FileName <> '') then
             begin
-            s:= UserPathz[Soundz[snd].Path] + '/' + voicepack^.name + '/' + Soundz[snd].FileName;
-            if not FileExists(s) then
-                s:= Pathz[Soundz[snd].Path] + '/' + voicepack^.name + '/' + Soundz[snd].FileName;
+            s:= cPathz[Soundz[snd].Path] + '/' + voicepack^.name + '/' + Soundz[snd].FileName;
             if (not FileExists(s)) and (snd in [sndFirePunch2, sndFirePunch3, sndFirePunch4, sndFirePunch5, sndFirePunch6]) then
-                s:= Pathz[Soundz[sndFirePunch1].Path] + '/' + voicepack^.name + '/' + Soundz[snd].FileName;
+                s:= cPathz[Soundz[sndFirePunch1].Path] + '/' + voicepack^.name + '/' + Soundz[snd].FileName;
             WriteToConsole(msgLoading + s + ' ');
-            voicepack^.chunks[snd]:= Mix_LoadWAV_RW(SDL_RWFromFile(Str2PChar(s), _P'rb'), 1);
+            voicepack^.chunks[snd]:= Mix_LoadWAV_RW(rwopsOpenRead(s), 1);
             if voicepack^.chunks[snd] = nil then
                 WriteLnToConsole(msgFailed)
             else
@@ -285,11 +271,9 @@
         begin
         if (defVoicepack^.chunks[snd] = nil) and (Soundz[snd].Path <> ptVoices) and (Soundz[snd].FileName <> '') then
             begin
-            s:= UserPathz[Soundz[snd].Path] + '/' + Soundz[snd].FileName;
-            if not FileExists(s) then
-                s:= Pathz[Soundz[snd].Path] + '/' + Soundz[snd].FileName;
+            s:= cPathz[Soundz[snd].Path] + '/' + Soundz[snd].FileName;
             WriteToConsole(msgLoading + s + ' ');
-            defVoicepack^.chunks[snd]:= Mix_LoadWAV_RW(SDL_RWFromFile(Str2PChar(s), _P'rb'), 1);
+            defVoicepack^.chunks[snd]:= Mix_LoadWAV_RW(rwopsOpenRead(s), 1);
             SDLTry(defVoicepack^.chunks[snd] <> nil, true);
             WriteLnToConsole(msgOK);
             end;
@@ -369,11 +353,9 @@
         begin
         if (voicepack^.chunks[snd] = nil) and (Soundz[snd].Path = ptVoices) and (Soundz[snd].FileName <> '') then
            begin
-            s:= UserPathz[Soundz[snd].Path] + '/' + voicepack^.name + '/' + Soundz[snd].FileName;
-            if not FileExists(s) then
-                s:= Pathz[Soundz[snd].Path] + '/' + voicepack^.name + '/' + Soundz[snd].FileName;
+            s:= cPathz[Soundz[snd].Path] + '/' + voicepack^.name + '/' + Soundz[snd].FileName;
             WriteToConsole(msgLoading + s + ' ');
-            voicepack^.chunks[snd]:= Mix_LoadWAV_RW(SDL_RWFromFile(Str2PChar(s), _P'rb'), 1);
+            voicepack^.chunks[snd]:= Mix_LoadWAV_RW(rwopsOpenRead(s), 1);
             if voicepack^.chunks[snd] = nil then
                 WriteLnToConsole(msgFailed)
             else
@@ -385,11 +367,9 @@
         begin
         if (defVoicepack^.chunks[snd] = nil) and (Soundz[snd].Path <> ptVoices) and (Soundz[snd].FileName <> '') then
             begin
-            s:= UserPathz[Soundz[snd].Path] + '/' + Soundz[snd].FileName;
-            if not FileExists(s) then
-                s:= Pathz[Soundz[snd].Path] + '/' + Soundz[snd].FileName;
+            s:= cPathz[Soundz[snd].Path] + '/' + Soundz[snd].FileName;
             WriteToConsole(msgLoading + s + ' ');
-            defVoicepack^.chunks[snd]:= Mix_LoadWAV_RW(SDL_RWFromFile(Str2PChar(s), _P'rb'), 1);
+            defVoicepack^.chunks[snd]:= Mix_LoadWAV_RW(rwopsOpenRead(s), 1);
             SDLTry(defVoicepack^.chunks[snd] <> nil, true);
             WriteLnToConsole(msgOK);
             end;
@@ -436,12 +416,10 @@
     if (not isSoundEnabled) or (MusicFN = '') or (not isMusicEnabled) then
         exit;
 
-    s:= UserPathPrefix + '/Data/Music/' + MusicFN;
-    if not FileExists(s) then
-        s:= PathPrefix + '/Music/' + MusicFN;
+    s:= '/Music/' + MusicFN;
     WriteToConsole(msgLoading + s + ' ');
 
-    Mus:= Mix_LoadMUS(Str2PChar(s));
+    Mus:= Mix_LoadMUS_RW(rwopsOpenRead(s));
     SDLTry(Mus <> nil, false);
     WriteLnToConsole(msgOK);
 
--- a/hedgewars/uStore.pas	Sat Nov 17 20:27:49 2012 -0500
+++ b/hedgewars/uStore.pas	Sat Nov 17 20:30:32 2012 -0500
@@ -56,9 +56,11 @@
 procedure SwapBuffers; {$IFDEF USE_VIDEO_RECORDING}cdecl{$ELSE}inline{$ENDIF};
 
 implementation
-uses uMisc, uConsole, uMobile, uVariables, uUtils, uTextures, uRender, uRenderUtils, uCommands,
-     uDebug{$IFDEF USE_CONTEXT_RESTORE}, uWorld{$ENDIF}
-     {$IF NOT DEFINED(SDL13) AND DEFINED(USE_VIDEO_RECORDING)}, glut {$ENDIF};
+uses uMisc, uConsole, uMobile, uVariables, uUtils, uTextures, uRender, uRenderUtils, uCommands
+    , uPhysFSLayer
+    , uDebug
+    {$IFDEF USE_CONTEXT_RESTORE}, uWorld{$ENDIF}
+    {$IF NOT DEFINED(SDL13) AND DEFINED(USE_VIDEO_RECORDING)}, glut {$ENDIF};
 
 //type TGPUVendor = (gvUnknown, gvNVIDIA, gvATI, gvIntel, gvApple);
 
@@ -309,11 +311,9 @@
     for fi:= Low(THWFont) to High(THWFont) do
         with Fontz[fi] do
             begin
-            s:= UserPathz[ptFonts] + '/' + Name;
-            if not FileExists(s) then
-                s:= Pathz[ptFonts] + '/' + Name;
+            s:= cPathz[ptFonts] + '/' + Name;
             WriteToConsole(msgLoading + s + ' (' + inttostr(Height) + 'pt)... ');
-            Handle:= TTF_OpenFont(Str2PChar(s), Height);
+            Handle:= TTF_OpenFontRW(rwopsOpenRead(s), true, Height);
             SDLTry(Handle <> nil, true);
             TTF_SetFontStyle(Handle, style);
             WriteLnToConsole(msgOK)
@@ -565,7 +565,7 @@
     WriteToConsole(msgLoading + filename + '.png [flags: ' + inttostr(imageFlags) + '] ');
 
     s:= filename + '.png';
-    tmpsurf:= IMG_Load(Str2PChar(s));
+    tmpsurf:= IMG_Load_RW(rwopsOpenRead(s), true);
 
     if tmpsurf = nil then
     begin
@@ -597,13 +597,7 @@
 var tmpsurf: PSDL_Surface;
 begin
     // check for file in user dir (never critical)
-    tmpsurf:= LoadImage(UserPathz[path] + '/' + filename, imageFlags and (not ifCritical));
-
-    // if unsuccessful check data dir
-    if (tmpsurf = nil) then
-        tmpsurf:= LoadImage(Pathz[path] + '/' + filename, imageFlags);
-
-    LoadDataImage:= tmpsurf;
+    tmpsurf:= LoadImage(cPathz[path] + '/' + filename, imageFlags);
 end;
 
 
--- a/hedgewars/uVariables.pas	Sat Nov 17 20:27:49 2012 -0500
+++ b/hedgewars/uVariables.pas	Sat Nov 17 20:30:32 2012 -0500
@@ -118,9 +118,6 @@
     SDWaterOpacity: byte;
     GrayScale: Boolean;
 
-    // originally from uConsts
-    Pathz: array[TPathType] of shortstring;
-    UserPathz: array[TPathType] of shortstring;
     CountTexz: array[0..Pred(AMMO_INFINITE)] of PTexture;
     LAND_WIDTH       : LongInt;
     LAND_HEIGHT      : LongInt;
@@ -225,27 +222,27 @@
     // these consts are here because they would cause circular dependencies in uConsts/uTypes
     cPathz: array[TPathType] of shortstring = (
         '',                              // ptNone
-        '',                              // ptData
-        'Graphics',                      // ptGraphics
-        'Themes',                        // ptThemes
-        'Themes/Bamboo',                 // ptCurrTheme
-        'Teams',                         // ptTeams
-        'Maps',                          // ptMaps
+        '/',                             // ptData
+        '/Graphics',                     // ptGraphics
+        '/Themes',                       // ptThemes
+        '/Themes/Bamboo',                // ptCurrTheme
+        '/Teams',                        // ptTeams
+        '/Maps',                         // ptMaps
         '',                              // ptMapCurrent
-        'Demos',                         // ptDemos
-        'Sounds',                        // ptSounds
-        'Graphics/Graves',               // ptGraves
-        'Fonts',                         // ptFonts
-        'Forts',                         // ptForts
-        'Locale',                        // ptLocale
-        'Graphics/AmmoMenu',             // ptAmmoMenu
-        'Graphics/Hedgehog',             // ptHedgehog
-        'Sounds/voices',                 // ptVoices
-        'Graphics/Hats',                 // ptHats
-        'Graphics/Flags',                // ptFlags
-        'Missions/Maps',                 // ptMissionMaps
-        'Graphics/SuddenDeath',           // ptSuddenDeath
-        'Graphics/Buttons'                // ptButton
+        '/Demos',                        // ptDemos
+        '/Sounds',                       // ptSounds
+        '/Graphics/Graves',              // ptGraves
+        '/Fonts',                        // ptFonts
+        '/Forts',                        // ptForts
+        '/Locale',                       // ptLocale
+        '/Graphics/AmmoMenu',            // ptAmmoMenu
+        '/Graphics/Hedgehog',            // ptHedgehog
+        '/Sounds/voices',                // ptVoices
+        '/Graphics/Hats',                // ptHats
+        '/Graphics/Flags',               // ptFlags
+        '/Missions/Maps',                // ptMissionMaps
+        '/Graphics/SuddenDeath',         // ptSuddenDeath
+        '/Graphics/Buttons'              // ptButton
     );
 
     Fontz: array[THWFont] of THHFont = (
@@ -2586,7 +2583,6 @@
     lastVisualGearByUID := nil;
     lastGearByUID       := nil;
     cReadyDelay         := 5000;
-    Pathz               := cPathz;
 
         {*  REFERENCE
       4096 -> $FFFFF000
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/misc/physfs/CMakeLists.txt	Sat Nov 17 20:30:32 2012 -0500
@@ -0,0 +1,546 @@
+# PhysicsFS; a portable, flexible file i/o abstraction.
+# Copyright (C) 2007  Ryan C. Gordon.
+#
+# Please see the file LICENSE.txt in the source's root directory.
+
+CMAKE_MINIMUM_REQUIRED(VERSION 2.4)
+
+PROJECT(PhysicsFS)
+SET(PHYSFS_VERSION 2.1.0)
+
+# Increment this if/when we break backwards compatibility.
+SET(PHYSFS_SOVERSION 1)
+
+# I hate that they define "WIN32" ... we're about to move to Win64...I hope!
+IF(WIN32 AND NOT WINDOWS)
+    SET(WINDOWS TRUE)
+ENDIF(WIN32 AND NOT WINDOWS)
+
+# Bleh, let's do it for "APPLE" too.
+IF(APPLE AND NOT MACOSX)
+    SET(MACOSX TRUE)
+ENDIF(APPLE AND NOT MACOSX)
+
+# For now, Haiku and BeOS are the same, as far as the build system cares.
+IF(HAIKU AND NOT BEOS)
+    SET(BEOS TRUE)
+ENDIF(HAIKU AND NOT BEOS)
+
+IF(CMAKE_SYSTEM_NAME STREQUAL "SunOS")
+    SET(SOLARIS TRUE)
+ENDIF(CMAKE_SYSTEM_NAME STREQUAL "SunOS")
+
+INCLUDE(CheckIncludeFile)
+INCLUDE(CheckLibraryExists)
+INCLUDE(CheckCSourceCompiles)
+
+INCLUDE_DIRECTORIES(./src)
+
+IF(MACOSX)
+    # Fallback to older OS X on PowerPC to support wider range of systems...
+    IF(CMAKE_OSX_ARCHITECTURES MATCHES ppc)
+        ADD_DEFINITIONS(-DMAC_OS_X_VERSION_MIN_REQUIRED=1020)
+        SET(OTHER_LDFLAGS ${OTHER_LDFLAGS} " -mmacosx-version-min=10.2")
+    ENDIF(CMAKE_OSX_ARCHITECTURES MATCHES ppc)
+
+    # Need these everywhere...
+    ADD_DEFINITIONS(-fno-common)
+    SET(OTHER_LDFLAGS ${OTHER_LDFLAGS} "-framework Carbon -framework IOKit")
+ENDIF(MACOSX)
+
+# Add some gcc-specific command lines.
+IF(CMAKE_COMPILER_IS_GNUCC)
+    # Always build with debug symbols...you can strip it later.
+    ADD_DEFINITIONS(-g -pipe -Werror -fsigned-char)
+
+    # Stupid BeOS generates warnings in the system headers.
+    IF(NOT BEOS)
+        ADD_DEFINITIONS(-Wall)
+    ENDIF(NOT BEOS)
+
+    CHECK_C_SOURCE_COMPILES("
+        #if ((defined(__GNUC__)) && (__GNUC__ >= 4))
+        int main(int argc, char **argv) { int is_gcc4 = 1; return 0; }
+        #else
+        #error This is not gcc4.
+        #endif
+    " PHYSFS_IS_GCC4)
+
+    IF(PHYSFS_IS_GCC4)
+        # Not supported on several operating systems at this time.
+        IF(NOT SOLARIS AND NOT WINDOWS)
+            ADD_DEFINITIONS(-fvisibility=hidden)
+        ENDIF(NOT SOLARIS AND NOT WINDOWS)
+    ENDIF(PHYSFS_IS_GCC4)
+
+    # Don't use -rpath.
+    SET(CMAKE_SKIP_RPATH ON CACHE BOOL "Skip RPATH" FORCE)
+ENDIF(CMAKE_COMPILER_IS_GNUCC)
+
+IF(CMAKE_C_COMPILER_ID STREQUAL "SunPro")
+    ADD_DEFINITIONS(-erroff=E_EMPTY_TRANSLATION_UNIT)
+    ADD_DEFINITIONS(-xldscope=hidden)
+ENDIF(CMAKE_C_COMPILER_ID STREQUAL "SunPro")
+
+IF(MSVC)
+    # VS.NET 8.0 got really really anal about strcpy, etc, which even if we
+    #  cleaned up our code, zlib, etc still use...so disable the warning.
+    ADD_DEFINITIONS(-D_CRT_SECURE_NO_WARNINGS=1)
+ENDIF(MSVC)
+
+# Basic chunks of source code ...
+
+SET(LZMA_SRCS
+    src/lzma/C/7zCrc.c
+    src/lzma/C/Archive/7z/7zBuffer.c
+    src/lzma/C/Archive/7z/7zDecode.c
+    src/lzma/C/Archive/7z/7zExtract.c
+    src/lzma/C/Archive/7z/7zHeader.c
+    src/lzma/C/Archive/7z/7zIn.c
+    src/lzma/C/Archive/7z/7zItem.c
+    src/lzma/C/Archive/7z/7zMethodID.c
+    src/lzma/C/Compress/Branch/BranchX86.c
+    src/lzma/C/Compress/Branch/BranchX86_2.c
+    src/lzma/C/Compress/Lzma/LzmaDecode.c
+)
+
+IF(BEOS)
+    # We add this explicitly, since we don't want CMake to think this
+    #  is a C++ project unless we're on BeOS.
+    SET(PHYSFS_BEOS_SRCS src/platform_beos.cpp)
+    FIND_LIBRARY(BE_LIBRARY be)
+    FIND_LIBRARY(ROOT_LIBRARY root)
+    SET(OPTIONAL_LIBRARY_LIBS ${OPTIONAL_LIBRARY_LIBS} ${BE_LIBRARY} ${ROOT_LIBRARY})
+ENDIF(BEOS)
+
+# Almost everything is "compiled" here, but things that don't apply to the
+#  build are #ifdef'd out. This is to make it easy to embed PhysicsFS into
+#  another project or bring up a new build system: just compile all the source
+#  code and #define the things you want.
+SET(PHYSFS_SRCS
+    src/physfs.c
+    src/physfs_byteorder.c
+    src/physfs_unicode.c
+    src/platform_posix.c
+    src/platform_unix.c
+    src/platform_macosx.c
+    src/platform_windows.c
+    src/archiver_dir.c
+    src/archiver_unpacked.c
+    src/archiver_grp.c
+    src/archiver_hog.c
+    src/archiver_lzma.c
+    src/archiver_mvl.c
+    src/archiver_qpak.c
+    src/archiver_wad.c
+    src/archiver_zip.c
+    src/archiver_iso9660.c
+    ${PHYSFS_BEOS_SRCS}
+)
+
+
+# platform layers ...
+
+IF(UNIX)
+    IF(BEOS)
+        SET(PHYSFS_HAVE_CDROM_SUPPORT TRUE)
+        SET(PHYSFS_HAVE_THREAD_SUPPORT TRUE)
+        SET(HAVE_PTHREAD_H TRUE)
+    ELSE(BEOS)
+        CHECK_INCLUDE_FILE(sys/ucred.h HAVE_UCRED_H)
+        IF(HAVE_UCRED_H)
+            ADD_DEFINITIONS(-DPHYSFS_HAVE_SYS_UCRED_H=1)
+            SET(PHYSFS_HAVE_CDROM_SUPPORT TRUE)
+        ENDIF(HAVE_UCRED_H)
+
+        CHECK_INCLUDE_FILE(mntent.h HAVE_MNTENT_H)
+        IF(HAVE_MNTENT_H)
+            ADD_DEFINITIONS(-DPHYSFS_HAVE_MNTENT_H=1)
+            SET(PHYSFS_HAVE_CDROM_SUPPORT TRUE)
+        ENDIF(HAVE_MNTENT_H)
+
+        # !!! FIXME: Solaris fails this, because mnttab.h implicitly
+        # !!! FIXME:  depends on other system headers.  :(
+        #CHECK_INCLUDE_FILE(sys/mnttab.h HAVE_SYS_MNTTAB_H)
+        CHECK_C_SOURCE_COMPILES("
+            #include <stdio.h>
+            #include <sys/mnttab.h>
+            int main(int argc, char **argv) { return 0; }
+        " HAVE_SYS_MNTTAB_H)
+
+        IF(HAVE_SYS_MNTTAB_H)
+            ADD_DEFINITIONS(-DPHYSFS_HAVE_SYS_MNTTAB_H=1)
+            SET(PHYSFS_HAVE_CDROM_SUPPORT TRUE)
+        ENDIF(HAVE_SYS_MNTTAB_H)
+
+        CHECK_INCLUDE_FILE(pthread.h HAVE_PTHREAD_H)
+        IF(HAVE_PTHREAD_H)
+            SET(PHYSFS_HAVE_THREAD_SUPPORT TRUE)
+        ENDIF(HAVE_PTHREAD_H)
+    ENDIF(BEOS)
+ENDIF(UNIX)
+
+IF(WINDOWS)
+    SET(PHYSFS_HAVE_CDROM_SUPPORT TRUE)
+    SET(PHYSFS_HAVE_THREAD_SUPPORT TRUE)
+ENDIF(WINDOWS)
+
+IF(NOT PHYSFS_HAVE_CDROM_SUPPORT)
+    ADD_DEFINITIONS(-DPHYSFS_NO_CDROM_SUPPORT=1)
+    MESSAGE(WARNING " ***")
+    MESSAGE(WARNING " *** There is no CD-ROM support in this build!")
+    MESSAGE(WARNING " *** PhysicsFS will just pretend there are no discs.")
+    MESSAGE(WARNING " *** This may be fine, depending on how PhysicsFS is used,")
+    MESSAGE(WARNING " ***   but is this what you REALLY wanted?")
+    MESSAGE(WARNING " *** (Maybe fix CMakeLists.txt, or write a platform driver?)")
+    MESSAGE(WARNING " ***")
+ENDIF(NOT PHYSFS_HAVE_CDROM_SUPPORT)
+
+IF(PHYSFS_HAVE_THREAD_SUPPORT)
+    ADD_DEFINITIONS(-D_REENTRANT -D_THREAD_SAFE)
+ELSE(PHYSFS_HAVE_THREAD_SUPPORT)
+    ADD_DEFINITIONS(-DPHYSFS_NO_THREAD_SUPPORT=1)
+    MESSAGE(WARNING " ***")
+    MESSAGE(WARNING " *** There is no thread support in this build!")
+    MESSAGE(WARNING " *** PhysicsFS will NOT be reentrant!")
+    MESSAGE(WARNING " *** This may be fine, depending on how PhysicsFS is used,")
+    MESSAGE(WARNING " ***   but is this what you REALLY wanted?")
+    MESSAGE(WARNING " *** (Maybe fix CMakeLists.txt, or write a platform driver?)")
+    MESSAGE(WARNING " ***")
+ENDIF(PHYSFS_HAVE_THREAD_SUPPORT)
+
+
+# Archivers ...
+
+OPTION(PHYSFS_ARCHIVE_ZIP "Enable ZIP support" TRUE)
+IF(PHYSFS_ARCHIVE_ZIP)
+    ADD_DEFINITIONS(-DPHYSFS_SUPPORTS_ZIP=1)
+ENDIF(PHYSFS_ARCHIVE_ZIP)
+
+OPTION(PHYSFS_ARCHIVE_7Z "Enable 7zip support" FALSE)
+IF(PHYSFS_ARCHIVE_7Z)
+    ADD_DEFINITIONS(-DPHYSFS_SUPPORTS_7Z=1)
+    # !!! FIXME: rename to 7z.c?
+    SET(PHYSFS_SRCS ${PHYSFS_SRCS} ${LZMA_SRCS})
+ENDIF(PHYSFS_ARCHIVE_7Z)
+
+OPTION(PHYSFS_ARCHIVE_GRP "Enable Build Engine GRP support" TRUE)
+IF(PHYSFS_ARCHIVE_GRP)
+    ADD_DEFINITIONS(-DPHYSFS_SUPPORTS_GRP=1)
+ENDIF(PHYSFS_ARCHIVE_GRP)
+
+OPTION(PHYSFS_ARCHIVE_WAD "Enable Doom WAD support" TRUE)
+IF(PHYSFS_ARCHIVE_WAD)
+    ADD_DEFINITIONS(-DPHYSFS_SUPPORTS_WAD=1)
+ENDIF(PHYSFS_ARCHIVE_WAD)
+
+OPTION(PHYSFS_ARCHIVE_HOG "Enable Descent I/II HOG support" TRUE)
+IF(PHYSFS_ARCHIVE_HOG)
+    ADD_DEFINITIONS(-DPHYSFS_SUPPORTS_HOG=1)
+ENDIF(PHYSFS_ARCHIVE_HOG)
+
+OPTION(PHYSFS_ARCHIVE_MVL "Enable Descent I/II MVL support" TRUE)
+IF(PHYSFS_ARCHIVE_MVL)
+    ADD_DEFINITIONS(-DPHYSFS_SUPPORTS_MVL=1)
+ENDIF(PHYSFS_ARCHIVE_MVL)
+
+OPTION(PHYSFS_ARCHIVE_QPAK "Enable Quake I/II QPAK support" TRUE)
+IF(PHYSFS_ARCHIVE_QPAK)
+    ADD_DEFINITIONS(-DPHYSFS_SUPPORTS_QPAK=1)
+ENDIF(PHYSFS_ARCHIVE_QPAK)
+
+OPTION(PHYSFS_ARCHIVE_ISO9660 "Enable ISO9660 support" TRUE)
+IF(PHYSFS_ARCHIVE_ISO9660)
+    ADD_DEFINITIONS(-DPHYSFS_SUPPORTS_ISO9660=1)
+ENDIF(PHYSFS_ARCHIVE_ISO9660)
+
+
+OPTION(PHYSFS_BUILD_STATIC "Build static library" TRUE)
+IF(PHYSFS_BUILD_STATIC)
+    ADD_LIBRARY(physfs STATIC ${PHYSFS_SRCS})
+    SET_TARGET_PROPERTIES(physfs PROPERTIES OUTPUT_NAME "physfs")
+    SET(PHYSFS_LIB_TARGET physfs)
+    SET(PHYSFS_INSTALL_TARGETS ${PHYSFS_INSTALL_TARGETS} ";physfs")
+ENDIF(PHYSFS_BUILD_STATIC)
+
+#OPTION(PHYSFS_BUILD_SHARED "Build shared library" FALSE)
+#IF(PHYSFS_BUILD_SHARED)
+#    ADD_LIBRARY(physfs SHARED ${PHYSFS_SRCS})
+#    SET_TARGET_PROPERTIES(physfs PROPERTIES VERSION ${PHYSFS_VERSION})
+#    SET_TARGET_PROPERTIES(physfs PROPERTIES SOVERSION ${PHYSFS_SOVERSION})
+#    TARGET_LINK_LIBRARIES(physfs ${OPTIONAL_LIBRARY_LIBS} ${OTHER_LDFLAGS})
+#    SET(PHYSFS_LIB_TARGET physfs)
+#    SET(PHYSFS_INSTALL_TARGETS ${PHYSFS_INSTALL_TARGETS} ";physfs")
+#ENDIF(PHYSFS_BUILD_SHARED)
+
+IF(NOT PHYSFS_BUILD_SHARED AND NOT PHYSFS_BUILD_STATIC)
+    MESSAGE(FATAL "Both shared and static libraries are disabled!")
+ENDIF(NOT PHYSFS_BUILD_SHARED AND NOT PHYSFS_BUILD_STATIC)
+
+# CMake FAQ says I need this...
+IF(PHYSFS_BUILD_SHARED AND PHYSFS_BUILD_STATIC)
+    SET_TARGET_PROPERTIES(physfs PROPERTIES CLEAN_DIRECT_OUTPUT 1)
+    SET_TARGET_PROPERTIES(physfs-static PROPERTIES CLEAN_DIRECT_OUTPUT 1)
+ENDIF(PHYSFS_BUILD_SHARED AND PHYSFS_BUILD_STATIC)
+
+OPTION(PHYSFS_BUILD_TEST "Build stdio test program." FALSE)
+MARK_AS_ADVANCED(PHYSFS_BUILD_TEST)
+IF(PHYSFS_BUILD_TEST)
+    FIND_PATH(READLINE_H readline/readline.h)
+    FIND_PATH(HISTORY_H readline/history.h)
+    IF(READLINE_H AND HISTORY_H)
+        FIND_LIBRARY(CURSES_LIBRARY NAMES curses ncurses)
+        SET(CMAKE_REQUIRED_LIBRARIES ${CURSES_LIBRARY})
+        FIND_LIBRARY(READLINE_LIBRARY readline)
+        IF(READLINE_LIBRARY)
+            SET(HAVE_SYSTEM_READLINE TRUE)
+            SET(TEST_PHYSFS_LIBS ${TEST_PHYSFS_LIBS} ${READLINE_LIBRARY} ${CURSES_LIBRARY})
+            INCLUDE_DIRECTORIES(${READLINE_H} ${HISTORY_H})
+            ADD_DEFINITIONS(-DPHYSFS_HAVE_READLINE=1)
+        ENDIF(READLINE_LIBRARY)
+    ENDIF(READLINE_H AND HISTORY_H)
+    ADD_EXECUTABLE(test_physfs test/test_physfs.c)
+    TARGET_LINK_LIBRARIES(test_physfs ${PHYSFS_LIB_TARGET} ${TEST_PHYSFS_LIBS} ${OTHER_LDFLAGS})
+    SET(PHYSFS_INSTALL_TARGETS ${PHYSFS_INSTALL_TARGETS} ";test_physfs")
+ENDIF(PHYSFS_BUILD_TEST)
+
+
+# Scripting language bindings...
+
+#CMake's SWIG support is basically useless.
+#FIND_PACKAGE(SWIG)
+
+OPTION(PHYSFS_BUILD_SWIG "Build ${_LANG} bindings." FALSE)
+MARK_AS_ADVANCED(PHYSFS_BUILD_SWIG)
+
+FIND_PROGRAM(SWIG swig DOC "Path to swig command line app: http://swig.org/")
+IF(NOT SWIG)
+    MESSAGE(STATUS "SWIG not found. You won't be able to build scripting language bindings.")
+ELSE(NOT SWIG)
+    MARK_AS_ADVANCED(SWIG)
+    IF(DEFINED CMAKE_BUILD_TYPE)
+        IF((NOT CMAKE_BUILD_TYPE STREQUAL "") AND (NOT CMAKE_BUILD_TYPE STREQUAL "Debug"))
+            IF(CMAKE_BUILD_TYPE STREQUAL "MinSizeRel")
+                SET(SWIG_OPT_CFLAGS "-small")
+            ELSE(CMAKE_BUILD_TYPE STREQUAL "MinSizeRel")
+                SET(SWIG_OPT_CFLAGS "-O")
+            ENDIF(CMAKE_BUILD_TYPE STREQUAL "MinSizeRel")
+        ENDIF((NOT CMAKE_BUILD_TYPE STREQUAL "") AND (NOT CMAKE_BUILD_TYPE STREQUAL "Debug"))
+    ENDIF(DEFINED CMAKE_BUILD_TYPE)
+
+    SET(SWIG_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/physfs-swig-bindings")
+
+    MACRO(CONFIGURE_SWIG_BINDING _LANG _INSTALLPATH _EXTRAOUTPUTS _EXTRACFLAGS _EXTRALDFLAGS)
+        STRING(TOUPPER "${_LANG}" _UPPERLANG)
+        STRING(TOLOWER "${_LANG}" _LOWERLANG)
+        SET(_TARGET "physfs-${_LOWERLANG}")
+        SET(_TARGETDIR "${SWIG_OUTPUT_DIR}/${_LOWERLANG}")
+
+        IF(NOT EXISTS "${_TARGETDIR}")
+            FILE(MAKE_DIRECTORY "${_TARGETDIR}")
+        ENDIF(NOT EXISTS "${_TARGETDIR}")
+
+        IF(PHYSFS_BUILD_${_UPPERLANG})
+            ADD_CUSTOM_COMMAND(
+                OUTPUT "${_TARGETDIR}/${_TARGET}.c" ${_EXTRAOUTPUTS}
+                MAIN_DEPENDENCY "${CMAKE_CURRENT_SOURCE_DIR}/extras/physfs-swig.i"
+                COMMAND "${SWIG}"
+                ARGS ${SWIG_OPT_CFLAGS} -${_LOWERLANG} -outdir "${_TARGETDIR}" -o "${_TARGETDIR}/${_TARGET}.c" "${CMAKE_CURRENT_SOURCE_DIR}/extras/physfs-swig.i"
+                COMMENT "Generating ${_LANG} bindings..."
+            )
+
+            ADD_LIBRARY(${_TARGET} SHARED "${_TARGETDIR}/${_TARGET}.c")
+            TARGET_LINK_LIBRARIES(${_TARGET} ${PHYSFS_LIB_TARGET})
+            SET_TARGET_PROPERTIES(${_TARGET} PROPERTIES
+                COMPILE_FLAGS "${_EXTRACFLAGS}"
+                LINK_FLAGS "${_EXTRALDFLAGS}"
+                LIBRARY_OUTPUT_NAME "physfs"
+                LIBRARY_OUTPUT_DIRECTORY "${_TARGETDIR}"
+                CLEAN_DIRECT_OUTPUT 1
+            )
+            INSTALL(TARGETS ${_TARGET} LIBRARY DESTINATION "${_INSTALLPATH}")
+            MESSAGE(STATUS "${_LANG} bindings configured!")
+        ELSE(PHYSFS_BUILD_${_UPPERLANG})
+            MESSAGE(STATUS "Couldn't figure out ${_LANG} configuration. Skipping ${_LANG} bindings.")
+        ENDIF(PHYSFS_BUILD_${_UPPERLANG})
+    ENDMACRO(CONFIGURE_SWIG_BINDING)
+
+    MACRO(ADD_SCRIPT_BINDING_OPTION _VAR _LANG _DEFVAL)
+        SET(BUILDSWIGVAL ${_DEFVAL})
+        IF(NOT PHYSFS_BUILD_SWIG)
+            SET(BUILDSWIGVAL FALSE)
+        ENDIF(NOT PHYSFS_BUILD_SWIG)
+        OPTION(${_VAR} "Build ${_LANG} bindings." ${BUILDSWIGVAL})
+        MARK_AS_ADVANCED(${_VAR})
+    ENDMACRO(ADD_SCRIPT_BINDING_OPTION)
+
+    ADD_SCRIPT_BINDING_OPTION(PHYSFS_BUILD_PERL "Perl" TRUE)
+    ADD_SCRIPT_BINDING_OPTION(PHYSFS_BUILD_RUBY "Ruby" TRUE)
+ENDIF(NOT SWIG)
+
+IF(PHYSFS_BUILD_PERL)
+    MESSAGE(STATUS "Configuring Perl bindings...")
+    FIND_PROGRAM(PERL perl DOC "Path to perl command line app: http://perl.org/")
+    IF(NOT PERL)
+        MESSAGE(STATUS "Perl not found. You won't be able to build perl bindings.")
+        SET(PHYSFS_BUILD_PERL FALSE)
+    ENDIF(NOT PERL)
+    MARK_AS_ADVANCED(PERL)
+
+    MACRO(GET_PERL_CONFIG _KEY _VALUE)
+        IF(PHYSFS_BUILD_PERL)
+            MESSAGE(STATUS "Figuring out perl config value '${_KEY}' ...")
+            EXECUTE_PROCESS(
+                COMMAND ${PERL} -w -e "use Config; print \$Config{${_KEY}};"
+                RESULT_VARIABLE GET_PERL_CONFIG_RC
+                OUTPUT_VARIABLE ${_VALUE}
+            )
+            IF(NOT GET_PERL_CONFIG_RC EQUAL 0)
+                MESSAGE(STATUS "Perl executable ('${PERL}') reported failure: ${GET_PERL_CONFIG_RC}")
+                SET(PHYSFS_BUILD_PERL FALSE)
+            ENDIF(NOT GET_PERL_CONFIG_RC EQUAL 0)
+            IF(NOT ${_VALUE})
+                MESSAGE(STATUS "Perl executable ('${PERL}') didn't have a value for '${_KEY}'")
+                SET(PHYSFS_BUILD_PERL FALSE)
+            ENDIF(NOT ${_VALUE})
+
+            IF(PHYSFS_BUILD_PERL)
+                MESSAGE(STATUS "Perl says: '${${_VALUE}}'.")
+            ENDIF(PHYSFS_BUILD_PERL)
+        ENDIF(PHYSFS_BUILD_PERL)
+    ENDMACRO(GET_PERL_CONFIG)
+
+    # !!! FIXME: installsitearch might be the wrong location.
+    GET_PERL_CONFIG("archlibexp" PERL_INCLUDE_PATH)
+    GET_PERL_CONFIG("ccflags" PERL_CCFLAGS)
+    GET_PERL_CONFIG("ldflags" PERL_LDFLAGS)
+    GET_PERL_CONFIG("installsitearch" PERL_INSTALL_PATH)
+
+    # !!! FIXME: this test for Mac OS X is wrong.
+    IF(MACOSX)
+        GET_PERL_CONFIG("libperl" PERL_LIBPERL)
+        SET(TMPLIBPERL "${PERL_LIBPERL}")
+        STRING(REGEX REPLACE "^lib" "" TMPLIBPERL "${TMPLIBPERL}")
+        STRING(REGEX REPLACE "\\.so$" "" TMPLIBPERL "${TMPLIBPERL}")
+        STRING(REGEX REPLACE "\\.dylib$" "" TMPLIBPERL "${TMPLIBPERL}")
+        STRING(REGEX REPLACE "\\.dll$" "" TMPLIBPERL "${TMPLIBPERL}")
+        IF(NOT "${TMPLIBPERL}" STREQUAL "${PERL_LIBPERL}")
+            MESSAGE(STATUS "Stripped '${PERL_LIBPERL}' down to '${TMPLIBPERL}'.")
+            SET(PERL_LIBPERL "${TMPLIBPERL}")
+        ENDIF(NOT "${TMPLIBPERL}" STREQUAL "${PERL_LIBPERL}")
+        SET(PERL_LIBPERL "-l${PERL_LIBPERL}")
+    ENDIF(MACOSX)
+
+    CONFIGURE_SWIG_BINDING(Perl "${PERL_INSTALL_PATH}" "${SWIG_OUTPUT_DIR}/perl/physfs.pm" "\"-I${PERL_INCLUDE_PATH}/CORE\" ${PERL_CCFLAGS} -w" "\"-L${PERL_INCLUDE_PATH}/CORE\" ${PERL_LIBPERL} ${PERL_LDFLAGS}")
+    INSTALL(FILES "${SWIG_OUTPUT_DIR}/perl/physfs.pm" DESTINATION "${PERL_INSTALL_PATH}")
+    INSTALL(
+        FILES test/test_physfs.pl
+        DESTINATION bin
+        PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE
+                    GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE
+    )
+ENDIF(PHYSFS_BUILD_PERL)
+
+# !!! FIXME: lots of cut-and-paste from perl bindings.
+IF(PHYSFS_BUILD_RUBY)
+    MESSAGE(STATUS "Configuring Ruby bindings...")
+    FIND_PROGRAM(RUBY ruby DOC "Path to ruby command line app: http://ruby-lang.org/")
+    IF(NOT RUBY)
+        MESSAGE(STATUS "Ruby not found. You won't be able to build ruby bindings.")
+        SET(PHYSFS_BUILD_RUBY FALSE)
+    ENDIF(NOT RUBY)
+    MARK_AS_ADVANCED(RUBY)
+
+    MACRO(GET_RUBY_CONFIG _KEY _VALUE)
+        IF(PHYSFS_BUILD_RUBY)
+            MESSAGE(STATUS "Figuring out ruby config value '${_KEY}' ...")
+            EXECUTE_PROCESS(
+                COMMAND ${RUBY} -e "require 'rbconfig'; puts RbConfig::CONFIG['${_KEY}'];"
+                RESULT_VARIABLE GET_RUBY_CONFIG_RC
+                OUTPUT_VARIABLE ${_VALUE}
+                OUTPUT_STRIP_TRAILING_WHITESPACE
+            )
+            IF(NOT GET_RUBY_CONFIG_RC EQUAL 0)
+                MESSAGE(STATUS "Ruby executable ('${RUBY}') reported failure: ${GET_RUBY_CONFIG_RC}")
+                SET(PHYSFS_BUILD_RUBY FALSE)
+            ENDIF(NOT GET_RUBY_CONFIG_RC EQUAL 0)
+            IF(NOT ${_VALUE})
+                MESSAGE(STATUS "Ruby executable ('${RUBY}') didn't have a value for '${_KEY}'")
+                SET(PHYSFS_BUILD_RUBY FALSE)
+            ENDIF(NOT ${_VALUE})
+
+            IF(PHYSFS_BUILD_RUBY)
+                MESSAGE(STATUS "Ruby says: '${${_VALUE}}'.")
+            ENDIF(PHYSFS_BUILD_RUBY)
+        ENDIF(PHYSFS_BUILD_RUBY)
+    ENDMACRO(GET_RUBY_CONFIG)
+
+    GET_RUBY_CONFIG("archdir" RUBY_INCLUDE_PATH)
+    GET_RUBY_CONFIG("CFLAGS" RUBY_CCFLAGS)
+    GET_RUBY_CONFIG("LDFLAGS" RUBY_LDFLAGS)
+    GET_RUBY_CONFIG("sitearchdir" RUBY_INSTALL_PATH)
+    GET_RUBY_CONFIG("LIBRUBYARG_SHARED" RUBY_LIBRUBY)
+    GET_RUBY_CONFIG("libdir" RUBY_LIBDIR)
+
+    CONFIGURE_SWIG_BINDING(Ruby "${RUBY_INSTALL_PATH}" "" "\"-I${RUBY_INCLUDE_PATH}\" ${RUBY_CCFLAGS} -w" "\"-L${RUBY_LIBDIR}\" ${RUBY_LIBRUBY} ${RUBY_LDFLAGS}")
+    SET_TARGET_PROPERTIES(physfs-ruby PROPERTIES PREFIX "")
+    INSTALL(
+        FILES test/test_physfs.rb
+        DESTINATION bin
+        PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE
+                    GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE
+    )
+ENDIF(PHYSFS_BUILD_RUBY)
+
+
+INSTALL(TARGETS ${PHYSFS_INSTALL_TARGETS}
+        RUNTIME DESTINATION bin
+        LIBRARY DESTINATION lib${LIB_SUFFIX}
+        ARCHIVE DESTINATION lib${LIB_SUFFIX})
+INSTALL(FILES src/physfs.h DESTINATION include)
+
+IF(UNIX)
+    SET(PHYSFS_TARBALL "${CMAKE_CURRENT_SOURCE_DIR}/../physfs-${PHYSFS_VERSION}.tar.gz")
+    ADD_CUSTOM_TARGET(
+        dist
+        hg archive -t tgz "${PHYSFS_TARBALL}"
+        WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}"
+        COMMENT "Building source tarball '${PHYSFS_TARBALL}'..."
+    )
+#    ADD_CUSTOM_TARGET(
+#        uninstall
+#        "${CMAKE_CURRENT_SOURCE_DIR}/extras/uninstall.sh"
+#        WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}"
+#        COMMENT "Uninstall the project..."
+#    )
+ENDIF(UNIX)
+
+MACRO(MESSAGE_BOOL_OPTION _NAME _VALUE)
+    IF(${_VALUE})
+        MESSAGE(STATUS "  ${_NAME}: enabled")
+    ELSE(${_VALUE})
+        MESSAGE(STATUS "  ${_NAME}: disabled")
+    ENDIF(${_VALUE})
+ENDMACRO(MESSAGE_BOOL_OPTION)
+
+MESSAGE(STATUS "PhysicsFS will build with the following options:")
+MESSAGE_BOOL_OPTION("ZIP support" PHYSFS_ARCHIVE_ZIP)
+MESSAGE_BOOL_OPTION("7zip support" PHYSFS_ARCHIVE_7Z)
+MESSAGE_BOOL_OPTION("GRP support" PHYSFS_ARCHIVE_GRP)
+MESSAGE_BOOL_OPTION("WAD support" PHYSFS_ARCHIVE_WAD)
+MESSAGE_BOOL_OPTION("HOG support" PHYSFS_ARCHIVE_HOG)
+MESSAGE_BOOL_OPTION("MVL support" PHYSFS_ARCHIVE_MVL)
+MESSAGE_BOOL_OPTION("QPAK support" PHYSFS_ARCHIVE_QPAK)
+MESSAGE_BOOL_OPTION("CD-ROM drive support" PHYSFS_HAVE_CDROM_SUPPORT)
+MESSAGE_BOOL_OPTION("Thread safety" PHYSFS_HAVE_THREAD_SUPPORT)
+MESSAGE_BOOL_OPTION("Build static library" PHYSFS_BUILD_STATIC)
+MESSAGE_BOOL_OPTION("Build shared library" PHYSFS_BUILD_SHARED)
+MESSAGE_BOOL_OPTION("Build Perl bindings" PHYSFS_BUILD_PERL)
+MESSAGE_BOOL_OPTION("Build Ruby bindings" PHYSFS_BUILD_RUBY)
+MESSAGE_BOOL_OPTION("Build stdio test program" PHYSFS_BUILD_TEST)
+IF(PHYSFS_BUILD_TEST)
+    MESSAGE_BOOL_OPTION("  Use readline in test program" HAVE_SYSTEM_READLINE)
+ENDIF(PHYSFS_BUILD_TEST)
+
+# end of CMakeLists.txt ...
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/misc/physfs/extras/CMakeLists.txt	Sat Nov 17 20:30:32 2012 -0500
@@ -0,0 +1,9 @@
+find_package(SDL REQUIRED)
+
+include_directories(${SDL_INCLUDE_DIR})
+include_directories(${CMAKE_SOURCE_DIR}/misc/liblua)
+include_directories(${CMAKE_SOURCE_DIR}/misc/physfs/src)
+
+add_library(physfsrwops STATIC physfsrwops.c physfslualoader.c hwpacksmounter.c)
+
+add_dependencies(physfsrwops lua)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/misc/physfs/extras/hwpacksmounter.c	Sat Nov 17 20:30:32 2012 -0500
@@ -0,0 +1,36 @@
+#include <string.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <physfs.h>
+
+#include "hwpacksmounter.h"
+
+void hedgewarsMountPackages()
+{
+    char ** filesList = PHYSFS_enumerateFiles("/");
+    char **i;
+
+    for (i = filesList; *i != NULL; i++)
+    {
+        char * fileName = *i;
+        int fileNameLength = strlen(fileName);
+        if (fileNameLength > 4)
+            if (strcmp(fileName + fileNameLength - 4, ".hwp") == 0)
+            {
+                const char * dir = PHYSFS_getRealDir(fileName);
+                if(dir)
+                {
+                    char * fullPath = (char *)malloc(strlen(dir) + fileNameLength + 2);
+                    strcpy(fullPath, dir);
+                    strcat(fullPath, "/");
+                    strcat(fullPath, fileName);
+
+                    PHYSFS_mount(fullPath, NULL, 1);
+
+                    free(fullPath);
+                }
+            }
+    }
+
+    PHYSFS_freeList(filesList);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/misc/physfs/extras/hwpacksmounter.h	Sat Nov 17 20:30:32 2012 -0500
@@ -0,0 +1,15 @@
+#ifndef HEDGEWARS_PACKAGES_MOUNTER_H
+#define HEDGEWARS_PACKAGES_MOUNTER_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void hedgewarsMountPackages();
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/misc/physfs/extras/physfslualoader.c	Sat Nov 17 20:30:32 2012 -0500
@@ -0,0 +1,24 @@
+#include <lua.h>
+#include <physfs.h>
+
+#define BUFSIZE 1024
+
+void * physfsReaderBuffer;
+
+const char * physfsReader(lua_State *L, PHYSFS_File *f, size_t *size)
+{
+
+    if(PHYSFS_eof(f))
+    {
+        return NULL;
+    }
+    else
+    {
+        *size = PHYSFS_readBytes(f, physfsReaderBuffer, BUFSIZE);
+
+        if(*size == 0)
+            return NULL;
+        else
+            return physfsReaderBuffer;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/misc/physfs/extras/physfsrwops.c	Sat Nov 17 20:30:32 2012 -0500
@@ -0,0 +1,219 @@
+/*
+ * This code provides a glue layer between PhysicsFS and Simple Directmedia
+ *  Layer's (SDL) RWops i/o abstraction.
+ *
+ * License: this code is public domain. I make no warranty that it is useful,
+ *  correct, harmless, or environmentally safe.
+ *
+ * This particular file may be used however you like, including copying it
+ *  verbatim into a closed-source project, exploiting it commercially, and
+ *  removing any trace of my name from the source (although I hope you won't
+ *  do that). I welcome enhancements and corrections to this file, but I do
+ *  not require you to send me patches if you make changes. This code has
+ *  NO WARRANTY.
+ *
+ * Unless otherwise stated, the rest of PhysicsFS falls under the zlib license.
+ *  Please see LICENSE.txt in the root of the source tree.
+ *
+ * SDL 1.2 falls under the LGPL license. SDL 1.3+ is zlib, like PhysicsFS.
+ *  You can get SDL at http://www.libsdl.org/
+ *
+ *  This file was written by Ryan C. Gordon. (icculus@icculus.org).
+ */
+
+#include <stdio.h>  /* used for SEEK_SET, SEEK_CUR, SEEK_END ... */
+#include "physfsrwops.h"
+
+/* SDL's RWOPS interface changed a little in SDL 1.3... */
+#if defined(SDL_VERSION_ATLEAST)
+#if SDL_VERSION_ATLEAST(1, 3, 0)
+#define TARGET_SDL13 1
+#endif
+#endif
+
+#if TARGET_SDL13
+static long SDLCALL physfsrwops_seek(struct SDL_RWops *rw, long offset, int whence)
+#else
+static int physfsrwops_seek(SDL_RWops *rw, int offset, int whence)
+#endif
+{
+    PHYSFS_File *handle = (PHYSFS_File *) rw->hidden.unknown.data1;
+    PHYSFS_sint64 pos = 0;
+
+    if (whence == SEEK_SET)
+        pos = (PHYSFS_sint64) offset;
+
+    else if (whence == SEEK_CUR)
+    {
+        const PHYSFS_sint64 current = PHYSFS_tell(handle);
+        if (current == -1)
+        {
+            SDL_SetError("Can't find position in file: %s",
+                          PHYSFS_getLastError());
+            return -1;
+        } /* if */
+
+        if (offset == 0)  /* this is a "tell" call. We're done. */
+        {
+            #if TARGET_SDL13
+            return (long) current;
+            #else
+            return (int) current;
+            #endif
+        } /* if */
+
+        pos = current + ((PHYSFS_sint64) offset);
+    } /* else if */
+
+    else if (whence == SEEK_END)
+    {
+        const PHYSFS_sint64 len = PHYSFS_fileLength(handle);
+        if (len == -1)
+        {
+            SDL_SetError("Can't find end of file: %s", PHYSFS_getLastError());
+            return -1;
+        } /* if */
+
+        pos = len + ((PHYSFS_sint64) offset);
+    } /* else if */
+
+    else
+    {
+        SDL_SetError("Invalid 'whence' parameter.");
+        return -1;
+    } /* else */
+
+    if ( pos < 0 )
+    {
+        SDL_SetError("Attempt to seek past start of file.");
+        return -1;
+    } /* if */
+    
+    if (!PHYSFS_seek(handle, (PHYSFS_uint64) pos))
+    {
+        SDL_SetError("PhysicsFS error: %s", PHYSFS_getLastError());
+        return -1;
+    } /* if */
+
+    #if TARGET_SDL13
+    return (long) pos;
+    #else
+    return (int) pos;
+    #endif
+} /* physfsrwops_seek */
+
+
+#if TARGET_SDL13
+static size_t SDLCALL physfsrwops_read(struct SDL_RWops *rw, void *ptr,
+                                       size_t size, size_t maxnum)
+#else
+static int physfsrwops_read(SDL_RWops *rw, void *ptr, int size, int maxnum)
+#endif
+{
+    PHYSFS_File *handle = (PHYSFS_File *) rw->hidden.unknown.data1;
+    const PHYSFS_uint64 readlen = (PHYSFS_uint64) (maxnum * size);
+    const PHYSFS_sint64 rc = PHYSFS_readBytes(handle, ptr, readlen);
+    if (rc != ((PHYSFS_sint64) readlen))
+    {
+        if (!PHYSFS_eof(handle)) /* not EOF? Must be an error. */
+            SDL_SetError("PhysicsFS error: %s", PHYSFS_getLastError());
+    } /* if */
+
+    #if TARGET_SDL13
+    return (size_t) rc;
+    #else
+    return (int) rc;
+    #endif
+} /* physfsrwops_read */
+
+
+#if TARGET_SDL13
+static size_t SDLCALL physfsrwops_write(struct SDL_RWops *rw, const void *ptr,
+                                        size_t size, size_t num)
+#else
+static int physfsrwops_write(SDL_RWops *rw, const void *ptr, int size, int num)
+#endif
+{
+    PHYSFS_File *handle = (PHYSFS_File *) rw->hidden.unknown.data1;
+    const PHYSFS_uint64 writelen = (PHYSFS_uint64) (num * size);
+    const PHYSFS_sint64 rc = PHYSFS_writeBytes(handle, ptr, writelen);
+    if (rc != ((PHYSFS_sint64) writelen))
+        SDL_SetError("PhysicsFS error: %s", PHYSFS_getLastError());
+
+    #if TARGET_SDL13
+    return (size_t) rc;
+    #else
+    return (int) rc;
+    #endif
+} /* physfsrwops_write */
+
+
+static int physfsrwops_close(SDL_RWops *rw)
+{
+    PHYSFS_File *handle = (PHYSFS_File *) rw->hidden.unknown.data1;
+    if (!PHYSFS_close(handle))
+    {
+        SDL_SetError("PhysicsFS error: %s", PHYSFS_getLastError());
+        return -1;
+    } /* if */
+
+    SDL_FreeRW(rw);
+    return 0;
+} /* physfsrwops_close */
+
+
+static SDL_RWops *create_rwops(PHYSFS_File *handle)
+{
+    SDL_RWops *retval = NULL;
+
+    if (handle == NULL)
+        SDL_SetError("PhysicsFS error: %s", PHYSFS_getLastError());
+    else
+    {
+        retval = SDL_AllocRW();
+        if (retval != NULL)
+        {
+            retval->seek  = physfsrwops_seek;
+            retval->read  = physfsrwops_read;
+            retval->write = physfsrwops_write;
+            retval->close = physfsrwops_close;
+            retval->hidden.unknown.data1 = handle;
+        } /* if */
+    } /* else */
+
+    return retval;
+} /* create_rwops */
+
+
+SDL_RWops *PHYSFSRWOPS_makeRWops(PHYSFS_File *handle)
+{
+    SDL_RWops *retval = NULL;
+    if (handle == NULL)
+        SDL_SetError("NULL pointer passed to PHYSFSRWOPS_makeRWops().");
+    else
+        retval = create_rwops(handle);
+
+    return retval;
+} /* PHYSFSRWOPS_makeRWops */
+
+
+SDL_RWops *PHYSFSRWOPS_openRead(const char *fname)
+{
+    return create_rwops(PHYSFS_openRead(fname));
+} /* PHYSFSRWOPS_openRead */
+
+
+SDL_RWops *PHYSFSRWOPS_openWrite(const char *fname)
+{
+    return create_rwops(PHYSFS_openWrite(fname));
+} /* PHYSFSRWOPS_openWrite */
+
+
+SDL_RWops *PHYSFSRWOPS_openAppend(const char *fname)
+{
+    return create_rwops(PHYSFS_openAppend(fname));
+} /* PHYSFSRWOPS_openAppend */
+
+
+/* end of physfsrwops.c ... */
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/misc/physfs/extras/physfsrwops.h	Sat Nov 17 20:30:32 2012 -0500
@@ -0,0 +1,88 @@
+/*
+ * This code provides a glue layer between PhysicsFS and Simple Directmedia
+ *  Layer's (SDL) RWops i/o abstraction.
+ *
+ * License: this code is public domain. I make no warranty that it is useful,
+ *  correct, harmless, or environmentally safe.
+ *
+ * This particular file may be used however you like, including copying it
+ *  verbatim into a closed-source project, exploiting it commercially, and
+ *  removing any trace of my name from the source (although I hope you won't
+ *  do that). I welcome enhancements and corrections to this file, but I do
+ *  not require you to send me patches if you make changes. This code has
+ *  NO WARRANTY.
+ *
+ * Unless otherwise stated, the rest of PhysicsFS falls under the zlib license.
+ *  Please see LICENSE.txt in the root of the source tree.
+ *
+ * SDL falls under the LGPL license. You can get SDL at http://www.libsdl.org/
+ *
+ *  This file was written by Ryan C. Gordon. (icculus@icculus.org).
+ */
+
+#ifndef _INCLUDE_PHYSFSRWOPS_H_
+#define _INCLUDE_PHYSFSRWOPS_H_
+
+#include "physfs.h"
+#include "SDL.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * Open a platform-independent filename for reading, and make it accessible
+ *  via an SDL_RWops structure. The file will be closed in PhysicsFS when the
+ *  RWops is closed. PhysicsFS should be configured to your liking before
+ *  opening files through this method.
+ *
+ *   @param filename File to open in platform-independent notation.
+ *  @return A valid SDL_RWops structure on success, NULL on error. Specifics
+ *           of the error can be gleaned from PHYSFS_getLastError().
+ */
+PHYSFS_DECL SDL_RWops *PHYSFSRWOPS_openRead(const char *fname);
+
+/**
+ * Open a platform-independent filename for writing, and make it accessible
+ *  via an SDL_RWops structure. The file will be closed in PhysicsFS when the
+ *  RWops is closed. PhysicsFS should be configured to your liking before
+ *  opening files through this method.
+ *
+ *   @param filename File to open in platform-independent notation.
+ *  @return A valid SDL_RWops structure on success, NULL on error. Specifics
+ *           of the error can be gleaned from PHYSFS_getLastError().
+ */
+PHYSFS_DECL SDL_RWops *PHYSFSRWOPS_openWrite(const char *fname);
+
+/**
+ * Open a platform-independent filename for appending, and make it accessible
+ *  via an SDL_RWops structure. The file will be closed in PhysicsFS when the
+ *  RWops is closed. PhysicsFS should be configured to your liking before
+ *  opening files through this method.
+ *
+ *   @param filename File to open in platform-independent notation.
+ *  @return A valid SDL_RWops structure on success, NULL on error. Specifics
+ *           of the error can be gleaned from PHYSFS_getLastError().
+ */
+PHYSFS_DECL SDL_RWops *PHYSFSRWOPS_openAppend(const char *fname);
+
+/**
+ * Make a SDL_RWops from an existing PhysicsFS file handle. You should
+ *  dispose of any references to the handle after successful creation of
+ *  the RWops. The actual PhysicsFS handle will be destroyed when the
+ *  RWops is closed.
+ *
+ *   @param handle a valid PhysicsFS file handle.
+ *  @return A valid SDL_RWops structure on success, NULL on error. Specifics
+ *           of the error can be gleaned from PHYSFS_getLastError().
+ */
+PHYSFS_DECL SDL_RWops *PHYSFSRWOPS_makeRWops(PHYSFS_File *handle);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* include-once blocker */
+
+/* end of physfsrwops.h ... */
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/misc/physfs/src/archiver_dir.c	Sat Nov 17 20:30:32 2012 -0500
@@ -0,0 +1,201 @@
+/*
+ * Standard directory I/O support routines for PhysicsFS.
+ *
+ * Please see the file LICENSE.txt in the source's root directory.
+ *
+ *  This file written by Ryan C. Gordon.
+ */
+
+#define __PHYSICSFS_INTERNAL__
+#include "physfs_internal.h"
+
+/* There's no PHYSFS_Io interface here. Use __PHYSFS_createNativeIo(). */
+
+
+
+static char *cvtToDependent(const char *prepend, const char *path, char *buf)
+{
+    BAIL_IF_MACRO(buf == NULL, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
+    sprintf(buf, "%s%s", prepend ? prepend : "", path);
+
+    if (__PHYSFS_platformDirSeparator != '/')
+    {
+        char *p;
+        for (p = strchr(buf, '/'); p != NULL; p = strchr(p + 1, '/'))
+            *p = __PHYSFS_platformDirSeparator;
+    } /* if */
+
+    return buf;
+} /* cvtToDependent */
+
+
+#define CVT_TO_DEPENDENT(buf, pre, dir) { \
+    const size_t len = ((pre) ? strlen((char *) pre) : 0) + strlen(dir) + 1; \
+    buf = cvtToDependent((char*)pre,dir,(char*)__PHYSFS_smallAlloc(len)); \
+}
+
+
+
+static void *DIR_openArchive(PHYSFS_Io *io, const char *name, int forWriting)
+{
+    PHYSFS_Stat st;
+    const char dirsep = __PHYSFS_platformDirSeparator;
+    char *retval = NULL;
+    const size_t namelen = strlen(name);
+    const size_t seplen = 1;
+    int exists = 0;
+
+    assert(io == NULL);  /* shouldn't create an Io for these. */
+    BAIL_IF_MACRO(!__PHYSFS_platformStat(name, &exists, &st), ERRPASS, NULL);
+    if (st.filetype != PHYSFS_FILETYPE_DIRECTORY)
+        BAIL_MACRO(PHYSFS_ERR_UNSUPPORTED, NULL);
+
+    retval = allocator.Malloc(namelen + seplen + 1);
+    BAIL_IF_MACRO(retval == NULL, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
+
+    strcpy(retval, name);
+
+    /* make sure there's a dir separator at the end of the string */
+    if (retval[namelen - 1] != dirsep)
+    {
+        retval[namelen] = dirsep;
+        retval[namelen + 1] = '\0';
+    } /* if */
+
+    return retval;
+} /* DIR_openArchive */
+
+
+static void DIR_enumerateFiles(PHYSFS_Dir *opaque, const char *dname,
+                               int omitSymLinks, PHYSFS_EnumFilesCallback cb,
+                               const char *origdir, void *callbackdata)
+{
+    char *d;
+
+    CVT_TO_DEPENDENT(d, opaque, dname);
+    if (d != NULL)
+    {
+        __PHYSFS_platformEnumerateFiles(d, omitSymLinks, cb,
+                                        origdir, callbackdata);
+        __PHYSFS_smallFree(d);
+    } /* if */
+} /* DIR_enumerateFiles */
+
+
+static PHYSFS_Io *doOpen(PHYSFS_Dir *opaque, const char *name,
+                         const int mode, int *fileExists)
+{
+    char *f;
+    PHYSFS_Io *io = NULL;
+    int existtmp = 0;
+
+    CVT_TO_DEPENDENT(f, opaque, name);
+    BAIL_IF_MACRO(!f, ERRPASS, NULL);
+
+    if (fileExists == NULL)
+        fileExists = &existtmp;
+
+    io = __PHYSFS_createNativeIo(f, mode);
+    if (io == NULL)
+    {
+        const PHYSFS_ErrorCode err = PHYSFS_getLastErrorCode();
+        PHYSFS_Stat statbuf;
+        __PHYSFS_platformStat(f, fileExists, &statbuf);
+        __PHYSFS_setError(err);
+    } /* if */
+    else
+    {
+        *fileExists = 1;
+    } /* else */
+
+    __PHYSFS_smallFree(f);
+
+    return io;
+} /* doOpen */
+
+
+static PHYSFS_Io *DIR_openRead(PHYSFS_Dir *opaque, const char *fnm, int *exist)
+{
+    return doOpen(opaque, fnm, 'r', exist);
+} /* DIR_openRead */
+
+
+static PHYSFS_Io *DIR_openWrite(PHYSFS_Dir *opaque, const char *filename)
+{
+    return doOpen(opaque, filename, 'w', NULL);
+} /* DIR_openWrite */
+
+
+static PHYSFS_Io *DIR_openAppend(PHYSFS_Dir *opaque, const char *filename)
+{
+    return doOpen(opaque, filename, 'a', NULL);
+} /* DIR_openAppend */
+
+
+static int DIR_remove(PHYSFS_Dir *opaque, const char *name)
+{
+    int retval;
+    char *f;
+
+    CVT_TO_DEPENDENT(f, opaque, name);
+    BAIL_IF_MACRO(!f, ERRPASS, 0);
+    retval = __PHYSFS_platformDelete(f);
+    __PHYSFS_smallFree(f);
+    return retval;
+} /* DIR_remove */
+
+
+static int DIR_mkdir(PHYSFS_Dir *opaque, const char *name)
+{
+    int retval;
+    char *f;
+
+    CVT_TO_DEPENDENT(f, opaque, name);
+    BAIL_IF_MACRO(!f, ERRPASS, 0);
+    retval = __PHYSFS_platformMkDir(f);
+    __PHYSFS_smallFree(f);
+    return retval;
+} /* DIR_mkdir */
+
+
+static void DIR_closeArchive(PHYSFS_Dir *opaque)
+{
+    allocator.Free(opaque);
+} /* DIR_closeArchive */
+
+
+static int DIR_stat(PHYSFS_Dir *opaque, const char *name,
+                    int *exists, PHYSFS_Stat *stat)
+{
+    int retval = 0;
+    char *d;
+
+    CVT_TO_DEPENDENT(d, opaque, name);
+    BAIL_IF_MACRO(!d, ERRPASS, 0);
+    retval = __PHYSFS_platformStat(d, exists, stat);
+    __PHYSFS_smallFree(d);
+    return retval;
+} /* DIR_stat */
+
+
+const PHYSFS_Archiver __PHYSFS_Archiver_DIR =
+{
+    {
+        "",
+        "Non-archive, direct filesystem I/O",
+        "Ryan C. Gordon <icculus@icculus.org>",
+        "http://icculus.org/physfs/",
+    },
+    DIR_openArchive,        /* openArchive() method    */
+    DIR_enumerateFiles,     /* enumerateFiles() method */
+    DIR_openRead,           /* openRead() method       */
+    DIR_openWrite,          /* openWrite() method      */
+    DIR_openAppend,         /* openAppend() method     */
+    DIR_remove,             /* remove() method         */
+    DIR_mkdir,              /* mkdir() method          */
+    DIR_closeArchive,       /* closeArchive() method   */
+    DIR_stat                /* stat() method           */
+};
+
+/* end of dir.c ... */
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/misc/physfs/src/archiver_grp.c	Sat Nov 17 20:30:32 2012 -0500
@@ -0,0 +1,110 @@
+/*
+ * GRP support routines for PhysicsFS.
+ *
+ * This driver handles BUILD engine archives ("groupfiles"). This format
+ *  (but not this driver) was put together by Ken Silverman.
+ *
+ * The format is simple enough. In Ken's words:
+ *
+ *    What's the .GRP file format?
+ *
+ *     The ".grp" file format is just a collection of a lot of files stored
+ *     into 1 big one. I tried to make the format as simple as possible: The
+ *     first 12 bytes contains my name, "KenSilverman". The next 4 bytes is
+ *     the number of files that were compacted into the group file. Then for
+ *     each file, there is a 16 byte structure, where the first 12 bytes are
+ *     the filename, and the last 4 bytes are the file's size. The rest of
+ *     the group file is just the raw data packed one after the other in the
+ *     same order as the list of files.
+ *
+ * (That info is from http://www.advsys.net/ken/build.htm ...)
+ *
+ * Please see the file LICENSE.txt in the source's root directory.
+ *
+ *  This file written by Ryan C. Gordon.
+ */
+
+#define __PHYSICSFS_INTERNAL__
+#include "physfs_internal.h"
+
+#if PHYSFS_SUPPORTS_GRP
+
+static UNPKentry *grpLoadEntries(PHYSFS_Io *io, PHYSFS_uint32 fileCount)
+{
+    PHYSFS_uint32 location = 16;  /* sizeof sig. */
+    UNPKentry *entries = NULL;
+    UNPKentry *entry = NULL;
+    char *ptr = NULL;
+
+    entries = (UNPKentry *) allocator.Malloc(sizeof (UNPKentry) * fileCount);
+    BAIL_IF_MACRO(entries == NULL, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
+
+    location += (16 * fileCount);
+
+    for (entry = entries; fileCount > 0; fileCount--, entry++)
+    {
+        GOTO_IF_MACRO(!__PHYSFS_readAll(io, &entry->name, 12), ERRPASS, failed);
+        GOTO_IF_MACRO(!__PHYSFS_readAll(io, &entry->size, 4), ERRPASS, failed);
+        entry->name[12] = '\0';  /* name isn't null-terminated in file. */
+        if ((ptr = strchr(entry->name, ' ')) != NULL)
+            *ptr = '\0';  /* trim extra spaces. */
+
+        entry->size = PHYSFS_swapULE32(entry->size);
+        entry->startPos = location;
+        location += entry->size;
+    } /* for */
+
+    return entries;
+
+failed:
+    allocator.Free(entries);
+    return NULL;
+} /* grpLoadEntries */
+
+
+static void *GRP_openArchive(PHYSFS_Io *io, const char *name, int forWriting)
+{
+    PHYSFS_uint8 buf[12];
+    PHYSFS_uint32 count = 0;
+    UNPKentry *entries = NULL;
+
+    assert(io != NULL);  /* shouldn't ever happen. */
+
+    BAIL_IF_MACRO(forWriting, PHYSFS_ERR_READ_ONLY, NULL);
+
+    BAIL_IF_MACRO(!__PHYSFS_readAll(io, buf, sizeof (buf)), ERRPASS, NULL);
+    if (memcmp(buf, "KenSilverman", sizeof (buf)) != 0)
+        BAIL_MACRO(PHYSFS_ERR_UNSUPPORTED, NULL);
+
+    BAIL_IF_MACRO(!__PHYSFS_readAll(io, &count, sizeof(count)), ERRPASS, NULL);
+    count = PHYSFS_swapULE32(count);
+
+    entries = grpLoadEntries(io, count);
+    BAIL_IF_MACRO(!entries, ERRPASS, NULL);
+    return UNPK_openArchive(io, entries, count);
+} /* GRP_openArchive */
+
+
+const PHYSFS_Archiver __PHYSFS_Archiver_GRP =
+{
+    {
+        "GRP",
+        "Build engine Groupfile format",
+        "Ryan C. Gordon <icculus@icculus.org>",
+        "http://icculus.org/physfs/",
+    },
+    GRP_openArchive,        /* openArchive() method    */
+    UNPK_enumerateFiles,    /* enumerateFiles() method */
+    UNPK_openRead,          /* openRead() method       */
+    UNPK_openWrite,         /* openWrite() method      */
+    UNPK_openAppend,        /* openAppend() method     */
+    UNPK_remove,            /* remove() method         */
+    UNPK_mkdir,             /* mkdir() method          */
+    UNPK_closeArchive,      /* closeArchive() method   */
+    UNPK_stat               /* stat() method           */
+};
+
+#endif  /* defined PHYSFS_SUPPORTS_GRP */
+
+/* end of grp.c ... */
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/misc/physfs/src/archiver_hog.c	Sat Nov 17 20:30:32 2012 -0500
@@ -0,0 +1,116 @@
+/*
+ * HOG support routines for PhysicsFS.
+ *
+ * This driver handles Descent I/II HOG archives.
+ *
+ * The format is very simple:
+ *
+ *   The file always starts with the 3-byte signature "DHF" (Descent
+ *   HOG file). After that the files of a HOG are just attached after
+ *   another, divided by a 17 bytes header, which specifies the name
+ *   and length (in bytes) of the forthcoming file! So you just read
+ *   the header with its information of how big the following file is,
+ *   and then skip exact that number of bytes to get to the next file
+ *   in that HOG.
+ *
+ *    char sig[3] = {'D', 'H', 'F'}; // "DHF"=Descent HOG File
+ *
+ *    struct {
+ *     char file_name[13]; // Filename, padded to 13 bytes with 0s
+ *     int file_size; // filesize in bytes
+ *     char data[file_size]; // The file data
+ *    } FILE_STRUCT; // Repeated until the end of the file.
+ *
+ * (That info is from http://www.descent2.com/ddn/specs/hog/)
+ *
+ * Please see the file LICENSE.txt in the source's root directory.
+ *
+ *  This file written by Bradley Bell.
+ *  Based on grp.c by Ryan C. Gordon.
+ */
+
+#define __PHYSICSFS_INTERNAL__
+#include "physfs_internal.h"
+
+#if PHYSFS_SUPPORTS_HOG
+
+static UNPKentry *hogLoadEntries(PHYSFS_Io *io, PHYSFS_uint32 *_entCount)
+{
+    const PHYSFS_uint64 iolen = io->length(io);
+    PHYSFS_uint32 entCount = 0;
+    void *ptr = NULL;
+    UNPKentry *entries = NULL;
+    UNPKentry *entry = NULL;
+    PHYSFS_uint32 size = 0;
+    PHYSFS_uint32 pos = 3;
+
+    while (pos < iolen)
+    {
+        entCount++;
+        ptr = allocator.Realloc(ptr, sizeof (UNPKentry) * entCount);
+        GOTO_IF_MACRO(ptr == NULL, PHYSFS_ERR_OUT_OF_MEMORY, failed);
+        entries = (UNPKentry *) ptr;
+        entry = &entries[entCount-1];
+
+        GOTO_IF_MACRO(!__PHYSFS_readAll(io, &entry->name, 13), ERRPASS, failed);
+        pos += 13;
+        GOTO_IF_MACRO(!__PHYSFS_readAll(io, &size, 4), ERRPASS, failed);
+        pos += 4;
+
+        entry->size = PHYSFS_swapULE32(size);
+        entry->startPos = pos;
+        pos += size;
+
+        /* skip over entry */
+        GOTO_IF_MACRO(!io->seek(io, pos), ERRPASS, failed);
+    } /* while */
+
+    *_entCount = entCount;
+    return entries;
+
+failed:
+    allocator.Free(entries);
+    return NULL;
+} /* hogLoadEntries */
+
+
+static void *HOG_openArchive(PHYSFS_Io *io, const char *name, int forWriting)
+{
+    PHYSFS_uint8 buf[3];
+    PHYSFS_uint32 count = 0;
+    UNPKentry *entries = NULL;
+
+    assert(io != NULL);  /* shouldn't ever happen. */
+    BAIL_IF_MACRO(forWriting, PHYSFS_ERR_READ_ONLY, NULL);
+    BAIL_IF_MACRO(!__PHYSFS_readAll(io, buf, 3), ERRPASS, NULL);
+    BAIL_IF_MACRO(memcmp(buf, "DHF", 3) != 0, PHYSFS_ERR_UNSUPPORTED, NULL);
+
+    entries = hogLoadEntries(io, &count);
+    BAIL_IF_MACRO(!entries, ERRPASS, NULL);
+    return UNPK_openArchive(io, entries, count);
+} /* HOG_openArchive */
+
+
+const PHYSFS_Archiver __PHYSFS_Archiver_HOG =
+{
+    {
+        "HOG",
+        "Descent I/II HOG file format",
+        "Bradley Bell <btb@icculus.org>",
+        "http://icculus.org/physfs/",
+    },
+    HOG_openArchive,         /* openArchive() method    */
+    UNPK_enumerateFiles,     /* enumerateFiles() method */
+    UNPK_openRead,           /* openRead() method       */
+    UNPK_openWrite,          /* openWrite() method      */
+    UNPK_openAppend,         /* openAppend() method     */
+    UNPK_remove,             /* remove() method         */
+    UNPK_mkdir,              /* mkdir() method          */
+    UNPK_closeArchive,       /* closeArchive() method   */
+    UNPK_stat                /* stat() method           */
+};
+
+#endif  /* defined PHYSFS_SUPPORTS_HOG */
+
+/* end of hog.c ... */
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/misc/physfs/src/archiver_iso9660.c	Sat Nov 17 20:30:32 2012 -0500
@@ -0,0 +1,969 @@
+/*
+ * ISO9660 support routines for PhysicsFS.
+ *
+ * Please see the file LICENSE.txt in the source's root directory.
+ *
+ *  This file written by Christoph Nelles.
+ */
+
+/* !!! FIXME: this file needs Ryanification. */
+
+/*
+ * Handles CD-ROM disk images (and raw CD-ROM devices).
+ *
+ * Not supported:
+ * - RockRidge
+ * - Non 2048 Sectors
+ * - UDF
+ *
+ * Deviations from the standard
+ * - Ignores mandatory sort order
+ * - Allows various invalid file names
+ *
+ * Problems
+ * - Ambiguities in the standard
+ */
+
+#define __PHYSICSFS_INTERNAL__
+#include "physfs_internal.h"
+
+#if PHYSFS_SUPPORTS_ISO9660
+
+#include <time.h>
+
+/* cache files smaller than this completely in memory */
+#define ISO9660_FULLCACHEMAXSIZE 2048
+
+/* !!! FIXME: this is going to cause trouble. */
+#pragma pack(push)  /* push current alignment to stack */
+#pragma pack(1)     /* set alignment to 1 byte boundary */
+
+/* This is the format as defined by the standard
+typedef struct
+{
+    PHYSFS_uint32 lsb;
+    PHYSFS_uint32 msb;
+} ISOBB32bit; // 32byte Both Byte type, means the value first in LSB then in MSB
+
+typedef struct
+{
+    PHYSFS_uint16 lsb;
+    PHYSFS_uint16 msb;
+} ISOBB16bit; // 16byte Both Byte type, means the value first in LSB then in MSB
+*/
+
+/* define better ones to simplify coding (less if's) */
+#if PHYSFS_BYTEORDER == PHYSFS_LIL_ENDIAN
+#define ISOBB32bit(name) PHYSFS_uint32 name; PHYSFS_uint32 __dummy_##name;
+#define ISOBB16bit(name) PHYSFS_uint16 name; PHYSFS_uint16 __dummy_##name;
+#else
+#define ISOBB32bit(name) PHYSFS_uint32 __dummy_##name; PHYSFS_uint32 name;
+#define ISOBB16bit(name) PHYSFS_uint16 __dummy_##name; PHYSFS_uint16 name;
+#endif
+
+typedef struct
+{
+    char year[4];
+    char month[2];
+    char day[2];
+    char hour[2];
+    char minute[2];
+    char second[2];
+    char centisec[2];
+    PHYSFS_sint8 offset; /* in 15min from GMT */
+} ISO9660VolumeTimestamp;
+
+typedef struct
+{
+    PHYSFS_uint8 year;
+    PHYSFS_uint8 month;
+    PHYSFS_uint8 day;
+    PHYSFS_uint8 hour;
+    PHYSFS_uint8 minute;
+    PHYSFS_uint8 second;
+    PHYSFS_sint8 offset;
+} ISO9660FileTimestamp;
+
+typedef struct
+{
+  unsigned existence:1;
+  unsigned directory:1;
+  unsigned associated_file:1;
+  unsigned record:1;
+  unsigned protection:1;
+  unsigned reserved:2;
+  unsigned multiextent:1;
+} ISO9660FileFlags;
+
+typedef struct
+{
+    PHYSFS_uint8 length;
+    PHYSFS_uint8 attribute_length;
+    ISOBB32bit(extent_location)
+    ISOBB32bit(data_length)
+    ISO9660FileTimestamp timestamp;
+    ISO9660FileFlags file_flags;
+    PHYSFS_uint8 file_unit_size;
+    PHYSFS_uint8 gap_size;
+    ISOBB16bit(vol_seq_no)
+    PHYSFS_uint8 len_fi;
+    char unused;
+} ISO9660RootDirectoryRecord;
+
+/* this structure is combined for all Volume descriptor types */
+typedef struct
+{
+    PHYSFS_uint8 type;
+    char identifier[5];
+    PHYSFS_uint8 version;
+    PHYSFS_uint8 flags;
+    char system_identifier[32];
+    char volume_identifier[32];
+    char unused2[8];
+    ISOBB32bit(space_size)
+    PHYSFS_uint8 escape_sequences[32];
+    ISOBB16bit(vol_set_size)
+    ISOBB16bit(vol_seq_no)
+    ISOBB16bit(block_size)
+    ISOBB32bit(path_table_size)
+/*    PHYSFS_uint32 path_table_start_lsb; // why didn't they use both byte type?
+    PHYSFS_uint32 opt_path_table_start_lsb;
+    PHYSFS_uint32 path_table_start_msb;
+    PHYSFS_uint32 opt_path_table_start_msb;*/
+#if PHYSFS_BYTEORDER == PHYSFS_LIL_ENDIAN
+    PHYSFS_uint32 path_table_start;
+    PHYSFS_uint32 opt_path_table_start;
+    PHYSFS_uint32 unused6;
+    PHYSFS_uint32 unused7;
+#else
+    PHYSFS_uint32 unused6;
+    PHYSFS_uint32 unused7;
+    PHYSFS_uint32 path_table_start;
+    PHYSFS_uint32 opt_path_table_start;
+#endif
+    ISO9660RootDirectoryRecord rootdirectory;
+    char set_identifier[128];
+    char publisher_identifier[128];
+    char preparer_identifer[128];
+    char application_identifier[128];
+    char copyright_file_identifier[37];
+    char abstract_file_identifier[37];
+    char bibliographic_file_identifier[37];
+    ISO9660VolumeTimestamp creation_timestamp;
+    ISO9660VolumeTimestamp modification_timestamp;
+    ISO9660VolumeTimestamp expiration_timestamp;
+    ISO9660VolumeTimestamp effective_timestamp;
+    PHYSFS_uint8 file_structure_version;
+    char unused4;
+    char application_use[512];
+    char unused5[653];
+} ISO9660VolumeDescriptor;
+
+typedef struct
+{
+    PHYSFS_uint8 recordlen;
+    PHYSFS_uint8 extattributelen;
+    ISOBB32bit(extentpos)
+    ISOBB32bit(datalen)
+    ISO9660FileTimestamp recordtime;
+    ISO9660FileFlags flags;
+    PHYSFS_uint8 file_unit_size;
+    PHYSFS_uint8 interleave_gap;
+    ISOBB16bit(volseqno)
+    PHYSFS_uint8 filenamelen;
+    char filename[222]; /* This is not exact, but makes reading easier */
+} ISO9660FileDescriptor;
+
+typedef struct
+{
+    ISOBB16bit(owner)
+    ISOBB16bit(group)
+    PHYSFS_uint16 flags; /* not implemented*/
+    ISO9660VolumeTimestamp create_time; /* yes, not file timestamp */
+    ISO9660VolumeTimestamp mod_time;
+    ISO9660VolumeTimestamp expire_time;
+    ISO9660VolumeTimestamp effective_time;
+    PHYSFS_uint8 record_format;
+    PHYSFS_uint8 record_attributes;
+    ISOBB16bit(record_len)
+    char system_identifier[32];
+    char system_use[64];
+    PHYSFS_uint8 version;
+    ISOBB16bit(escape_len)
+    char reserved[64];
+    /** further fields not implemented */
+} ISO9660ExtAttributeRec;
+
+#pragma pack(pop)   /* restore original alignment from stack */
+
+typedef struct
+{
+    PHYSFS_Io *io;
+    PHYSFS_uint32 rootdirstart;
+    PHYSFS_uint32 rootdirsize;
+    PHYSFS_uint64 currpos;
+    int isjoliet;
+    char *path;
+    void *mutex;
+} ISO9660Handle;
+
+
+typedef struct __ISO9660FileHandle
+{
+    PHYSFS_sint64 filesize;
+    PHYSFS_uint64 currpos;
+    PHYSFS_uint64 startblock;
+    ISO9660Handle *isohandle;
+    PHYSFS_uint32 (*read) (struct __ISO9660FileHandle *filehandle, void *buffer,
+            PHYSFS_uint64 len);
+    int (*seek)(struct __ISO9660FileHandle *filehandle,  PHYSFS_sint64 offset);
+    void (*close)(struct __ISO9660FileHandle *filehandle);
+    /* !!! FIXME: anonymouse union is going to cause problems. */
+    union
+    {
+        /* !!! FIXME: just use a memory PHYSFS_Io here, unify all this code. */
+        char *cacheddata; /* data of file when cached */
+        PHYSFS_Io *io; /* handle to separate opened file */
+    };
+} ISO9660FileHandle;
+
+/*******************************************************************************
+ * Time conversion functions
+ ******************************************************************************/
+
+static PHYSFS_sint64 iso_mktime(ISO9660FileTimestamp *timestamp)
+{
+    struct tm tm;
+    tm.tm_year = timestamp->year;
+    tm.tm_mon = timestamp->month - 1;
+    tm.tm_mday = timestamp->day;
+    tm.tm_hour = timestamp->hour;
+    tm.tm_min = timestamp->minute;
+    tm.tm_sec = timestamp->second;
+    /* Ignore GMT offset for now... */
+    return mktime(&tm);
+} /* iso_mktime */
+
+static int iso_atoi2(char *text)
+{
+    return ((text[0] - 40) * 10) + (text[1] - 40);
+} /* iso_atoi2 */
+
+static int iso_atoi4(char *text)
+{
+    return ((text[0] - 40) * 1000) + ((text[1] - 40) * 100) +
+           ((text[2] - 40) * 10) + (text[3] - 40);
+} /* iso_atoi4 */
+
+static PHYSFS_sint64 iso_volume_mktime(ISO9660VolumeTimestamp *timestamp)
+{
+    struct tm tm;
+    tm.tm_year = iso_atoi4(timestamp->year);
+    tm.tm_mon = iso_atoi2(timestamp->month) - 1;
+    tm.tm_mday = iso_atoi2(timestamp->day);
+    tm.tm_hour = iso_atoi2(timestamp->hour);
+    tm.tm_min = iso_atoi2(timestamp->minute);
+    tm.tm_sec = iso_atoi2(timestamp->second);
+    /* this allows values outside the range of a unix timestamp... sanitize them */
+    PHYSFS_sint64 value = mktime(&tm);
+    return value == -1 ? 0 : value;
+} /* iso_volume_mktime */
+
+/*******************************************************************************
+ * Filename extraction
+ ******************************************************************************/
+
+static int iso_extractfilenameISO(ISO9660FileDescriptor *descriptor,
+        char *filename, int *version)
+{
+    *filename = '\0';
+    if (descriptor->flags.directory)
+    {
+        strncpy(filename, descriptor->filename, descriptor->filenamelen);
+        filename[descriptor->filenamelen] = '\0';
+        *version = 0;
+    } /* if */
+    else
+    {
+        /* find last SEPARATOR2 */
+        int pos = 0;
+        int lastfound = -1;
+        for(;pos < descriptor->filenamelen; pos++)
+            if (descriptor->filename[pos] == ';')
+                lastfound = pos;
+        BAIL_IF_MACRO(lastfound < 1, PHYSFS_ERR_NO_SUCH_PATH /* !!! FIXME: PHYSFS_ERR_BAD_FILENAME */, -1);
+        BAIL_IF_MACRO(lastfound == (descriptor->filenamelen -1), PHYSFS_ERR_NO_SUCH_PATH /* !!! PHYSFS_ERR_BAD_FILENAME */, -1);
+        strncpy(filename, descriptor->filename, lastfound);
+        if (filename[lastfound - 1] == '.')
+            filename[lastfound - 1] = '\0'; /* consume trailing ., as done in all implementations */
+        else
+            filename[lastfound] = '\0';
+        *version = atoi(descriptor->filename + lastfound);
+    } /* else */
+
+    return 0;
+} /* iso_extractfilenameISO */
+
+
+static int iso_extractfilenameUCS2(ISO9660FileDescriptor *descriptor,
+        char *filename, int *version)
+{
+    PHYSFS_uint16 tmp[128];
+    PHYSFS_uint16 *src;
+    int len;
+
+    *filename = '\0';
+    *version = 1; /* Joliet does not have versions.. at least not on my images */
+
+    src = (PHYSFS_uint16*) descriptor->filename;
+    len = descriptor->filenamelen / 2;
+    tmp[len] = 0;
+
+    while(len--)
+        tmp[len] = PHYSFS_swapUBE16(src[len]);
+
+    PHYSFS_utf8FromUcs2(tmp, filename, 255);
+
+    return 0;
+} /* iso_extractfilenameUCS2 */
+
+
+static int iso_extractfilename(ISO9660Handle *handle,
+        ISO9660FileDescriptor *descriptor, char *filename,int *version)
+{
+    if (handle->isjoliet)
+        return iso_extractfilenameUCS2(descriptor, filename, version);
+    else
+        return iso_extractfilenameISO(descriptor, filename, version);
+} /* iso_extractfilename */
+
+/*******************************************************************************
+ * Basic image read functions
+ ******************************************************************************/
+
+static int iso_readimage(ISO9660Handle *handle, PHYSFS_uint64 where,
+                         void *buffer, PHYSFS_uint64 len)
+{
+    BAIL_IF_MACRO(!__PHYSFS_platformGrabMutex(handle->mutex), ERRPASS, -1);
+    int rc = -1;
+    if (where != handle->currpos)
+        GOTO_IF_MACRO(!handle->io->seek(handle->io,where), ERRPASS, unlockme);
+    rc = handle->io->read(handle->io, buffer, len);
+    if (rc == -1)
+    {
+        handle->currpos = (PHYSFS_uint64) -1;
+        goto unlockme;
+    } /* if */
+    handle->currpos += rc;
+
+    unlockme:
+    __PHYSFS_platformReleaseMutex(handle->mutex);
+    return rc;
+} /* iso_readimage */
+
+
+static PHYSFS_sint64 iso_readfiledescriptor(ISO9660Handle *handle,
+                                            PHYSFS_uint64 where,
+                                            ISO9660FileDescriptor *descriptor)
+{
+    PHYSFS_sint64 rc = iso_readimage(handle, where, descriptor,
+                                     sizeof (descriptor->recordlen));
+    BAIL_IF_MACRO(rc == -1, ERRPASS, -1);
+    BAIL_IF_MACRO(rc != 1, PHYSFS_ERR_CORRUPT, -1);
+
+    if (descriptor->recordlen == 0)
+        return 0; /* fill bytes at the end of a sector */
+
+    rc = iso_readimage(handle, where + 1, &descriptor->extattributelen,
+            descriptor->recordlen - sizeof(descriptor->recordlen));
+    BAIL_IF_MACRO(rc == -1, ERRPASS, -1);
+    BAIL_IF_MACRO(rc != 1, PHYSFS_ERR_CORRUPT, -1);
+
+    return 0;
+} /* iso_readfiledescriptor */
+
+static void iso_extractsubpath(char *path, char **subpath)
+{
+    *subpath = strchr(path,'/');
+    if (*subpath != 0)
+    {
+        **subpath = 0;
+        *subpath +=1;
+    } /* if */
+} /* iso_extractsubpath */
+
+/*
+ * Don't use path tables, they are not necessarily faster, but more complicated
+ * to implement as they store only directories and not files, so searching for
+ * a file needs to branch to the directory extent sooner or later.
+ */
+static int iso_find_dir_entry(ISO9660Handle *handle,const char *path,
+                              ISO9660FileDescriptor *descriptor, int *exists)
+{
+    char *subpath = 0;
+    PHYSFS_uint64 readpos, end_of_dir;
+    char filename[255];
+    char pathcopy[256];
+    char *mypath;
+    int version = 0;
+
+    strcpy(pathcopy, path);
+    mypath = pathcopy;
+    *exists = 0;
+
+    readpos = handle->rootdirstart;
+    end_of_dir = handle->rootdirstart + handle->rootdirsize;
+    iso_extractsubpath(mypath, &subpath);
+    while (1)
+    {
+        BAIL_IF_MACRO(iso_readfiledescriptor(handle, readpos, descriptor), ERRPASS, -1);
+
+        /* recordlen = 0 -> no more entries or fill entry */
+        if (!descriptor->recordlen)
+        {
+            /* if we are in the last sector of the directory & it's 0 -> end */
+            if ((end_of_dir - 2048) <= (readpos -1))
+                break; /* finished */
+
+            /* else skip to the next sector & continue; */
+            readpos = (((readpos - 1) / 2048) + 1) * 2048;
+            continue;
+        } /* if */
+
+        readpos += descriptor->recordlen;
+        if (descriptor->filenamelen == 1 && (descriptor->filename[0] == 0
+                || descriptor->filename[0] == 1))
+            continue; /* special ones, ignore */
+
+        BAIL_IF_MACRO(
+            iso_extractfilename(handle, descriptor, filename, &version),
+            ERRPASS, -1);
+
+        if (strcmp(filename, mypath) == 0)
+        {
+            if ( (subpath == 0) || (subpath[0] == 0) )
+            {
+                *exists = 1;
+                return 0;  /* no subpaths left and we found the entry */
+            } /* if */
+
+            if (descriptor->flags.directory)
+            {
+                /* shorten the path to the subpath */
+                mypath = subpath;
+                iso_extractsubpath(mypath, &subpath);
+                /* gosub to the new directory extent */
+                readpos = descriptor->extentpos * 2048;
+                end_of_dir = readpos + descriptor->datalen;
+            } /* if */
+            else
+            {
+                /* we're at a file but have a remaining subpath -> no match */
+                return 0;
+            } /* else */
+        } /* if */
+    } /* while */
+
+    return 0;
+} /* iso_find_dir_entry */
+
+
+static int iso_read_ext_attributes(ISO9660Handle *handle, int block,
+                                   ISO9660ExtAttributeRec *attributes)
+{
+    return iso_readimage(handle, block * 2048, attributes,
+                         sizeof(ISO9660ExtAttributeRec));
+} /* iso_read_ext_attributes */
+
+
+static int ISO9660_flush(PHYSFS_Io *io) { return 1;  /* no write support. */ }
+
+static PHYSFS_Io *ISO9660_duplicate(PHYSFS_Io *_io)
+{
+    BAIL_MACRO(PHYSFS_ERR_UNSUPPORTED, NULL);  /* !!! FIXME: write me. */
+} /* ISO9660_duplicate */
+
+
+static void ISO9660_destroy(PHYSFS_Io *io)
+{
+    ISO9660FileHandle *fhandle = (ISO9660FileHandle*) io->opaque;
+    fhandle->close(fhandle);
+    allocator.Free(io);
+} /* ISO9660_destroy */
+
+
+static PHYSFS_sint64 ISO9660_read(PHYSFS_Io *io, void *buf, PHYSFS_uint64 len)
+{
+    ISO9660FileHandle *fhandle = (ISO9660FileHandle*) io->opaque;
+    return fhandle->read(fhandle, buf, len);
+} /* ISO9660_read */
+
+
+static PHYSFS_sint64 ISO9660_write(PHYSFS_Io *io, const void *b, PHYSFS_uint64 l)
+{
+    BAIL_MACRO(PHYSFS_ERR_READ_ONLY, -1);
+} /* ISO9660_write */
+
+
+static PHYSFS_sint64 ISO9660_tell(PHYSFS_Io *io)
+{
+    return ((ISO9660FileHandle*) io->opaque)->currpos;
+} /* ISO9660_tell */
+
+
+static int ISO9660_seek(PHYSFS_Io *io, PHYSFS_uint64 offset)
+{
+    ISO9660FileHandle *fhandle = (ISO9660FileHandle*) io->opaque;
+    return fhandle->seek(fhandle, offset);
+} /* ISO9660_seek */
+
+
+static PHYSFS_sint64 ISO9660_length(PHYSFS_Io *io)
+{
+    return ((ISO9660FileHandle*) io->opaque)->filesize;
+} /* ISO9660_length */
+
+
+static const PHYSFS_Io ISO9660_Io =
+{
+    CURRENT_PHYSFS_IO_API_VERSION, NULL,
+    ISO9660_read,
+    ISO9660_write,
+    ISO9660_seek,
+    ISO9660_tell,
+    ISO9660_length,
+    ISO9660_duplicate,
+    ISO9660_flush,
+    ISO9660_destroy
+};
+
+
+/*******************************************************************************
+ * Archive management functions
+ ******************************************************************************/
+
+static void *ISO9660_openArchive(PHYSFS_Io *io, const char *filename, int forWriting)
+{
+    char magicnumber[6];
+    ISO9660Handle *handle;
+    int founddescriptor = 0;
+    int foundjoliet = 0;
+
+    assert(io != NULL);  /* shouldn't ever happen. */
+
+    BAIL_IF_MACRO(forWriting, PHYSFS_ERR_READ_ONLY, NULL);
+
+    /* Skip system area to magic number in Volume descriptor */
+    BAIL_IF_MACRO(!io->seek(io, 32769), ERRPASS, NULL);
+    BAIL_IF_MACRO(!io->read(io, magicnumber, 5) != 5, ERRPASS, NULL);
+    if (memcmp(magicnumber, "CD001", 6) != 0)
+        BAIL_MACRO(PHYSFS_ERR_UNSUPPORTED, NULL);
+
+    handle = allocator.Malloc(sizeof(ISO9660Handle));
+    GOTO_IF_MACRO(!handle, PHYSFS_ERR_OUT_OF_MEMORY, errorcleanup);
+    handle->path = 0;
+    handle->mutex= 0;
+    handle->io = NULL;
+
+    handle->path = allocator.Malloc(strlen(filename) + 1);
+    GOTO_IF_MACRO(!handle->path, PHYSFS_ERR_OUT_OF_MEMORY, errorcleanup);
+    strcpy(handle->path, filename);
+
+    handle->mutex = __PHYSFS_platformCreateMutex();
+    GOTO_IF_MACRO(!handle->mutex, ERRPASS, errorcleanup);
+
+    handle->io = io;
+
+    /* seek Primary Volume Descriptor */
+    GOTO_IF_MACRO(!io->seek(io, 32768), PHYSFS_ERR_IO, errorcleanup);
+
+    while (1)
+    {
+        ISO9660VolumeDescriptor descriptor;
+        GOTO_IF_MACRO(io->read(io, &descriptor, sizeof(ISO9660VolumeDescriptor)) != sizeof(ISO9660VolumeDescriptor), PHYSFS_ERR_IO, errorcleanup);
+        GOTO_IF_MACRO(strncmp(descriptor.identifier, "CD001", 5) != 0, PHYSFS_ERR_UNSUPPORTED, errorcleanup);
+
+        if (descriptor.type == 255)
+        {
+            /* type 255 terminates the volume descriptor list */
+            if (founddescriptor)
+                return handle; /* ok, we've found one volume descriptor */
+            else
+                GOTO_MACRO(PHYSFS_ERR_CORRUPT, errorcleanup);
+        } /* if */
+        if (descriptor.type == 1 && !founddescriptor)
+        {
+            handle->currpos = io->tell(io);
+            handle->rootdirstart =
+                    descriptor.rootdirectory.extent_location * 2048;
+            handle->rootdirsize =
+                    descriptor.rootdirectory.data_length;
+            handle->isjoliet = 0;
+            founddescriptor = 1; /* continue search for joliet */
+        } /* if */
+        if (descriptor.type == 2 && !foundjoliet)
+        {
+            /* check if is joliet */
+            PHYSFS_uint8 *s = descriptor.escape_sequences;
+            int joliet = !(descriptor.flags & 1)
+                    && (s[0] == 0x25)
+                    && (s[1] == 0x2F)
+                    && ((s[2] == 0x40) || (s[2] == 0x43) || (s[2] == 0x45));
+            if (!joliet)
+                continue;
+
+            handle->currpos = io->tell(io);
+            handle->rootdirstart =
+                    descriptor.rootdirectory.extent_location * 2048;
+            handle->rootdirsize =
+                    descriptor.rootdirectory.data_length;
+            handle->isjoliet = 1;
+            founddescriptor = 1;
+            foundjoliet = 1;
+        } /* if */
+    } /* while */
+
+    GOTO_MACRO(PHYSFS_ERR_CORRUPT, errorcleanup);  /* not found. */
+
+errorcleanup:
+    if (handle)
+    {
+        if (handle->path)
+            allocator.Free(handle->path);
+        if (handle->mutex)
+            __PHYSFS_platformDestroyMutex(handle->mutex);
+        allocator.Free(handle);
+    } /* if */
+    return NULL;
+} /* ISO9660_openArchive */
+
+
+static void ISO9660_closeArchive(PHYSFS_Dir *opaque)
+{
+    ISO9660Handle *handle = (ISO9660Handle*) opaque;
+    handle->io->destroy(handle->io);
+    __PHYSFS_platformDestroyMutex(handle->mutex);
+    allocator.Free(handle->path);
+    allocator.Free(handle);
+} /* ISO9660_closeArchive */
+
+
+/*******************************************************************************
+ * Read functions
+ ******************************************************************************/
+
+
+static PHYSFS_uint32 iso_file_read_mem(ISO9660FileHandle *filehandle,
+                                       void *buffer, PHYSFS_uint64 len)
+{
+    /* check remaining bytes & max obj which can be fetched */
+    const PHYSFS_sint64 bytesleft = filehandle->filesize - filehandle->currpos;
+    if (bytesleft < len)
+        len = bytesleft;
+
+    if (len == 0)
+        return 0;
+
+    memcpy(buffer, filehandle->cacheddata + filehandle->currpos, (size_t) len);
+
+    filehandle->currpos += len;
+    return (PHYSFS_uint32) len;
+} /* iso_file_read_mem */
+
+
+static int iso_file_seek_mem(ISO9660FileHandle *fhandle, PHYSFS_sint64 offset)
+{
+    BAIL_IF_MACRO(offset < 0, PHYSFS_ERR_INVALID_ARGUMENT, 0);
+    BAIL_IF_MACRO(offset >= fhandle->filesize, PHYSFS_ERR_PAST_EOF, 0);
+
+    fhandle->currpos = offset;
+    return 0;
+} /* iso_file_seek_mem */
+
+
+static void iso_file_close_mem(ISO9660FileHandle *fhandle)
+{
+    allocator.Free(fhandle->cacheddata);
+    allocator.Free(fhandle);
+} /* iso_file_close_mem */
+
+
+static PHYSFS_uint32 iso_file_read_foreign(ISO9660FileHandle *filehandle,
+                                           void *buffer, PHYSFS_uint64 len)
+{
+    /* check remaining bytes & max obj which can be fetched */
+    const PHYSFS_sint64 bytesleft = filehandle->filesize - filehandle->currpos;
+    if (bytesleft < len)
+        len = bytesleft;
+
+    const PHYSFS_sint64 rc = filehandle->io->read(filehandle->io, buffer, len);
+    BAIL_IF_MACRO(rc == -1, ERRPASS, -1);
+
+    filehandle->currpos += rc; /* i trust my internal book keeping */
+    BAIL_IF_MACRO(rc < len, PHYSFS_ERR_CORRUPT, -1);
+    return rc;
+} /* iso_file_read_foreign */
+
+
+static int iso_file_seek_foreign(ISO9660FileHandle *fhandle,
+                                 PHYSFS_sint64 offset)
+{
+    BAIL_IF_MACRO(offset < 0, PHYSFS_ERR_INVALID_ARGUMENT, 0);
+    BAIL_IF_MACRO(offset >= fhandle->filesize, PHYSFS_ERR_PAST_EOF, 0);
+
+    PHYSFS_sint64 pos = fhandle->startblock * 2048 + offset;
+    BAIL_IF_MACRO(!fhandle->io->seek(fhandle->io, pos), ERRPASS, -1);
+
+    fhandle->currpos = offset;
+    return 0;
+} /* iso_file_seek_foreign */
+
+
+static void iso_file_close_foreign(ISO9660FileHandle *fhandle)
+{
+    fhandle->io->destroy(fhandle->io);
+    allocator.Free(fhandle);
+} /* iso_file_close_foreign */
+
+
+static int iso_file_open_mem(ISO9660Handle *handle, ISO9660FileHandle *fhandle)
+{
+    fhandle->cacheddata = allocator.Malloc(fhandle->filesize);
+    BAIL_IF_MACRO(!fhandle->cacheddata, PHYSFS_ERR_OUT_OF_MEMORY, -1);
+    int rc = iso_readimage(handle, fhandle->startblock * 2048,
+                           fhandle->cacheddata, fhandle->filesize);
+    GOTO_IF_MACRO(rc < 0, ERRPASS, freemem);
+    GOTO_IF_MACRO(rc == 0, PHYSFS_ERR_CORRUPT, freemem);
+
+    fhandle->read = iso_file_read_mem;
+    fhandle->seek = iso_file_seek_mem;
+    fhandle->close = iso_file_close_mem;
+    return 0;
+
+freemem:
+    allocator.Free(fhandle->cacheddata);
+    return -1;
+} /* iso_file_open_mem */
+
+
+static int iso_file_open_foreign(ISO9660Handle *handle,
+                                 ISO9660FileHandle *fhandle)
+{
+    int rc;
+    fhandle->io = __PHYSFS_createNativeIo(handle->path, 'r');
+    BAIL_IF_MACRO(!fhandle->io, ERRPASS, -1);
+    rc = fhandle->io->seek(fhandle->io, fhandle->startblock * 2048);
+    GOTO_IF_MACRO(!rc, ERRPASS, closefile);
+
+    fhandle->read = iso_file_read_foreign;
+    fhandle->seek = iso_file_seek_foreign;
+    fhandle->close = iso_file_close_foreign;
+    return 0;
+
+closefile:
+    fhandle->io->destroy(fhandle->io);
+    return -1;
+} /* iso_file_open_foreign */
+
+
+static PHYSFS_Io *ISO9660_openRead(PHYSFS_Dir *opaque, const char *filename,
+                                   int *exists)
+{
+    PHYSFS_Io *retval = NULL;
+    ISO9660Handle *handle = (ISO9660Handle*) opaque;
+    ISO9660FileHandle *fhandle;
+    ISO9660FileDescriptor descriptor;
+    int rc;
+
+    fhandle = allocator.Malloc(sizeof(ISO9660FileHandle));
+    BAIL_IF_MACRO(fhandle == 0, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
+    fhandle->cacheddata = 0;
+
+    retval = allocator.Malloc(sizeof(PHYSFS_Io));
+    GOTO_IF_MACRO(retval == 0, PHYSFS_ERR_OUT_OF_MEMORY, errorhandling);
+
+    /* find file descriptor */
+    rc = iso_find_dir_entry(handle, filename, &descriptor, exists);
+    GOTO_IF_MACRO(rc, ERRPASS, errorhandling);
+    GOTO_IF_MACRO(!*exists, PHYSFS_ERR_NO_SUCH_PATH, errorhandling);
+
+    fhandle->startblock = descriptor.extentpos + descriptor.extattributelen;
+    fhandle->filesize = descriptor.datalen;
+    fhandle->currpos = 0;
+    fhandle->isohandle = handle;
+    fhandle->cacheddata = NULL;
+    fhandle->io = NULL;
+
+    if (descriptor.datalen <= ISO9660_FULLCACHEMAXSIZE)
+        rc = iso_file_open_mem(handle, fhandle);
+    else
+        rc = iso_file_open_foreign(handle, fhandle);
+    GOTO_IF_MACRO(rc, ERRPASS, errorhandling);
+
+    memcpy(retval, &ISO9660_Io, sizeof (PHYSFS_Io));
+    retval->opaque = fhandle;
+    return retval;
+
+errorhandling:
+    if (retval) allocator.Free(retval);
+    if (fhandle) allocator.Free(fhandle);
+    return NULL;
+} /* ISO9660_openRead */
+
+
+
+/*******************************************************************************
+ * Information gathering functions
+ ******************************************************************************/
+
+static void ISO9660_enumerateFiles(PHYSFS_Dir *opaque, const char *dname,
+                                   int omitSymLinks,
+                                   PHYSFS_EnumFilesCallback cb,
+                                   const char *origdir, void *callbackdata)
+{
+    ISO9660Handle *handle = (ISO9660Handle*) opaque;
+    ISO9660FileDescriptor descriptor;
+    PHYSFS_uint64 readpos;
+    PHYSFS_uint64 end_of_dir;
+    char filename[130]; /* ISO allows 31, Joliet 128 -> 128 + 2 eol bytes */
+    int version = 0;
+
+    if (*dname == '\0')
+    {
+        readpos = handle->rootdirstart;
+        end_of_dir = readpos + handle->rootdirsize;
+    } /* if */
+    else
+    {
+        printf("pfad %s\n",dname);
+        int exists = 0;
+        BAIL_IF_MACRO(iso_find_dir_entry(handle,dname, &descriptor, &exists), ERRPASS,);
+        BAIL_IF_MACRO(!exists, ERRPASS, );
+        BAIL_IF_MACRO(!descriptor.flags.directory, ERRPASS,);
+
+        readpos = descriptor.extentpos * 2048;
+        end_of_dir = readpos + descriptor.datalen;
+    } /* else */
+
+    while (1)
+    {
+        BAIL_IF_MACRO(iso_readfiledescriptor(handle, readpos, &descriptor), ERRPASS, );
+
+        /* recordlen = 0 -> no more entries or fill entry */
+        if (!descriptor.recordlen)
+        {
+            /* if we are in the last sector of the directory & it's 0 -> end */
+            if ((end_of_dir - 2048) <= (readpos -1))
+                break;  /* finished */
+
+            /* else skip to the next sector & continue; */
+            readpos = (((readpos - 1) / 2048) + 1) * 2048;
+            continue;
+        } /* if */
+
+        readpos +=  descriptor.recordlen;
+        if (descriptor.filenamelen == 1 && (descriptor.filename[0] == 0
+                || descriptor.filename[0] == 1))
+            continue; /* special ones, ignore */
+
+        strncpy(filename,descriptor.filename,descriptor.filenamelen);
+        iso_extractfilename(handle, &descriptor, filename, &version);
+        cb(callbackdata, origdir,filename);
+    } /* while */
+} /* ISO9660_enumerateFiles */
+
+
+static int ISO9660_stat(PHYSFS_Dir *opaque, const char *name, int *exists,
+                        PHYSFS_Stat *stat)
+{
+    ISO9660Handle *handle = (ISO9660Handle*) opaque;
+    ISO9660FileDescriptor descriptor;
+    ISO9660ExtAttributeRec extattr;
+    BAIL_IF_MACRO(iso_find_dir_entry(handle, name, &descriptor, exists), ERRPASS, -1);
+    if (!*exists)
+        return 0;
+
+    stat->readonly = 1;
+
+    /* try to get extended info */
+    if (descriptor.extattributelen)
+    {
+        BAIL_IF_MACRO(iso_read_ext_attributes(handle,
+                descriptor.extentpos, &extattr), ERRPASS, -1);
+        stat->createtime = iso_volume_mktime(&extattr.create_time);
+        stat->modtime = iso_volume_mktime(&extattr.mod_time);
+        stat->accesstime = iso_volume_mktime(&extattr.mod_time);
+    } /* if */
+    else
+    {
+        stat->createtime = iso_mktime(&descriptor.recordtime);
+        stat->modtime = iso_mktime(&descriptor.recordtime);
+        stat->accesstime = iso_mktime(&descriptor.recordtime);
+    } /* else */
+
+    if (descriptor.flags.directory)
+    {
+        stat->filesize = 0;
+        stat->filetype = PHYSFS_FILETYPE_DIRECTORY;
+    } /* if */
+    else
+    {
+        stat->filesize = descriptor.datalen;
+        stat->filetype = PHYSFS_FILETYPE_REGULAR;
+    } /* else */
+
+    return 1;
+} /* ISO9660_stat */
+
+
+/*******************************************************************************
+ * Not supported functions
+ ******************************************************************************/
+
+static PHYSFS_Io *ISO9660_openWrite(PHYSFS_Dir *opaque, const char *name)
+{
+    BAIL_MACRO(PHYSFS_ERR_READ_ONLY, NULL);
+} /* ISO9660_openWrite */
+
+
+static PHYSFS_Io *ISO9660_openAppend(PHYSFS_Dir *opaque, const char *name)
+{
+    BAIL_MACRO(PHYSFS_ERR_READ_ONLY, NULL);
+} /* ISO9660_openAppend */
+
+
+static int ISO9660_remove(PHYSFS_Dir *opaque, const char *name)
+{
+    BAIL_MACRO(PHYSFS_ERR_READ_ONLY, 0);
+} /* ISO9660_remove */
+
+
+static int ISO9660_mkdir(PHYSFS_Dir *opaque, const char *name)
+{
+    BAIL_MACRO(PHYSFS_ERR_READ_ONLY, 0);
+} /* ISO9660_mkdir */
+
+
+const PHYSFS_Archiver __PHYSFS_Archiver_ISO9660 =
+{
+    {
+        "ISO",
+        "ISO9660 image file",
+        "Christoph Nelles <evilazrael@evilazrael.de>",
+        "http://www.evilazrael.de/",
+    },
+    ISO9660_openArchive,        /* openArchive() method    */
+    ISO9660_enumerateFiles,     /* enumerateFiles() method */
+    ISO9660_openRead,           /* openRead() method       */
+    ISO9660_openWrite,          /* openWrite() method      */
+    ISO9660_openAppend,         /* openAppend() method     */
+    ISO9660_remove,             /* remove() method         */
+    ISO9660_mkdir,              /* mkdir() method          */
+    ISO9660_closeArchive,       /* closeArchive() method   */
+    ISO9660_stat                /* stat() method           */
+};
+
+#endif  /* defined PHYSFS_SUPPORTS_ISO9660 */
+
+/* end of archiver_iso9660.c ... */
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/misc/physfs/src/archiver_lzma.c	Sat Nov 17 20:30:32 2012 -0500
@@ -0,0 +1,701 @@
+/*
+ * LZMA support routines for PhysicsFS.
+ *
+ * Please see the file lzma.txt in the lzma/ directory.
+ *
+ *  This file was written by Dennis Schridde, with some peeking at "7zMain.c"
+ *   by Igor Pavlov.
+ */
+
+#define __PHYSICSFS_INTERNAL__
+#include "physfs_internal.h"
+
+#if PHYSFS_SUPPORTS_7Z
+
+#include "lzma/C/7zCrc.h"
+#include "lzma/C/Archive/7z/7zIn.h"
+#include "lzma/C/Archive/7z/7zExtract.h"
+
+
+/* 7z internal from 7zIn.c */
+extern int TestSignatureCandidate(Byte *testBytes);
+
+
+#ifdef _LZMA_IN_CB
+# define BUFFER_SIZE (1 << 12)
+#endif /* _LZMA_IN_CB */
+
+
+/*
+ * Carries filestream metadata through 7z
+ */
+typedef struct _FileInputStream
+{
+    ISzAlloc allocImp; /* Allocation implementation, used by 7z */
+    ISzAlloc allocTempImp; /* Temporary allocation implementation, used by 7z */
+    ISzInStream inStream; /* Input stream with read callbacks, used by 7z */
+    PHYSFS_Io *io;  /* Filehandle, used by read implementation */
+#ifdef _LZMA_IN_CB
+    Byte buffer[BUFFER_SIZE]; /* Buffer, used by read implementation */
+#endif /* _LZMA_IN_CB */
+} FileInputStream;
+
+/*
+ * In the 7z format archives are splited into blocks, those are called folders
+ * Set by LZMA_read()
+*/
+typedef struct _LZMAfolder
+{
+    PHYSFS_uint32 index; /* Index of folder in archive */
+    PHYSFS_uint32 references; /* Number of files using this block */
+    PHYSFS_uint8 *cache; /* Cached folder */
+    size_t size; /* Size of folder */
+} LZMAfolder;
+
+/*
+ * Set by LZMA_openArchive(), except folder which gets it's values
+ *  in LZMA_read()
+ */
+typedef struct _LZMAarchive
+{
+    struct _LZMAfile *files; /* Array of files, size == archive->db.Database.NumFiles */
+    LZMAfolder *folders; /* Array of folders, size == archive->db.Database.NumFolders */
+    CArchiveDatabaseEx db; /* For 7z: Database */
+    FileInputStream stream; /* For 7z: Input file incl. read and seek callbacks */
+} LZMAarchive;
+
+/* Set by LZMA_openArchive(), except offset which is set by LZMA_read() */
+typedef struct _LZMAfile
+{
+    PHYSFS_uint32 index; /* Index of file in archive */
+    LZMAarchive *archive; /* Link to corresponding archive */
+    LZMAfolder *folder; /* Link to corresponding folder */
+    CFileItem *item; /* For 7z: File info, eg. name, size */
+    size_t offset; /* Offset in folder */
+    size_t position; /* Current "virtual" position in file */
+} LZMAfile;
+
+
+/* Memory management implementations to be passed to 7z */
+
+static void *SzAllocPhysicsFS(size_t size)
+{
+    return ((size == 0) ? NULL : allocator.Malloc(size));
+} /* SzAllocPhysicsFS */
+
+
+static void SzFreePhysicsFS(void *address)
+{
+    if (address != NULL)
+        allocator.Free(address);
+} /* SzFreePhysicsFS */
+
+
+/* Filesystem implementations to be passed to 7z */
+
+#ifdef _LZMA_IN_CB
+
+/*
+ * Read implementation, to be passed to 7z
+ * WARNING: If the ISzInStream in 'object' is not contained in a valid FileInputStream this _will_ break horribly!
+ */
+SZ_RESULT SzFileReadImp(void *object, void **buffer, size_t maxReqSize,
+                        size_t *processedSize)
+{
+    FileInputStream *s = (FileInputStream *)(object - offsetof(FileInputStream, inStream)); /* HACK! */
+    PHYSFS_sint64 processedSizeLoc = 0;
+
+    if (maxReqSize > BUFFER_SIZE)
+        maxReqSize = BUFFER_SIZE;
+    processedSizeLoc = s->io->read(s->io, s->buffer, maxReqSize);
+    *buffer = s->buffer;
+    if (processedSize != NULL)
+        *processedSize = (size_t) processedSizeLoc;
+
+    return SZ_OK;
+} /* SzFileReadImp */
+
+#else
+
+/*
+ * Read implementation, to be passed to 7z
+ * WARNING: If the ISzInStream in 'object' is not contained in a valid FileInputStream this _will_ break horribly!
+ */
+SZ_RESULT SzFileReadImp(void *object, void *buffer, size_t size,
+                        size_t *processedSize)
+{
+    FileInputStream *s = (FileInputStream *)((unsigned long)object - offsetof(FileInputStream, inStream)); /* HACK! */
+    const size_t processedSizeLoc = s->io->read(s->io, buffer, size);
+    if (processedSize != NULL)
+        *processedSize = processedSizeLoc;
+    return SZ_OK;
+} /* SzFileReadImp */
+
+#endif
+
+/*
+ * Seek implementation, to be passed to 7z
+ * WARNING: If the ISzInStream in 'object' is not contained in a valid FileInputStream this _will_ break horribly!
+ */
+SZ_RESULT SzFileSeekImp(void *object, CFileSize pos)
+{
+    FileInputStream *s = (FileInputStream *)((unsigned long)object - offsetof(FileInputStream, inStream)); /* HACK! */
+    if (s->io->seek(s->io, (PHYSFS_uint64) pos))
+        return SZ_OK;
+    return SZE_FAIL;
+} /* SzFileSeekImp */
+
+
+/*
+ * Translate Microsoft FILETIME (used by 7zip) into UNIX timestamp
+ */
+static PHYSFS_sint64 lzma_filetime_to_unix_timestamp(CArchiveFileTime *ft)
+{
+    /* MS counts in nanoseconds ... */
+    const PHYSFS_uint64 FILETIME_NANOTICKS_PER_SECOND = __PHYSFS_UI64(10000000);
+    /* MS likes to count seconds since 01.01.1601 ... */
+    const PHYSFS_uint64 FILETIME_UNIX_DIFF = __PHYSFS_UI64(11644473600);
+
+    PHYSFS_uint64 filetime = ft->Low | ((PHYSFS_uint64)ft->High << 32);
+    return filetime/FILETIME_NANOTICKS_PER_SECOND - FILETIME_UNIX_DIFF;
+} /* lzma_filetime_to_unix_timestamp */
+
+
+/*
+ * Compare a file with a given name, C89 stdlib variant
+ * Used for sorting
+ */
+static int lzma_file_cmp_stdlib(const void *key, const void *object)
+{
+    const char *name = (const char *) key;
+    LZMAfile *file = (LZMAfile *) object;
+    return strcmp(name, file->item->Name);
+} /* lzma_file_cmp_posix */
+
+
+/*
+ * Compare two files with each other based on the name
+ * Used for sorting
+ */
+static int lzma_file_cmp(void *_a, size_t one, size_t two)
+{
+    LZMAfile *files = (LZMAfile *) _a;
+    return strcmp(files[one].item->Name, files[two].item->Name);
+} /* lzma_file_cmp */
+
+
+/*
+ * Swap two entries in the file array
+ */
+static void lzma_file_swap(void *_a, size_t one, size_t two)
+{
+    LZMAfile tmp;
+    LZMAfile *first = &(((LZMAfile *) _a)[one]);
+    LZMAfile *second = &(((LZMAfile *) _a)[two]);
+    memcpy(&tmp, first, sizeof (LZMAfile));
+    memcpy(first, second, sizeof (LZMAfile));
+    memcpy(second, &tmp, sizeof (LZMAfile));
+} /* lzma_file_swap */
+
+
+/*
+ * Find entry 'name' in 'archive'
+ */
+static LZMAfile * lzma_find_file(const LZMAarchive *archive, const char *name)
+{
+    LZMAfile *file = bsearch(name, archive->files, archive->db.Database.NumFiles, sizeof(*archive->files), lzma_file_cmp_stdlib); /* FIXME: Should become __PHYSFS_search!!! */
+
+    BAIL_IF_MACRO(file == NULL, PHYSFS_ERR_NO_SUCH_PATH, NULL);
+
+    return file;
+} /* lzma_find_file */
+
+
+/*
+ * Load metadata for the file at given index
+ */
+static int lzma_file_init(LZMAarchive *archive, PHYSFS_uint32 fileIndex)
+{
+    LZMAfile *file = &archive->files[fileIndex];
+    PHYSFS_uint32 folderIndex = archive->db.FileIndexToFolderIndexMap[fileIndex];
+
+    file->index = fileIndex; /* Store index into 7z array, since we sort our own. */
+    file->archive = archive;
+    file->folder = (folderIndex != (PHYSFS_uint32)-1 ? &archive->folders[folderIndex] : NULL); /* Directories don't have a folder (they contain no own data...) */
+    file->item = &archive->db.Database.Files[fileIndex]; /* Holds crucial data and is often referenced -> Store link */
+    file->position = 0;
+    file->offset = 0; /* Offset will be set by LZMA_read() */
+
+    return 1;
+} /* lzma_load_file */
+
+
+/*
+ * Load metadata for all files
+ */
+static int lzma_files_init(LZMAarchive *archive)
+{
+    PHYSFS_uint32 fileIndex = 0, numFiles = archive->db.Database.NumFiles;
+
+    for (fileIndex = 0; fileIndex < numFiles; fileIndex++ )
+    {
+        if (!lzma_file_init(archive, fileIndex))
+        {
+            return 0; /* FALSE on failure */
+        }
+    } /* for */
+
+   __PHYSFS_sort(archive->files, (size_t) numFiles, lzma_file_cmp, lzma_file_swap);
+
+    return 1;
+} /* lzma_load_files */
+
+
+/*
+ * Initialise specified archive
+ */
+static void lzma_archive_init(LZMAarchive *archive)
+{
+    memset(archive, 0, sizeof(*archive));
+
+    /* Prepare callbacks for 7z */
+    archive->stream.inStream.Read = SzFileReadImp;
+    archive->stream.inStream.Seek = SzFileSeekImp;
+
+    archive->stream.allocImp.Alloc = SzAllocPhysicsFS;
+    archive->stream.allocImp.Free = SzFreePhysicsFS;
+
+    archive->stream.allocTempImp.Alloc = SzAllocPhysicsFS;
+    archive->stream.allocTempImp.Free = SzFreePhysicsFS;
+}
+
+
+/*
+ * Deinitialise archive
+ */
+static void lzma_archive_exit(LZMAarchive *archive)
+{
+    /* Free arrays */
+    allocator.Free(archive->folders);
+    allocator.Free(archive->files);
+    allocator.Free(archive);
+}
+
+/*
+ * Wrap all 7z calls in this, so the physfs error state is set appropriately.
+ */
+static int lzma_err(SZ_RESULT rc)
+{
+    switch (rc)
+    {
+        case SZ_OK: /* Same as LZMA_RESULT_OK */
+            break;
+        case SZE_DATA_ERROR: /* Same as LZMA_RESULT_DATA_ERROR */
+            __PHYSFS_setError(PHYSFS_ERR_CORRUPT); /*!!!FIXME: was "PHYSFS_ERR_DATA_ERROR" */
+            break;
+        case SZE_OUTOFMEMORY:
+            __PHYSFS_setError(PHYSFS_ERR_OUT_OF_MEMORY);
+            break;
+        case SZE_CRC_ERROR:
+            __PHYSFS_setError(PHYSFS_ERR_CORRUPT);
+            break;
+        case SZE_NOTIMPL:
+            __PHYSFS_setError(PHYSFS_ERR_UNSUPPORTED);
+            break;
+        case SZE_FAIL:
+            __PHYSFS_setError(PHYSFS_ERR_OTHER_ERROR);  /* !!! FIXME: right? */
+            break;
+        case SZE_ARCHIVE_ERROR:
+            __PHYSFS_setError(PHYSFS_ERR_CORRUPT);  /* !!! FIXME: right? */
+            break;
+        default:
+            __PHYSFS_setError(PHYSFS_ERR_OTHER_ERROR);
+    } /* switch */
+
+    return rc;
+} /* lzma_err */
+
+
+static PHYSFS_sint64 LZMA_read(PHYSFS_Io *io, void *outBuf, PHYSFS_uint64 len)
+{
+    LZMAfile *file = (LZMAfile *) io->opaque;
+
+    size_t wantedSize = (size_t) len;
+    const size_t remainingSize = file->item->Size - file->position;
+    size_t fileSize = 0;
+
+    BAIL_IF_MACRO(wantedSize == 0, ERRPASS, 0); /* quick rejection. */
+    BAIL_IF_MACRO(remainingSize == 0, PHYSFS_ERR_PAST_EOF, 0);
+
+    if (wantedSize > remainingSize)
+        wantedSize = remainingSize;
+
+    /* Only decompress the folder if it is not already cached */
+    if (file->folder->cache == NULL)
+    {
+        const int rc = lzma_err(SzExtract(
+            &file->archive->stream.inStream, /* compressed data */
+            &file->archive->db, /* 7z's database, containing everything */
+            file->index, /* Index into database arrays */
+            /* Index of cached folder, will be changed by SzExtract */
+            &file->folder->index,
+            /* Cache for decompressed folder, allocated/freed by SzExtract */
+            &file->folder->cache,
+            /* Size of cache, will be changed by SzExtract */
+            &file->folder->size,
+            /* Offset of this file inside the cache, set by SzExtract */
+            &file->offset,
+            &fileSize, /* Size of this file */
+            &file->archive->stream.allocImp,
+            &file->archive->stream.allocTempImp));
+
+        if (rc != SZ_OK)
+            return -1;
+    } /* if */
+
+    /* Copy wanted bytes over from cache to outBuf */
+    memcpy(outBuf, (file->folder->cache + file->offset + file->position),
+            wantedSize);
+    file->position += wantedSize; /* Increase virtual position */
+
+    return wantedSize;
+} /* LZMA_read */
+
+
+static PHYSFS_sint64 LZMA_write(PHYSFS_Io *io, const void *b, PHYSFS_uint64 len)
+{
+    BAIL_MACRO(PHYSFS_ERR_READ_ONLY, -1);
+} /* LZMA_write */
+
+
+static PHYSFS_sint64 LZMA_tell(PHYSFS_Io *io)
+{
+    LZMAfile *file = (LZMAfile *) io->opaque;
+    return file->position;
+} /* LZMA_tell */
+
+
+static int LZMA_seek(PHYSFS_Io *io, PHYSFS_uint64 offset)
+{
+    LZMAfile *file = (LZMAfile *) io->opaque;
+
+    BAIL_IF_MACRO(offset > file->item->Size, PHYSFS_ERR_PAST_EOF, 0);
+
+    file->position = offset; /* We only use a virtual position... */
+
+    return 1;
+} /* LZMA_seek */
+
+
+static PHYSFS_sint64 LZMA_length(PHYSFS_Io *io)
+{
+    const LZMAfile *file = (LZMAfile *) io->opaque;
+    return (file->item->Size);
+} /* LZMA_length */
+
+
+static PHYSFS_Io *LZMA_duplicate(PHYSFS_Io *_io)
+{
+    /* !!! FIXME: this archiver needs to be reworked to allow multiple
+     * !!! FIXME:  opens before we worry about duplication. */
+    BAIL_MACRO(PHYSFS_ERR_UNSUPPORTED, NULL);
+} /* LZMA_duplicate */
+
+
+static int LZMA_flush(PHYSFS_Io *io) { return 1;  /* no write support. */ }
+
+
+static void LZMA_destroy(PHYSFS_Io *io)
+{
+    LZMAfile *file = (LZMAfile *) io->opaque;
+
+    if (file->folder != NULL)
+    {
+        /* Only decrease refcount if someone actually requested this file... Prevents from overflows and close-on-open... */
+        if (file->folder->references > 0)
+            file->folder->references--;
+        if (file->folder->references == 0)
+        {
+            /* Free the cache which might have been allocated by LZMA_read() */
+            allocator.Free(file->folder->cache);
+            file->folder->cache = NULL;
+        }
+        /* !!! FIXME: we don't free (file) or (file->folder)?! */
+    } /* if */
+} /* LZMA_destroy */
+
+
+static const PHYSFS_Io LZMA_Io =
+{
+    CURRENT_PHYSFS_IO_API_VERSION, NULL,
+    LZMA_read,
+    LZMA_write,
+    LZMA_seek,
+    LZMA_tell,
+    LZMA_length,
+    LZMA_duplicate,
+    LZMA_flush,
+    LZMA_destroy
+};
+
+
+static void *LZMA_openArchive(PHYSFS_Io *io, const char *name, int forWriting)
+{
+    PHYSFS_uint8 sig[k7zSignatureSize];
+    size_t len = 0;
+    LZMAarchive *archive = NULL;
+
+    assert(io != NULL);  /* shouldn't ever happen. */
+
+    BAIL_IF_MACRO(forWriting, PHYSFS_ERR_READ_ONLY, NULL);
+
+    if (io->read(io, sig, k7zSignatureSize) != k7zSignatureSize)
+        return 0;
+    BAIL_IF_MACRO(!TestSignatureCandidate(sig), PHYSFS_ERR_UNSUPPORTED, NULL);
+    BAIL_IF_MACRO(!io->seek(io, 0), ERRPASS, NULL);
+
+    archive = (LZMAarchive *) allocator.Malloc(sizeof (LZMAarchive));
+    BAIL_IF_MACRO(archive == NULL, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
+
+    lzma_archive_init(archive);
+    archive->stream.io = io;
+
+    CrcGenerateTable();
+    SzArDbExInit(&archive->db);
+    if (lzma_err(SzArchiveOpen(&archive->stream.inStream,
+                               &archive->db,
+                               &archive->stream.allocImp,
+                               &archive->stream.allocTempImp)) != SZ_OK)
+    {
+        SzArDbExFree(&archive->db, SzFreePhysicsFS);
+        lzma_archive_exit(archive);
+        return NULL; /* Error is set by lzma_err! */
+    } /* if */
+
+    len = archive->db.Database.NumFiles * sizeof (LZMAfile);
+    archive->files = (LZMAfile *) allocator.Malloc(len);
+    if (archive->files == NULL)
+    {
+        SzArDbExFree(&archive->db, SzFreePhysicsFS);
+        lzma_archive_exit(archive);
+        BAIL_MACRO(PHYSFS_ERR_OUT_OF_MEMORY, NULL);
+    }
+
+    /*
+     * Init with 0 so we know when a folder is already cached
+     * Values will be set by LZMA_openRead()
+     */
+    memset(archive->files, 0, len);
+
+    len = archive->db.Database.NumFolders * sizeof (LZMAfolder);
+    archive->folders = (LZMAfolder *) allocator.Malloc(len);
+    if (archive->folders == NULL)
+    {
+        SzArDbExFree(&archive->db, SzFreePhysicsFS);
+        lzma_archive_exit(archive);
+        BAIL_MACRO(PHYSFS_ERR_OUT_OF_MEMORY, NULL);
+    }
+
+    /*
+     * Init with 0 so we know when a folder is already cached
+     * Values will be set by LZMA_read()
+     */
+    memset(archive->folders, 0, len);
+
+    if(!lzma_files_init(archive))
+    {
+        SzArDbExFree(&archive->db, SzFreePhysicsFS);
+        lzma_archive_exit(archive);
+        BAIL_MACRO(PHYSFS_ERR_OTHER_ERROR, NULL);
+    }
+
+    return archive;
+} /* LZMA_openArchive */
+
+
+/*
+ * Moved to seperate function so we can use alloca then immediately throw
+ *  away the allocated stack space...
+ */
+static void doEnumCallback(PHYSFS_EnumFilesCallback cb, void *callbackdata,
+                           const char *odir, const char *str, size_t flen)
+{
+    char *newstr = __PHYSFS_smallAlloc(flen + 1);
+    if (newstr == NULL)
+        return;
+
+    memcpy(newstr, str, flen);
+    newstr[flen] = '\0';
+    cb(callbackdata, odir, newstr);
+    __PHYSFS_smallFree(newstr);
+} /* doEnumCallback */
+
+
+static void LZMA_enumerateFiles(PHYSFS_Dir *opaque, const char *dname,
+                                int omitSymLinks, PHYSFS_EnumFilesCallback cb,
+                                const char *origdir, void *callbackdata)
+{
+    size_t dlen = strlen(dname),
+           dlen_inc = dlen + ((dlen > 0) ? 1 : 0);
+    LZMAarchive *archive = (LZMAarchive *) opaque;
+    LZMAfile *file = NULL,
+            *lastFile = &archive->files[archive->db.Database.NumFiles];
+        if (dlen)
+        {
+            file = lzma_find_file(archive, dname);
+            if (file != NULL) /* if 'file' is NULL it should stay so, otherwise errors will not be handled */
+                file += 1;
+        }
+        else
+        {
+            file = archive->files;
+        }
+
+    BAIL_IF_MACRO(file == NULL, PHYSFS_ERR_NO_SUCH_PATH, );
+
+    while (file < lastFile)
+    {
+        const char * fname = file->item->Name;
+        const char * dirNameEnd = fname + dlen_inc;
+
+        if (strncmp(dname, fname, dlen) != 0) /* Stop after mismatch, archive->files is sorted */
+            break;
+
+        if (strchr(dirNameEnd, '/')) /* Skip subdirs */
+        {
+            file++;
+            continue;
+        }
+
+        /* Do the actual callback... */
+        doEnumCallback(cb, callbackdata, origdir, dirNameEnd, strlen(dirNameEnd));
+
+        file++;
+    }
+} /* LZMA_enumerateFiles */
+
+
+static PHYSFS_Io *LZMA_openRead(PHYSFS_Dir *opaque, const char *name,
+                                int *fileExists)
+{
+    LZMAarchive *archive = (LZMAarchive *) opaque;
+    LZMAfile *file = lzma_find_file(archive, name);
+    PHYSFS_Io *io = NULL;
+
+    *fileExists = (file != NULL);
+    BAIL_IF_MACRO(file == NULL, PHYSFS_ERR_NO_SUCH_PATH, NULL);
+    BAIL_IF_MACRO(file->folder == NULL, PHYSFS_ERR_NOT_A_FILE, NULL);
+
+    file->position = 0;
+    file->folder->references++; /* Increase refcount for automatic cleanup... */
+
+    io = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
+    BAIL_IF_MACRO(io == NULL, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
+    memcpy(io, &LZMA_Io, sizeof (*io));
+    io->opaque = file;
+
+    return io;
+} /* LZMA_openRead */
+
+
+static PHYSFS_Io *LZMA_openWrite(PHYSFS_Dir *opaque, const char *filename)
+{
+    BAIL_MACRO(PHYSFS_ERR_READ_ONLY, NULL);
+} /* LZMA_openWrite */
+
+
+static PHYSFS_Io *LZMA_openAppend(PHYSFS_Dir *opaque, const char *filename)
+{
+    BAIL_MACRO(PHYSFS_ERR_READ_ONLY, NULL);
+} /* LZMA_openAppend */
+
+
+static void LZMA_closeArchive(PHYSFS_Dir *opaque)
+{
+    LZMAarchive *archive = (LZMAarchive *) opaque;
+
+#if 0  /* !!! FIXME: you shouldn't have to do this. */
+    PHYSFS_uint32 fileIndex = 0, numFiles = archive->db.Database.NumFiles;
+    for (fileIndex = 0; fileIndex < numFiles; fileIndex++)
+    {
+        LZMA_fileClose(&archive->files[fileIndex]);
+    } /* for */
+#endif
+
+    SzArDbExFree(&archive->db, SzFreePhysicsFS);
+    archive->stream.io->destroy(archive->stream.io);
+    lzma_archive_exit(archive);
+} /* LZMA_closeArchive */
+
+
+static int LZMA_remove(PHYSFS_Dir *opaque, const char *name)
+{
+    BAIL_MACRO(PHYSFS_ERR_READ_ONLY, 0);
+} /* LZMA_remove */
+
+
+static int LZMA_mkdir(PHYSFS_Dir *opaque, const char *name)
+{
+    BAIL_MACRO(PHYSFS_ERR_READ_ONLY, 0);
+} /* LZMA_mkdir */
+
+static int LZMA_stat(PHYSFS_Dir *opaque, const char *filename,
+                     int *exists, PHYSFS_Stat *stat)
+{
+    const LZMAarchive *archive = (const LZMAarchive *) opaque;
+    const LZMAfile *file = lzma_find_file(archive, filename);
+
+    *exists = (file != 0);
+    if (!file)
+        return 0;
+
+    if(file->item->IsDirectory)
+    {
+        stat->filesize = 0;
+        stat->filetype = PHYSFS_FILETYPE_DIRECTORY;
+    } /* if */
+    else
+    {
+        stat->filesize = (PHYSFS_sint64) file->item->Size;
+        stat->filetype = PHYSFS_FILETYPE_REGULAR;
+    } /* else */
+
+    /* !!! FIXME: the 0's should be -1's? */
+    if (file->item->IsLastWriteTimeDefined)
+        stat->modtime = lzma_filetime_to_unix_timestamp(&file->item->LastWriteTime);
+    else
+        stat->modtime = 0;
+
+    /* real create and accesstype are currently not in the lzma SDK */
+    stat->createtime = stat->modtime;
+    stat->accesstime = 0;
+
+    stat->readonly = 1;  /* 7zips are always read only */
+
+    return 1;
+} /* LZMA_stat */
+
+
+const PHYSFS_Archiver __PHYSFS_Archiver_LZMA =
+{
+    {
+        "7Z",
+        "LZMA (7zip) format",
+        "Dennis Schridde <devurandom@gmx.net>",
+        "http://icculus.org/physfs/",
+    },
+    LZMA_openArchive,        /* openArchive() method    */
+    LZMA_enumerateFiles,     /* enumerateFiles() method */
+    LZMA_openRead,           /* openRead() method       */
+    LZMA_openWrite,          /* openWrite() method      */
+    LZMA_openAppend,         /* openAppend() method     */
+    LZMA_remove,             /* remove() method         */
+    LZMA_mkdir,              /* mkdir() method          */
+    LZMA_closeArchive,       /* closeArchive() method   */
+    LZMA_stat                /* stat() method           */
+};
+
+#endif  /* defined PHYSFS_SUPPORTS_7Z */
+
+/* end of lzma.c ... */
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/misc/physfs/src/archiver_mvl.c	Sat Nov 17 20:30:32 2012 -0500
@@ -0,0 +1,103 @@
+/*
+ * MVL support routines for PhysicsFS.
+ *
+ * This driver handles Descent II Movielib archives.
+ *
+ * The file format of MVL is quite easy...
+ *
+ *   //MVL File format - Written by Heiko Herrmann
+ *   char sig[4] = {'D','M', 'V', 'L'}; // "DMVL"=Descent MoVie Library
+ *
+ *   int num_files; // the number of files in this MVL
+ *
+ *   struct {
+ *    char file_name[13]; // Filename, padded to 13 bytes with 0s
+ *    int file_size; // filesize in bytes
+ *   }DIR_STRUCT[num_files];
+ *
+ *   struct {
+ *    char data[file_size]; // The file data
+ *   }FILE_STRUCT[num_files];
+ *
+ * (That info is from http://www.descent2.com/ddn/specs/mvl/)
+ *
+ * Please see the file LICENSE.txt in the source's root directory.
+ *
+ *  This file written by Bradley Bell.
+ *  Based on grp.c by Ryan C. Gordon.
+ */
+
+#define __PHYSICSFS_INTERNAL__
+#include "physfs_internal.h"
+
+#if PHYSFS_SUPPORTS_MVL
+
+static UNPKentry *mvlLoadEntries(PHYSFS_Io *io, PHYSFS_uint32 fileCount)
+{
+    PHYSFS_uint32 location = 8;  /* sizeof sig. */
+    UNPKentry *entries = NULL;
+    UNPKentry *entry = NULL;
+
+    entries = (UNPKentry *) allocator.Malloc(sizeof (UNPKentry) * fileCount);
+    BAIL_IF_MACRO(entries == NULL, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
+
+    location += (17 * fileCount);
+
+    for (entry = entries; fileCount > 0; fileCount--, entry++)
+    {
+        if (!__PHYSFS_readAll(io, &entry->name, 13)) goto failed;
+        if (!__PHYSFS_readAll(io, &entry->size, 4)) goto failed;
+        entry->size = PHYSFS_swapULE32(entry->size);
+        entry->startPos = location;
+        location += entry->size;
+    } /* for */
+
+    return entries;
+
+failed:
+    allocator.Free(entries);
+    return NULL;
+} /* mvlLoadEntries */
+
+
+static void *MVL_openArchive(PHYSFS_Io *io, const char *name, int forWriting)
+{
+    PHYSFS_uint8 buf[4];
+    PHYSFS_uint32 count = 0;
+    UNPKentry *entries = NULL;
+
+    assert(io != NULL);  /* shouldn't ever happen. */
+    BAIL_IF_MACRO(forWriting, PHYSFS_ERR_READ_ONLY, NULL);
+    BAIL_IF_MACRO(!__PHYSFS_readAll(io, buf, 4), ERRPASS, NULL);
+    BAIL_IF_MACRO(memcmp(buf, "DMVL", 4) != 0, PHYSFS_ERR_UNSUPPORTED, NULL);
+    BAIL_IF_MACRO(!__PHYSFS_readAll(io, &count, sizeof(count)), ERRPASS, NULL);
+
+    count = PHYSFS_swapULE32(count);
+    entries = mvlLoadEntries(io, count);
+    return (!entries) ? NULL : UNPK_openArchive(io, entries, count);
+} /* MVL_openArchive */
+
+
+const PHYSFS_Archiver __PHYSFS_Archiver_MVL =
+{
+    {
+        "MVL",
+        "Descent II Movielib format",
+        "Bradley Bell <btb@icculus.org>",
+        "http://icculus.org/physfs/",
+    },
+    MVL_openArchive,        /* openArchive() method    */
+    UNPK_enumerateFiles,     /* enumerateFiles() method */
+    UNPK_openRead,           /* openRead() method       */
+    UNPK_openWrite,          /* openWrite() method      */
+    UNPK_openAppend,         /* openAppend() method     */
+    UNPK_remove,             /* remove() method         */
+    UNPK_mkdir,              /* mkdir() method          */
+    UNPK_closeArchive,       /* closeArchive() method   */
+    UNPK_stat                /* stat() method           */
+};
+
+#endif  /* defined PHYSFS_SUPPORTS_MVL */
+
+/* end of mvl.c ... */
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/misc/physfs/src/archiver_qpak.c	Sat Nov 17 20:30:32 2012 -0500
@@ -0,0 +1,119 @@
+/*
+ * QPAK support routines for PhysicsFS.
+ *
+ *  This archiver handles the archive format utilized by Quake 1 and 2.
+ *  Quake3-based games use the PkZip/Info-Zip format (which our zip.c
+ *  archiver handles).
+ *
+ *  ========================================================================
+ *
+ *  This format info (in more detail) comes from:
+ *     http://debian.fmi.uni-sofia.bg/~sergei/cgsr/docs/pak.txt
+ *
+ *  Quake PAK Format
+ *
+ *  Header
+ *   (4 bytes)  signature = 'PACK'
+ *   (4 bytes)  directory offset
+ *   (4 bytes)  directory length
+ *
+ *  Directory
+ *   (56 bytes) file name
+ *   (4 bytes)  file position
+ *   (4 bytes)  file length
+ *
+ *  ========================================================================
+ *
+ * Please see the file LICENSE.txt in the source's root directory.
+ *
+ *  This file written by Ryan C. Gordon.
+ */
+
+#define __PHYSICSFS_INTERNAL__
+#include "physfs_internal.h"
+
+#if PHYSFS_SUPPORTS_QPAK
+
+#define QPAK_SIG 0x4B434150   /* "PACK" in ASCII. */
+
+static UNPKentry *qpakLoadEntries(PHYSFS_Io *io, PHYSFS_uint32 fileCount)
+{
+    UNPKentry *entries = NULL;
+    UNPKentry *entry = NULL;
+
+    entries = (UNPKentry *) allocator.Malloc(sizeof (UNPKentry) * fileCount);
+    BAIL_IF_MACRO(entries == NULL, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
+
+    for (entry = entries; fileCount > 0; fileCount--, entry++)
+    {
+        if (!__PHYSFS_readAll(io, &entry->name, 56)) goto failed;
+        if (!__PHYSFS_readAll(io, &entry->startPos, 4)) goto failed;
+        if (!__PHYSFS_readAll(io, &entry->size, 4)) goto failed;
+        entry->size = PHYSFS_swapULE32(entry->size);
+        entry->startPos = PHYSFS_swapULE32(entry->startPos);
+    } /* for */
+
+    return entries;
+
+failed:
+    allocator.Free(entries);
+    return NULL;
+} /* qpakLoadEntries */
+
+
+static void *QPAK_openArchive(PHYSFS_Io *io, const char *name, int forWriting)
+{
+    UNPKentry *entries = NULL;
+    PHYSFS_uint32 val = 0;
+    PHYSFS_uint32 pos = 0;
+    PHYSFS_uint32 count = 0;
+
+    assert(io != NULL);  /* shouldn't ever happen. */
+
+    BAIL_IF_MACRO(forWriting, PHYSFS_ERR_READ_ONLY, NULL);
+
+    BAIL_IF_MACRO(!__PHYSFS_readAll(io, &val, 4), ERRPASS, NULL);
+    if (PHYSFS_swapULE32(val) != QPAK_SIG)
+        BAIL_MACRO(PHYSFS_ERR_UNSUPPORTED, NULL);
+
+    BAIL_IF_MACRO(!__PHYSFS_readAll(io, &val, 4), ERRPASS, NULL);
+    pos = PHYSFS_swapULE32(val);  /* directory table offset. */
+
+    BAIL_IF_MACRO(!__PHYSFS_readAll(io, &val, 4), ERRPASS, NULL);
+    count = PHYSFS_swapULE32(val);
+
+    /* corrupted archive? */
+    BAIL_IF_MACRO((count % 64) != 0, PHYSFS_ERR_CORRUPT, NULL);
+    count /= 64;
+
+    BAIL_IF_MACRO(!io->seek(io, pos), ERRPASS, NULL);
+
+    entries = qpakLoadEntries(io, count);
+    BAIL_IF_MACRO(!entries, ERRPASS, NULL);
+    return UNPK_openArchive(io, entries, count);
+} /* QPAK_openArchive */
+
+
+const PHYSFS_Archiver __PHYSFS_Archiver_QPAK =
+{
+    {
+        "PAK",
+        "Quake I/II format",
+        "Ryan C. Gordon <icculus@icculus.org>",
+        "http://icculus.org/physfs/",
+    },
+    QPAK_openArchive,       /* openArchive() method    */
+    UNPK_enumerateFiles,    /* enumerateFiles() method */
+    UNPK_openRead,          /* openRead() method       */
+    UNPK_openWrite,         /* openWrite() method      */
+    UNPK_openAppend,        /* openAppend() method     */
+    UNPK_remove,            /* remove() method         */
+    UNPK_mkdir,             /* mkdir() method          */
+    UNPK_closeArchive,       /* closeArchive() method   */
+    UNPK_stat               /* stat() method           */
+};
+
+#endif  /* defined PHYSFS_SUPPORTS_QPAK */
+
+/* end of qpak.c ... */
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/misc/physfs/src/archiver_unpacked.c	Sat Nov 17 20:30:32 2012 -0500
@@ -0,0 +1,470 @@
+/*
+ * High-level PhysicsFS archiver for simple unpacked file formats.
+ *
+ * This is a framework that basic archivers build on top of. It's for simple
+ *  formats that can just hand back a list of files and the offsets of their
+ *  uncompressed data. There are an alarming number of formats like this.
+ *
+ * RULES: Archive entries must be uncompressed, must not have separate subdir
+ *  entries (but can have subdirs), must be case insensitive LOW ASCII
+ *  filenames <= 56 bytes. No symlinks, etc. We can relax some of these rules
+ *  as necessary.
+ *
+ * Please see the file LICENSE.txt in the source's root directory.
+ *
+ *  This file written by Ryan C. Gordon.
+ */
+
+#define __PHYSICSFS_INTERNAL__
+#include "physfs_internal.h"
+
+typedef struct
+{
+    PHYSFS_Io *io;
+    PHYSFS_uint32 entryCount;
+    UNPKentry *entries;
+} UNPKinfo;
+
+
+typedef struct
+{
+    PHYSFS_Io *io;
+    UNPKentry *entry;
+    PHYSFS_uint32 curPos;
+} UNPKfileinfo;
+
+
+void UNPK_closeArchive(PHYSFS_Dir *opaque)
+{
+    UNPKinfo *info = ((UNPKinfo *) opaque);
+    info->io->destroy(info->io);
+    allocator.Free(info->entries);
+    allocator.Free(info);
+} /* UNPK_closeArchive */
+
+
+static PHYSFS_sint64 UNPK_read(PHYSFS_Io *io, void *buffer, PHYSFS_uint64 len)
+{
+    UNPKfileinfo *finfo = (UNPKfileinfo *) io->opaque;
+    const UNPKentry *entry = finfo->entry;
+    const PHYSFS_uint64 bytesLeft = (PHYSFS_uint64)(entry->size-finfo->curPos);
+    PHYSFS_sint64 rc;
+
+    if (bytesLeft < len)
+        len = bytesLeft;
+
+    rc = finfo->io->read(finfo->io, buffer, len);
+    if (rc > 0)
+        finfo->curPos += (PHYSFS_uint32) rc;
+
+    return rc;
+} /* UNPK_read */
+
+
+static PHYSFS_sint64 UNPK_write(PHYSFS_Io *io, const void *b, PHYSFS_uint64 len)
+{
+    BAIL_MACRO(PHYSFS_ERR_READ_ONLY, -1);
+} /* UNPK_write */
+
+
+static PHYSFS_sint64 UNPK_tell(PHYSFS_Io *io)
+{
+    return ((UNPKfileinfo *) io->opaque)->curPos;
+} /* UNPK_tell */
+
+
+static int UNPK_seek(PHYSFS_Io *io, PHYSFS_uint64 offset)
+{
+    UNPKfileinfo *finfo = (UNPKfileinfo *) io->opaque;
+    const UNPKentry *entry = finfo->entry;
+    int rc;
+
+    BAIL_IF_MACRO(offset >= entry->size, PHYSFS_ERR_PAST_EOF, 0);
+    rc = finfo->io->seek(finfo->io, entry->startPos + offset);
+    if (rc)
+        finfo->curPos = (PHYSFS_uint32) offset;
+
+    return rc;
+} /* UNPK_seek */
+
+
+static PHYSFS_sint64 UNPK_length(PHYSFS_Io *io)
+{
+    const UNPKfileinfo *finfo = (UNPKfileinfo *) io->opaque;
+    return ((PHYSFS_sint64) finfo->entry->size);
+} /* UNPK_length */
+
+
+static PHYSFS_Io *UNPK_duplicate(PHYSFS_Io *_io)
+{
+    UNPKfileinfo *origfinfo = (UNPKfileinfo *) _io->opaque;
+    PHYSFS_Io *io = NULL;
+    PHYSFS_Io *retval = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
+    UNPKfileinfo *finfo = (UNPKfileinfo *) allocator.Malloc(sizeof (UNPKfileinfo));
+    GOTO_IF_MACRO(!retval, PHYSFS_ERR_OUT_OF_MEMORY, UNPK_duplicate_failed);
+    GOTO_IF_MACRO(!finfo, PHYSFS_ERR_OUT_OF_MEMORY, UNPK_duplicate_failed);
+
+    io = origfinfo->io->duplicate(origfinfo->io);
+    if (!io) goto UNPK_duplicate_failed;
+    finfo->io = io;
+    finfo->entry = origfinfo->entry;
+    finfo->curPos = 0;
+    memcpy(retval, _io, sizeof (PHYSFS_Io));
+    retval->opaque = finfo;
+    return retval;
+
+UNPK_duplicate_failed:
+    if (finfo != NULL) allocator.Free(finfo);
+    if (retval != NULL) allocator.Free(retval);
+    if (io != NULL) io->destroy(io);
+    return NULL;
+} /* UNPK_duplicate */
+
+static int UNPK_flush(PHYSFS_Io *io) { return 1;  /* no write support. */ }
+
+static void UNPK_destroy(PHYSFS_Io *io)
+{
+    UNPKfileinfo *finfo = (UNPKfileinfo *) io->opaque;
+    finfo->io->destroy(finfo->io);
+    allocator.Free(finfo);
+    allocator.Free(io);
+} /* UNPK_destroy */
+
+
+static const PHYSFS_Io UNPK_Io =
+{
+    CURRENT_PHYSFS_IO_API_VERSION, NULL,
+    UNPK_read,
+    UNPK_write,
+    UNPK_seek,
+    UNPK_tell,
+    UNPK_length,
+    UNPK_duplicate,
+    UNPK_flush,
+    UNPK_destroy
+};
+
+
+static int entryCmp(void *_a, size_t one, size_t two)
+{
+    if (one != two)
+    {
+        const UNPKentry *a = (const UNPKentry *) _a;
+        return __PHYSFS_stricmpASCII(a[one].name, a[two].name);
+    } /* if */
+
+    return 0;
+} /* entryCmp */
+
+
+static void entrySwap(void *_a, size_t one, size_t two)
+{
+    if (one != two)
+    {
+        UNPKentry tmp;
+        UNPKentry *first = &(((UNPKentry *) _a)[one]);
+        UNPKentry *second = &(((UNPKentry *) _a)[two]);
+        memcpy(&tmp, first, sizeof (UNPKentry));
+        memcpy(first, second, sizeof (UNPKentry));
+        memcpy(second, &tmp, sizeof (UNPKentry));
+    } /* if */
+} /* entrySwap */
+
+
+static PHYSFS_sint32 findStartOfDir(UNPKinfo *info, const char *path,
+                                    int stop_on_first_find)
+{
+    PHYSFS_sint32 lo = 0;
+    PHYSFS_sint32 hi = (PHYSFS_sint32) (info->entryCount - 1);
+    PHYSFS_sint32 middle;
+    PHYSFS_uint32 dlen = (PHYSFS_uint32) strlen(path);
+    PHYSFS_sint32 retval = -1;
+    const char *name;
+    int rc;
+
+    if (*path == '\0')  /* root dir? */
+        return 0;
+
+    if ((dlen > 0) && (path[dlen - 1] == '/')) /* ignore trailing slash. */
+        dlen--;
+
+    while (lo <= hi)
+    {
+        middle = lo + ((hi - lo) / 2);
+        name = info->entries[middle].name;
+        rc = __PHYSFS_strnicmpASCII(path, name, dlen);
+        if (rc == 0)
+        {
+            char ch = name[dlen];
+            if (ch < '/') /* make sure this isn't just a substr match. */
+                rc = -1;
+            else if (ch > '/')
+                rc = 1;
+            else 
+            {
+                if (stop_on_first_find) /* Just checking dir's existance? */
+                    return middle;
+
+                if (name[dlen + 1] == '\0') /* Skip initial dir entry. */
+                    return (middle + 1);
+
+                /* there might be more entries earlier in the list. */
+                retval = middle;
+                hi = middle - 1;
+            } /* else */
+        } /* if */
+
+        if (rc > 0)
+            lo = middle + 1;
+        else
+            hi = middle - 1;
+    } /* while */
+
+    return retval;
+} /* findStartOfDir */
+
+
+/*
+ * Moved to seperate function so we can use alloca then immediately throw
+ *  away the allocated stack space...
+ */
+static void doEnumCallback(PHYSFS_EnumFilesCallback cb, void *callbackdata,
+                           const char *odir, const char *str, PHYSFS_sint32 ln)
+{
+    char *newstr = __PHYSFS_smallAlloc(ln + 1);
+    if (newstr == NULL)
+        return;
+
+    memcpy(newstr, str, ln);
+    newstr[ln] = '\0';
+    cb(callbackdata, odir, newstr);
+    __PHYSFS_smallFree(newstr);
+} /* doEnumCallback */
+
+
+void UNPK_enumerateFiles(PHYSFS_Dir *opaque, const char *dname,
+                         int omitSymLinks, PHYSFS_EnumFilesCallback cb,
+                         const char *origdir, void *callbackdata)
+{
+    UNPKinfo *info = ((UNPKinfo *) opaque);
+    PHYSFS_sint32 dlen, dlen_inc, max, i;
+
+    i = findStartOfDir(info, dname, 0);
+    if (i == -1)  /* no such directory. */
+        return;
+
+    dlen = (PHYSFS_sint32) strlen(dname);
+    if ((dlen > 0) && (dname[dlen - 1] == '/')) /* ignore trailing slash. */
+        dlen--;
+
+    dlen_inc = ((dlen > 0) ? 1 : 0) + dlen;
+    max = (PHYSFS_sint32) info->entryCount;
+    while (i < max)
+    {
+        char *add;
+        char *ptr;
+        PHYSFS_sint32 ln;
+        char *e = info->entries[i].name;
+        if ((dlen) &&
+            ((__PHYSFS_strnicmpASCII(e, dname, dlen)) || (e[dlen] != '/')))
+        {
+            break;  /* past end of this dir; we're done. */
+        } /* if */
+
+        add = e + dlen_inc;
+        ptr = strchr(add, '/');
+        ln = (PHYSFS_sint32) ((ptr) ? ptr-add : strlen(add));
+        doEnumCallback(cb, callbackdata, origdir, add, ln);
+        ln += dlen_inc;  /* point past entry to children... */
+
+        /* increment counter and skip children of subdirs... */
+        while ((++i < max) && (ptr != NULL))
+        {
+            char *e_new = info->entries[i].name;
+            if ((__PHYSFS_strnicmpASCII(e, e_new, ln) != 0) ||
+                (e_new[ln] != '/'))
+            {
+                break;
+            } /* if */
+        } /* while */
+    } /* while */
+} /* UNPK_enumerateFiles */
+
+
+/*
+ * This will find the UNPKentry associated with a path in platform-independent
+ *  notation. Directories don't have UNPKentries associated with them, but 
+ *  (*isDir) will be set to non-zero if a dir was hit.
+ */
+static UNPKentry *findEntry(const UNPKinfo *info, const char *path, int *isDir)
+{
+    UNPKentry *a = info->entries;
+    PHYSFS_sint32 pathlen = (PHYSFS_sint32) strlen(path);
+    PHYSFS_sint32 lo = 0;
+    PHYSFS_sint32 hi = (PHYSFS_sint32) (info->entryCount - 1);
+    PHYSFS_sint32 middle;
+    const char *thispath = NULL;
+    int rc;
+
+    while (lo <= hi)
+    {
+        middle = lo + ((hi - lo) / 2);
+        thispath = a[middle].name;
+        rc = __PHYSFS_strnicmpASCII(path, thispath, pathlen);
+
+        if (rc > 0)
+            lo = middle + 1;
+
+        else if (rc < 0)
+            hi = middle - 1;
+
+        else /* substring match...might be dir or entry or nothing. */
+        {
+            if (isDir != NULL)
+            {
+                *isDir = (thispath[pathlen] == '/');
+                if (*isDir)
+                    return NULL;
+            } /* if */
+
+            if (thispath[pathlen] == '\0') /* found entry? */
+                return &a[middle];
+            /* adjust search params, try again. */
+            else if (thispath[pathlen] > '/')
+                hi = middle - 1;
+            else
+                lo = middle + 1;
+        } /* if */
+    } /* while */
+
+    if (isDir != NULL)
+        *isDir = 0;
+
+    BAIL_MACRO(PHYSFS_ERR_NO_SUCH_PATH, NULL);
+} /* findEntry */
+
+
+PHYSFS_Io *UNPK_openRead(PHYSFS_Dir *opaque, const char *fnm, int *fileExists)
+{
+    PHYSFS_Io *retval = NULL;
+    UNPKinfo *info = (UNPKinfo *) opaque;
+    UNPKfileinfo *finfo = NULL;
+    int isdir = 0;
+    UNPKentry *entry = findEntry(info, fnm, &isdir);
+
+    *fileExists = (entry != NULL);
+    GOTO_IF_MACRO(isdir, PHYSFS_ERR_NOT_A_FILE, UNPK_openRead_failed);
+    GOTO_IF_MACRO(!entry, ERRPASS, UNPK_openRead_failed);
+
+    retval = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
+    GOTO_IF_MACRO(!retval, PHYSFS_ERR_OUT_OF_MEMORY, UNPK_openRead_failed);
+
+    finfo = (UNPKfileinfo *) allocator.Malloc(sizeof (UNPKfileinfo));
+    GOTO_IF_MACRO(!finfo, PHYSFS_ERR_OUT_OF_MEMORY, UNPK_openRead_failed);
+
+    finfo->io = info->io->duplicate(info->io);
+    GOTO_IF_MACRO(!finfo->io, ERRPASS, UNPK_openRead_failed);
+
+    if (!finfo->io->seek(finfo->io, entry->startPos))
+        goto UNPK_openRead_failed;
+
+    finfo->curPos = 0;
+    finfo->entry = entry;
+
+    memcpy(retval, &UNPK_Io, sizeof (*retval));
+    retval->opaque = finfo;
+    return retval;
+
+UNPK_openRead_failed:
+    if (finfo != NULL)
+    {
+        if (finfo->io != NULL)
+            finfo->io->destroy(finfo->io);
+        allocator.Free(finfo);
+    } /* if */
+
+    if (retval != NULL)
+        allocator.Free(retval);
+
+    return NULL;
+} /* UNPK_openRead */
+
+
+PHYSFS_Io *UNPK_openWrite(PHYSFS_Dir *opaque, const char *name)
+{
+    BAIL_MACRO(PHYSFS_ERR_READ_ONLY, NULL);
+} /* UNPK_openWrite */
+
+
+PHYSFS_Io *UNPK_openAppend(PHYSFS_Dir *opaque, const char *name)
+{
+    BAIL_MACRO(PHYSFS_ERR_READ_ONLY, NULL);
+} /* UNPK_openAppend */
+
+
+int UNPK_remove(PHYSFS_Dir *opaque, const char *name)
+{
+    BAIL_MACRO(PHYSFS_ERR_READ_ONLY, 0);
+} /* UNPK_remove */
+
+
+int UNPK_mkdir(PHYSFS_Dir *opaque, const char *name)
+{
+    BAIL_MACRO(PHYSFS_ERR_READ_ONLY, 0);
+} /* UNPK_mkdir */
+
+
+int UNPK_stat(PHYSFS_Dir *opaque, const char *filename,
+              int *exists, PHYSFS_Stat *stat)
+{
+    int isDir = 0;
+    const UNPKinfo *info = (const UNPKinfo *) opaque;
+    const UNPKentry *entry = findEntry(info, filename, &isDir);
+
+    if (isDir)
+    {
+        *exists = 1;
+        stat->filetype = PHYSFS_FILETYPE_DIRECTORY;
+        stat->filesize = 0;
+    } /* if */
+    else if (entry != NULL)
+    {
+        *exists = 1;
+        stat->filetype = PHYSFS_FILETYPE_REGULAR;
+        stat->filesize = entry->size;
+    } /* else if */
+    else
+    {
+        *exists = 0;
+        return 0;
+    } /* else */
+
+    stat->modtime = -1;
+    stat->createtime = -1;
+    stat->accesstime = -1;
+    stat->readonly = 1;
+
+    return 1;
+} /* UNPK_stat */
+
+
+PHYSFS_Dir *UNPK_openArchive(PHYSFS_Io *io, UNPKentry *e,
+                             const PHYSFS_uint32 num)
+{
+    UNPKinfo *info = (UNPKinfo *) allocator.Malloc(sizeof (UNPKinfo));
+    if (info == NULL)
+    {
+        allocator.Free(e);
+        BAIL_MACRO(PHYSFS_ERR_OUT_OF_MEMORY, NULL);
+    } /* if */
+
+    __PHYSFS_sort(e, (size_t) num, entryCmp, entrySwap);
+    info->io = io;
+    info->entryCount = num;
+    info->entries = e;
+
+    return info;
+} /* UNPK_openArchive */
+
+/* end of archiver_unpacked.c ... */
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/misc/physfs/src/archiver_wad.c	Sat Nov 17 20:30:32 2012 -0500
@@ -0,0 +1,127 @@
+/*
+ * WAD support routines for PhysicsFS.
+ *
+ * This driver handles DOOM engine archives ("wads"). 
+ * This format (but not this driver) was designed by id Software for use
+ *  with the DOOM engine.
+ * The specs of the format are from the unofficial doom specs v1.666
+ * found here: http://www.gamers.org/dhs/helpdocs/dmsp1666.html
+ * The format of the archive: (from the specs)
+ *
+ *  A WAD file has three parts:
+ *  (1) a twelve-byte header
+ *  (2) one or more "lumps"
+ *  (3) a directory or "info table" that contains the names, offsets, and
+ *      sizes of all the lumps in the WAD
+ *
+ *  The header consists of three four-byte parts:
+ *    (a) an ASCII string which must be either "IWAD" or "PWAD"
+ *    (b) a 4-byte (long) integer which is the number of lumps in the wad
+ *    (c) a long integer which is the file offset to the start of
+ *    the directory
+ *
+ *  The directory has one 16-byte entry for every lump. Each entry consists
+ *  of three parts:
+ *
+ *    (a) a long integer, the file offset to the start of the lump
+ *    (b) a long integer, the size of the lump in bytes
+ *    (c) an 8-byte ASCII string, the name of the lump, padded with zeros.
+ *        For example, the "DEMO1" entry in hexadecimal would be
+ *        (44 45 4D 4F 31 00 00 00)
+ * 
+ * Note that there is no way to tell if an opened WAD archive is a
+ *  IWAD or PWAD with this archiver.
+ * I couldn't think of a way to provide that information, without being too
+ *  hacky.
+ * I don't think it's really that important though.
+ *
+ *
+ * Please see the file LICENSE.txt in the source's root directory.
+ *
+ * This file written by Travis Wells, based on the GRP archiver by
+ *  Ryan C. Gordon.
+ */
+
+#define __PHYSICSFS_INTERNAL__
+#include "physfs_internal.h"
+
+#if PHYSFS_SUPPORTS_WAD
+
+static UNPKentry *wadLoadEntries(PHYSFS_Io *io, PHYSFS_uint32 fileCount)
+{
+    PHYSFS_uint32 directoryOffset;
+    UNPKentry *entries = NULL;
+    UNPKentry *entry = NULL;
+
+    BAIL_IF_MACRO(!__PHYSFS_readAll(io, &directoryOffset, 4), ERRPASS, 0);
+    directoryOffset = PHYSFS_swapULE32(directoryOffset);
+
+    BAIL_IF_MACRO(!io->seek(io, directoryOffset), ERRPASS, 0);
+
+    entries = (UNPKentry *) allocator.Malloc(sizeof (UNPKentry) * fileCount);
+    BAIL_IF_MACRO(!entries, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
+
+    for (entry = entries; fileCount > 0; fileCount--, entry++)
+    {
+        if (!__PHYSFS_readAll(io, &entry->startPos, 4)) goto failed;
+        if (!__PHYSFS_readAll(io, &entry->size, 4)) goto failed;
+        if (!__PHYSFS_readAll(io, &entry->name, 8)) goto failed;
+
+        entry->name[8] = '\0'; /* name might not be null-terminated in file. */
+        entry->size = PHYSFS_swapULE32(entry->size);
+        entry->startPos = PHYSFS_swapULE32(entry->startPos);
+    } /* for */
+
+    return entries;
+
+failed:
+    allocator.Free(entries);
+    return NULL;
+} /* wadLoadEntries */
+
+
+static void *WAD_openArchive(PHYSFS_Io *io, const char *name, int forWriting)
+{
+    PHYSFS_uint8 buf[4];
+    UNPKentry *entries = NULL;
+    PHYSFS_uint32 count = 0;
+
+    assert(io != NULL);  /* shouldn't ever happen. */
+
+    BAIL_IF_MACRO(forWriting, PHYSFS_ERR_READ_ONLY, NULL);
+    BAIL_IF_MACRO(!__PHYSFS_readAll(io, buf, sizeof (buf)), ERRPASS, NULL);
+    if ((memcmp(buf, "IWAD", 4) != 0) && (memcmp(buf, "PWAD", 4) != 0))
+        BAIL_MACRO(PHYSFS_ERR_UNSUPPORTED, NULL);
+
+    BAIL_IF_MACRO(!__PHYSFS_readAll(io, &count, sizeof (count)), ERRPASS, NULL);
+    count = PHYSFS_swapULE32(count);
+
+    entries = wadLoadEntries(io, count);
+    BAIL_IF_MACRO(!entries, ERRPASS, NULL);
+    return UNPK_openArchive(io, entries, count);
+} /* WAD_openArchive */
+
+
+const PHYSFS_Archiver __PHYSFS_Archiver_WAD =
+{
+    {
+        "WAD",
+        "DOOM engine format",
+        "Travis Wells <traviswells@mchsi.com>",
+        "http://www.3dmm2.com/doom/",
+    },
+    WAD_openArchive,        /* openArchive() method    */
+    UNPK_enumerateFiles,     /* enumerateFiles() method */
+    UNPK_openRead,           /* openRead() method       */
+    UNPK_openWrite,          /* openWrite() method      */
+    UNPK_openAppend,         /* openAppend() method     */
+    UNPK_remove,             /* remove() method         */
+    UNPK_mkdir,              /* mkdir() method          */
+    UNPK_closeArchive,       /* closeArchive() method   */
+    UNPK_stat                /* stat() method           */
+};
+
+#endif  /* defined PHYSFS_SUPPORTS_WAD */
+
+/* end of wad.c ... */
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/misc/physfs/src/archiver_zip.c	Sat Nov 17 20:30:32 2012 -0500
@@ -0,0 +1,1717 @@
+/*
+ * ZIP support routines for PhysicsFS.
+ *
+ * Please see the file LICENSE.txt in the source's root directory.
+ *
+ *  This file written by Ryan C. Gordon, with some peeking at "unzip.c"
+ *   by Gilles Vollant.
+ */
+
+#define __PHYSICSFS_INTERNAL__
+#include "physfs_internal.h"
+
+#if PHYSFS_SUPPORTS_ZIP
+
+#include <errno.h>
+#include <time.h>
+
+#define USE_MINIZ 1
+#if USE_MINIZ
+#include "physfs_miniz.h"
+#else
+#include <zlib.h>
+#endif
+
+/*
+ * A buffer of ZIP_READBUFSIZE is allocated for each compressed file opened,
+ *  and is freed when you close the file; compressed data is read into
+ *  this buffer, and then is decompressed into the buffer passed to
+ *  PHYSFS_read().
+ *
+ * Uncompressed entries in a zipfile do not allocate this buffer; they just
+ *  read data directly into the buffer passed to PHYSFS_read().
+ *
+ * Depending on your speed and memory requirements, you should tweak this
+ *  value.
+ */
+#define ZIP_READBUFSIZE   (16 * 1024)
+
+
+/*
+ * Entries are "unresolved" until they are first opened. At that time,
+ *  local file headers parsed/validated, data offsets will be updated to look
+ *  at the actual file data instead of the header, and symlinks will be
+ *  followed and optimized. This means that we don't seek and read around the
+ *  archive until forced to do so, and after the first time, we had to do
+ *  less reading and parsing, which is very CD-ROM friendly.
+ */
+typedef enum
+{
+    ZIP_UNRESOLVED_FILE,
+    ZIP_UNRESOLVED_SYMLINK,
+    ZIP_RESOLVING,
+    ZIP_RESOLVED,
+    ZIP_BROKEN_FILE,
+    ZIP_BROKEN_SYMLINK
+} ZipResolveType;
+
+
+/*
+ * One ZIPentry is kept for each file in an open ZIP archive.
+ */
+typedef struct _ZIPentry
+{
+    char *name;                         /* Name of file in archive        */
+    struct _ZIPentry *symlink;          /* NULL or file we symlink to     */
+    ZipResolveType resolved;            /* Have we resolved file/symlink? */
+    PHYSFS_uint64 offset;               /* offset of data in archive      */
+    PHYSFS_uint16 version;              /* version made by                */
+    PHYSFS_uint16 version_needed;       /* version needed to extract      */
+    PHYSFS_uint16 compression_method;   /* compression method             */
+    PHYSFS_uint32 crc;                  /* crc-32                         */
+    PHYSFS_uint64 compressed_size;      /* compressed size                */
+    PHYSFS_uint64 uncompressed_size;    /* uncompressed size              */
+    PHYSFS_sint64 last_mod_time;        /* last file mod time             */
+} ZIPentry;
+
+/*
+ * One ZIPinfo is kept for each open ZIP archive.
+ */
+typedef struct
+{
+    PHYSFS_Io *io;
+    int zip64;                /* non-zero if this is a Zip64 archive. */
+    PHYSFS_uint64 entryCount; /* Number of files in ZIP.              */
+    ZIPentry *entries;        /* info on all files in ZIP.            */
+} ZIPinfo;
+
+/*
+ * One ZIPfileinfo is kept for each open file in a ZIP archive.
+ */
+typedef struct
+{
+    ZIPentry *entry;                      /* Info on file.              */
+    PHYSFS_Io *io;                        /* physical file handle.      */
+    PHYSFS_uint32 compressed_position;    /* offset in compressed data. */
+    PHYSFS_uint32 uncompressed_position;  /* tell() position.           */
+    PHYSFS_uint8 *buffer;                 /* decompression buffer.      */
+    z_stream stream;                      /* zlib stream state.         */
+} ZIPfileinfo;
+
+
+/* Magic numbers... */
+#define ZIP_LOCAL_FILE_SIG                          0x04034b50
+#define ZIP_CENTRAL_DIR_SIG                         0x02014b50
+#define ZIP_END_OF_CENTRAL_DIR_SIG                  0x06054b50
+#define ZIP64_END_OF_CENTRAL_DIR_SIG                0x06064b50
+#define ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIG  0x07064b50
+#define ZIP64_EXTENDED_INFO_EXTRA_FIELD_SIG         0x0001
+
+/* compression methods... */
+#define COMPMETH_NONE 0
+/* ...and others... */
+
+
+#define UNIX_FILETYPE_MASK    0170000
+#define UNIX_FILETYPE_SYMLINK 0120000
+
+
+/*
+ * Bridge physfs allocation functions to zlib's format...
+ */
+static voidpf zlibPhysfsAlloc(voidpf opaque, uInt items, uInt size)
+{
+    return ((PHYSFS_Allocator *) opaque)->Malloc(items * size);
+} /* zlibPhysfsAlloc */
+
+/*
+ * Bridge physfs allocation functions to zlib's format...
+ */
+static void zlibPhysfsFree(voidpf opaque, voidpf address)
+{
+    ((PHYSFS_Allocator *) opaque)->Free(address);
+} /* zlibPhysfsFree */
+
+
+/*
+ * Construct a new z_stream to a sane state.
+ */
+static void initializeZStream(z_stream *pstr)
+{
+    memset(pstr, '\0', sizeof (z_stream));
+    pstr->zalloc = zlibPhysfsAlloc;
+    pstr->zfree = zlibPhysfsFree;
+    pstr->opaque = &allocator;
+} /* initializeZStream */
+
+
+static PHYSFS_ErrorCode zlib_error_code(int rc)
+{
+    switch (rc)
+    {
+        case Z_OK: return PHYSFS_ERR_OK;  /* not an error. */
+        case Z_STREAM_END: return PHYSFS_ERR_OK; /* not an error. */
+        case Z_ERRNO: return PHYSFS_ERR_IO;
+        case Z_MEM_ERROR: return PHYSFS_ERR_OUT_OF_MEMORY;
+        default: return PHYSFS_ERR_CORRUPT;
+    } /* switch */
+} /* zlib_error_string */
+
+
+/*
+ * Wrap all zlib calls in this, so the physfs error state is set appropriately.
+ */
+static int zlib_err(const int rc)
+{
+    __PHYSFS_setError(zlib_error_code(rc));
+    return rc;
+} /* zlib_err */
+
+
+/*
+ * Read an unsigned 64-bit int and swap to native byte order.
+ */
+static int readui64(PHYSFS_Io *io, PHYSFS_uint64 *val)
+{
+    PHYSFS_uint64 v;
+    BAIL_IF_MACRO(!__PHYSFS_readAll(io, &v, sizeof (v)), ERRPASS, 0);
+    *val = PHYSFS_swapULE64(v);
+    return 1;
+} /* readui64 */
+
+/*
+ * Read an unsigned 32-bit int and swap to native byte order.
+ */
+static int readui32(PHYSFS_Io *io, PHYSFS_uint32 *val)
+{
+    PHYSFS_uint32 v;
+    BAIL_IF_MACRO(!__PHYSFS_readAll(io, &v, sizeof (v)), ERRPASS, 0);
+    *val = PHYSFS_swapULE32(v);
+    return 1;
+} /* readui32 */
+
+
+/*
+ * Read an unsigned 16-bit int and swap to native byte order.
+ */
+static int readui16(PHYSFS_Io *io, PHYSFS_uint16 *val)
+{
+    PHYSFS_uint16 v;
+    BAIL_IF_MACRO(!__PHYSFS_readAll(io, &v, sizeof (v)), ERRPASS, 0);
+    *val = PHYSFS_swapULE16(v);
+    return 1;
+} /* readui16 */
+
+
+static PHYSFS_sint64 ZIP_read(PHYSFS_Io *_io, void *buf, PHYSFS_uint64 len)
+{
+    ZIPfileinfo *finfo = (ZIPfileinfo *) _io->opaque;
+    PHYSFS_Io *io = finfo->io;
+    ZIPentry *entry = finfo->entry;
+    PHYSFS_sint64 retval = 0;
+    PHYSFS_sint64 maxread = (PHYSFS_sint64) len;
+    PHYSFS_sint64 avail = entry->uncompressed_size -
+                          finfo->uncompressed_position;
+
+    if (avail < maxread)
+        maxread = avail;
+
+    BAIL_IF_MACRO(maxread == 0, ERRPASS, 0);    /* quick rejection. */
+
+    if (entry->compression_method == COMPMETH_NONE)
+        retval = io->read(io, buf, maxread);
+    else
+    {
+        finfo->stream.next_out = buf;
+        finfo->stream.avail_out = (uInt) maxread;
+
+        while (retval < maxread)
+        {
+            PHYSFS_uint32 before = finfo->stream.total_out;
+            int rc;
+
+            if (finfo->stream.avail_in == 0)
+            {
+                PHYSFS_sint64 br;
+
+                br = entry->compressed_size - finfo->compressed_position;
+                if (br > 0)
+                {
+                    if (br > ZIP_READBUFSIZE)
+                        br = ZIP_READBUFSIZE;
+
+                    br = io->read(io, finfo->buffer, (PHYSFS_uint64) br);
+                    if (br <= 0)
+                        break;
+
+                    finfo->compressed_position += (PHYSFS_uint32) br;
+                    finfo->stream.next_in = finfo->buffer;
+                    finfo->stream.avail_in = (PHYSFS_uint32) br;
+                } /* if */
+            } /* if */
+
+            rc = zlib_err(inflate(&finfo->stream, Z_SYNC_FLUSH));
+            retval += (finfo->stream.total_out - before);
+
+            if (rc != Z_OK)
+                break;
+        } /* while */
+    } /* else */
+
+    if (retval > 0)
+        finfo->uncompressed_position += (PHYSFS_uint32) retval;
+
+    return retval;
+} /* ZIP_read */
+
+
+static PHYSFS_sint64 ZIP_write(PHYSFS_Io *io, const void *b, PHYSFS_uint64 len)
+{
+    BAIL_MACRO(PHYSFS_ERR_READ_ONLY, -1);
+} /* ZIP_write */
+
+
+static PHYSFS_sint64 ZIP_tell(PHYSFS_Io *io)
+{
+    return ((ZIPfileinfo *) io->opaque)->uncompressed_position;
+} /* ZIP_tell */
+
+
+static int ZIP_seek(PHYSFS_Io *_io, PHYSFS_uint64 offset)
+{
+    ZIPfileinfo *finfo = (ZIPfileinfo *) _io->opaque;
+    ZIPentry *entry = finfo->entry;
+    PHYSFS_Io *io = finfo->io;
+
+    BAIL_IF_MACRO(offset > entry->uncompressed_size, PHYSFS_ERR_PAST_EOF, 0);
+
+    if (entry->compression_method == COMPMETH_NONE)
+    {
+        const PHYSFS_sint64 newpos = offset + entry->offset;
+        BAIL_IF_MACRO(!io->seek(io, newpos), ERRPASS, 0);
+        finfo->uncompressed_position = (PHYSFS_uint32) offset;
+    } /* if */
+
+    else
+    {
+        /*
+         * If seeking backwards, we need to redecode the file
+         *  from the start and throw away the compressed bits until we hit
+         *  the offset we need. If seeking forward, we still need to
+         *  decode, but we don't rewind first.
+         */
+        if (offset < finfo->uncompressed_position)
+        {
+            /* we do a copy so state is sane if inflateInit2() fails. */
+            z_stream str;
+            initializeZStream(&str);
+            if (zlib_err(inflateInit2(&str, -MAX_WBITS)) != Z_OK)
+                return 0;
+
+            if (!io->seek(io, entry->offset))
+                return 0;
+
+            inflateEnd(&finfo->stream);
+            memcpy(&finfo->stream, &str, sizeof (z_stream));
+            finfo->uncompressed_position = finfo->compressed_position = 0;
+        } /* if */
+
+        while (finfo->uncompressed_position != offset)
+        {
+            PHYSFS_uint8 buf[512];
+            PHYSFS_uint32 maxread;
+
+            maxread = (PHYSFS_uint32) (offset - finfo->uncompressed_position);
+            if (maxread > sizeof (buf))
+                maxread = sizeof (buf);
+
+            if (ZIP_read(_io, buf, maxread) != maxread)
+                return 0;
+        } /* while */
+    } /* else */
+
+    return 1;
+} /* ZIP_seek */
+
+
+static PHYSFS_sint64 ZIP_length(PHYSFS_Io *io)
+{
+    const ZIPfileinfo *finfo = (ZIPfileinfo *) io->opaque;
+    return (PHYSFS_sint64) finfo->entry->uncompressed_size;
+} /* ZIP_length */
+
+
+static PHYSFS_Io *zip_get_io(PHYSFS_Io *io, ZIPinfo *inf, ZIPentry *entry);
+
+static PHYSFS_Io *ZIP_duplicate(PHYSFS_Io *io)
+{
+    ZIPfileinfo *origfinfo = (ZIPfileinfo *) io->opaque;
+    PHYSFS_Io *retval = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
+    ZIPfileinfo *finfo = (ZIPfileinfo *) allocator.Malloc(sizeof (ZIPfileinfo));
+    GOTO_IF_MACRO(!retval, PHYSFS_ERR_OUT_OF_MEMORY, failed);
+    GOTO_IF_MACRO(!finfo, PHYSFS_ERR_OUT_OF_MEMORY, failed);
+    memset(finfo, '\0', sizeof (*finfo));
+
+    finfo->entry = origfinfo->entry;
+    finfo->io = zip_get_io(origfinfo->io, NULL, finfo->entry);
+    GOTO_IF_MACRO(!finfo->io, ERRPASS, failed);
+
+    if (finfo->entry->compression_method != COMPMETH_NONE)
+    {
+        finfo->buffer = (PHYSFS_uint8 *) allocator.Malloc(ZIP_READBUFSIZE);
+        GOTO_IF_MACRO(!finfo->buffer, PHYSFS_ERR_OUT_OF_MEMORY, failed);
+        if (zlib_err(inflateInit2(&finfo->stream, -MAX_WBITS)) != Z_OK)
+            goto failed;
+    } /* if */
+
+    memcpy(retval, io, sizeof (PHYSFS_Io));
+    retval->opaque = finfo;
+    return retval;
+
+failed:
+    if (finfo != NULL)
+    {
+        if (finfo->io != NULL)
+            finfo->io->destroy(finfo->io);
+
+        if (finfo->buffer != NULL)
+        {
+            allocator.Free(finfo->buffer);
+            inflateEnd(&finfo->stream);
+        } /* if */
+
+        allocator.Free(finfo);
+    } /* if */
+
+    if (retval != NULL)
+        allocator.Free(retval);
+
+    return NULL;
+} /* ZIP_duplicate */
+
+static int ZIP_flush(PHYSFS_Io *io) { return 1;  /* no write support. */ }
+
+static void ZIP_destroy(PHYSFS_Io *io)
+{
+    ZIPfileinfo *finfo = (ZIPfileinfo *) io->opaque;
+    finfo->io->destroy(finfo->io);
+
+    if (finfo->entry->compression_method != COMPMETH_NONE)
+        inflateEnd(&finfo->stream);
+
+    if (finfo->buffer != NULL)
+        allocator.Free(finfo->buffer);
+
+    allocator.Free(finfo);
+    allocator.Free(io);
+} /* ZIP_destroy */
+
+
+static const PHYSFS_Io ZIP_Io =
+{
+    CURRENT_PHYSFS_IO_API_VERSION, NULL,
+    ZIP_read,
+    ZIP_write,
+    ZIP_seek,
+    ZIP_tell,
+    ZIP_length,
+    ZIP_duplicate,
+    ZIP_flush,
+    ZIP_destroy
+};
+
+
+
+static PHYSFS_sint64 zip_find_end_of_central_dir(PHYSFS_Io *io, PHYSFS_sint64 *len)
+{
+    PHYSFS_uint8 buf[256];
+    PHYSFS_uint8 extra[4] = { 0, 0, 0, 0 };
+    PHYSFS_sint32 i = 0;
+    PHYSFS_sint64 filelen;
+    PHYSFS_sint64 filepos;
+    PHYSFS_sint32 maxread;
+    PHYSFS_sint32 totalread = 0;
+    int found = 0;
+
+    filelen = io->length(io);
+    BAIL_IF_MACRO(filelen == -1, ERRPASS, 0);
+
+    /*
+     * Jump to the end of the file and start reading backwards.
+     *  The last thing in the file is the zipfile comment, which is variable
+     *  length, and the field that specifies its size is before it in the
+     *  file (argh!)...this means that we need to scan backwards until we
+     *  hit the end-of-central-dir signature. We can then sanity check that
+     *  the comment was as big as it should be to make sure we're in the
+     *  right place. The comment length field is 16 bits, so we can stop
+     *  searching for that signature after a little more than 64k at most,
+     *  and call it a corrupted zipfile.
+     */
+
+    if (sizeof (buf) < filelen)
+    {
+        filepos = filelen - sizeof (buf);
+        maxread = sizeof (buf);
+    } /* if */
+    else
+    {
+        filepos = 0;
+        maxread = (PHYSFS_uint32) filelen;
+    } /* else */
+
+    while ((totalread < filelen) && (totalread < 65557))
+    {
+        BAIL_IF_MACRO(!io->seek(io, filepos), ERRPASS, -1);
+
+        /* make sure we catch a signature between buffers. */
+        if (totalread != 0)
+        {
+            if (!__PHYSFS_readAll(io, buf, maxread - 4))
+                return -1;
+            memcpy(&buf[maxread - 4], &extra, sizeof (extra));
+            totalread += maxread - 4;
+        } /* if */
+        else
+        {
+            if (!__PHYSFS_readAll(io, buf, maxread))
+                return -1;
+            totalread += maxread;
+        } /* else */
+
+        memcpy(&extra, buf, sizeof (extra));
+
+        for (i = maxread - 4; i > 0; i--)
+        {
+            if ((buf[i + 0] == 0x50) &&
+                (buf[i + 1] == 0x4B) &&
+                (buf[i + 2] == 0x05) &&
+                (buf[i + 3] == 0x06) )
+            {
+                found = 1;  /* that's the signature! */
+                break;  
+            } /* if */
+        } /* for */
+
+        if (found)
+            break;
+
+        filepos -= (maxread - 4);
+        if (filepos < 0)
+            filepos = 0;
+    } /* while */
+
+    BAIL_IF_MACRO(!found, PHYSFS_ERR_UNSUPPORTED, -1);
+
+    if (len != NULL)
+        *len = filelen;
+
+    return (filepos + i);
+} /* zip_find_end_of_central_dir */
+
+
+static int isZip(PHYSFS_Io *io)
+{
+    PHYSFS_uint32 sig = 0;
+    int retval = 0;
+
+    /*
+     * The first thing in a zip file might be the signature of the
+     *  first local file record, so it makes for a quick determination.
+     */
+    if (readui32(io, &sig))
+    {
+        retval = (sig == ZIP_LOCAL_FILE_SIG);
+        if (!retval)
+        {
+            /*
+             * No sig...might be a ZIP with data at the start
+             *  (a self-extracting executable, etc), so we'll have to do
+             *  it the hard way...
+             */
+            retval = (zip_find_end_of_central_dir(io, NULL) != -1);
+        } /* if */
+    } /* if */
+
+    return retval;
+} /* isZip */
+
+
+static void zip_free_entries(ZIPentry *entries, PHYSFS_uint64 max)
+{
+    PHYSFS_uint64 i;
+    for (i = 0; i < max; i++)
+    {
+        ZIPentry *entry = &entries[i];
+        if (entry->name != NULL)
+            allocator.Free(entry->name);
+    } /* for */
+
+    allocator.Free(entries);
+} /* zip_free_entries */
+
+
+/*
+ * This will find the ZIPentry associated with a path in platform-independent
+ *  notation. Directories don't have ZIPentries associated with them, but 
+ *  (*isDir) will be set to non-zero if a dir was hit.
+ */
+static ZIPentry *zip_find_entry(const ZIPinfo *info, const char *path,
+                                int *isDir)
+{
+    ZIPentry *a = info->entries;
+    PHYSFS_sint32 pathlen = (PHYSFS_sint32) strlen(path);
+    PHYSFS_sint64 lo = 0;
+    PHYSFS_sint64 hi = (PHYSFS_sint64) (info->entryCount - 1);
+    PHYSFS_sint64 middle;
+    const char *thispath = NULL;
+    int rc;
+
+    while (lo <= hi)
+    {
+        middle = lo + ((hi - lo) / 2);
+        thispath = a[middle].name;
+        rc = strncmp(path, thispath, pathlen);
+
+        if (rc > 0)
+            lo = middle + 1;
+
+        else if (rc < 0)
+            hi = middle - 1;
+
+        else /* substring match...might be dir or entry or nothing. */
+        {
+            if (isDir != NULL)
+            {
+                *isDir = (thispath[pathlen] == '/');
+                if (*isDir)
+                    return NULL;
+            } /* if */
+
+            if (thispath[pathlen] == '\0') /* found entry? */
+                return &a[middle];
+            /* adjust search params, try again. */
+            else if (thispath[pathlen] > '/')
+                hi = middle - 1;
+            else
+                lo = middle + 1;
+        } /* if */
+    } /* while */
+
+    if (isDir != NULL)
+        *isDir = 0;
+
+    BAIL_MACRO(PHYSFS_ERR_NO_SUCH_PATH, NULL);
+} /* zip_find_entry */
+
+
+/* Convert paths from old, buggy DOS zippers... */
+static void zip_convert_dos_path(ZIPentry *entry, char *path)
+{
+    PHYSFS_uint8 hosttype = (PHYSFS_uint8) ((entry->version >> 8) & 0xFF);
+    if (hosttype == 0)  /* FS_FAT_ */
+    {
+        while (*path)
+        {
+            if (*path == '\\')
+                *path = '/';
+            path++;
+        } /* while */
+    } /* if */
+} /* zip_convert_dos_path */
+
+
+static void zip_expand_symlink_path(char *path)
+{
+    char *ptr = path;
+    char *prevptr = path;
+
+    while (1)
+    {
+        ptr = strchr(ptr, '/');
+        if (ptr == NULL)
+            break;
+
+        if (*(ptr + 1) == '.')
+        {
+            if (*(ptr + 2) == '/')
+            {
+                /* current dir in middle of string: ditch it. */
+                memmove(ptr, ptr + 2, strlen(ptr + 2) + 1);
+            } /* else if */
+
+            else if (*(ptr + 2) == '\0')
+            {
+                /* current dir at end of string: ditch it. */
+                *ptr = '\0';
+            } /* else if */
+
+            else if (*(ptr + 2) == '.')
+            {
+                if (*(ptr + 3) == '/')
+                {
+                    /* parent dir in middle: move back one, if possible. */
+                    memmove(prevptr, ptr + 4, strlen(ptr + 4) + 1);
+                    ptr = prevptr;
+                    while (prevptr != path)
+                    {
+                        prevptr--;
+                        if (*prevptr == '/')
+                        {
+                            prevptr++;
+                            break;
+                        } /* if */
+                    } /* while */
+                } /* if */
+
+                if (*(ptr + 3) == '\0')
+                {
+                    /* parent dir at end: move back one, if possible. */
+                    *prevptr = '\0';
+                } /* if */
+            } /* if */
+        } /* if */
+        else
+        {
+            prevptr = ptr;
+            ptr++;
+        } /* else */
+    } /* while */
+} /* zip_expand_symlink_path */
+
+/* (forward reference: zip_follow_symlink and zip_resolve call each other.) */
+static int zip_resolve(PHYSFS_Io *io, ZIPinfo *info, ZIPentry *entry);
+
+/*
+ * Look for the entry named by (path). If it exists, resolve it, and return
+ *  a pointer to that entry. If it's another symlink, keep resolving until you
+ *  hit a real file and then return a pointer to the final non-symlink entry.
+ *  If there's a problem, return NULL.
+ */
+static ZIPentry *zip_follow_symlink(PHYSFS_Io *io, ZIPinfo *info, char *path)
+{
+    ZIPentry *entry;
+
+    zip_expand_symlink_path(path);
+    entry = zip_find_entry(info, path, NULL);
+    if (entry != NULL)
+    {
+        if (!zip_resolve(io, info, entry))  /* recursive! */
+            entry = NULL;
+        else
+        {
+            if (entry->symlink != NULL)
+                entry = entry->symlink;
+        } /* else */
+    } /* if */
+
+    return entry;
+} /* zip_follow_symlink */
+
+
+static int zip_resolve_symlink(PHYSFS_Io *io, ZIPinfo *info, ZIPentry *entry)
+{
+    const PHYSFS_uint64 size = entry->uncompressed_size;
+    char *path = NULL;
+    int rc = 0;
+
+    /*
+     * We've already parsed the local file header of the symlink at this
+     *  point. Now we need to read the actual link from the file data and
+     *  follow it.
+     */
+
+    BAIL_IF_MACRO(!io->seek(io, entry->offset), ERRPASS, 0);
+
+    path = (char *) __PHYSFS_smallAlloc(size + 1);
+    BAIL_IF_MACRO(!path, PHYSFS_ERR_OUT_OF_MEMORY, 0);
+    
+    if (entry->compression_method == COMPMETH_NONE)
+        rc = __PHYSFS_readAll(io, path, size);
+
+    else  /* symlink target path is compressed... */
+    {
+        z_stream stream;
+        const PHYSFS_uint64 complen = entry->compressed_size;
+        PHYSFS_uint8 *compressed = (PHYSFS_uint8*) __PHYSFS_smallAlloc(complen);
+        if (compressed != NULL)
+        {
+            if (__PHYSFS_readAll(io, compressed, complen))
+            {
+                initializeZStream(&stream);
+                stream.next_in = compressed;
+                stream.avail_in = complen;
+                stream.next_out = (unsigned char *) path;
+                stream.avail_out = size;
+                if (zlib_err(inflateInit2(&stream, -MAX_WBITS)) == Z_OK)
+                {
+                    rc = zlib_err(inflate(&stream, Z_FINISH));
+                    inflateEnd(&stream);
+
+                    /* both are acceptable outcomes... */
+                    rc = ((rc == Z_OK) || (rc == Z_STREAM_END));
+                } /* if */
+            } /* if */
+            __PHYSFS_smallFree(compressed);
+        } /* if */
+    } /* else */
+
+    if (rc)
+    {
+        path[entry->uncompressed_size] = '\0';    /* null-terminate it. */
+        zip_convert_dos_path(entry, path);
+        entry->symlink = zip_follow_symlink(io, info, path);
+    } /* else */
+
+    __PHYSFS_smallFree(path);
+
+    return (entry->symlink != NULL);
+} /* zip_resolve_symlink */
+
+
+/*
+ * Parse the local file header of an entry, and update entry->offset.
+ */
+static int zip_parse_local(PHYSFS_Io *io, ZIPentry *entry)
+{
+    PHYSFS_uint32 ui32;
+    PHYSFS_uint16 ui16;
+    PHYSFS_uint16 fnamelen;
+    PHYSFS_uint16 extralen;
+
+    /*
+     * crc and (un)compressed_size are always zero if this is a "JAR"
+     *  archive created with Sun's Java tools, apparently. We only
+     *  consider this archive corrupted if those entries don't match and
+     *  aren't zero. That seems to work well.
+     * We also ignore a mismatch if the value is 0xFFFFFFFF here, since it's
+     *  possible that's a Zip64 thing.
+     */
+
+    BAIL_IF_MACRO(!io->seek(io, entry->offset), ERRPASS, 0);
+    BAIL_IF_MACRO(!readui32(io, &ui32), ERRPASS, 0);
+    BAIL_IF_MACRO(ui32 != ZIP_LOCAL_FILE_SIG, PHYSFS_ERR_CORRUPT, 0);
+    BAIL_IF_MACRO(!readui16(io, &ui16), ERRPASS, 0);
+    BAIL_IF_MACRO(ui16 != entry->version_needed, PHYSFS_ERR_CORRUPT, 0);
+    BAIL_IF_MACRO(!readui16(io, &ui16), ERRPASS, 0);  /* general bits. */
+    BAIL_IF_MACRO(!readui16(io, &ui16), ERRPASS, 0);
+    BAIL_IF_MACRO(ui16 != entry->compression_method, PHYSFS_ERR_CORRUPT, 0);
+    BAIL_IF_MACRO(!readui32(io, &ui32), ERRPASS, 0);  /* date/time */
+    BAIL_IF_MACRO(!readui32(io, &ui32), ERRPASS, 0);
+    BAIL_IF_MACRO(ui32 && (ui32 != entry->crc), PHYSFS_ERR_CORRUPT, 0);
+
+    BAIL_IF_MACRO(!readui32(io, &ui32), ERRPASS, 0);
+    BAIL_IF_MACRO(ui32 && (ui32 != 0xFFFFFFFF) &&
+                  (ui32 != entry->compressed_size), PHYSFS_ERR_CORRUPT, 0);
+
+    BAIL_IF_MACRO(!readui32(io, &ui32), ERRPASS, 0);
+    BAIL_IF_MACRO(ui32 && (ui32 != 0xFFFFFFFF) &&
+                 (ui32 != entry->uncompressed_size), PHYSFS_ERR_CORRUPT, 0);
+
+    BAIL_IF_MACRO(!readui16(io, &fnamelen), ERRPASS, 0);
+    BAIL_IF_MACRO(!readui16(io, &extralen), ERRPASS, 0);
+
+    entry->offset += fnamelen + extralen + 30;
+    return 1;
+} /* zip_parse_local */
+
+
+static int zip_resolve(PHYSFS_Io *io, ZIPinfo *info, ZIPentry *entry)
+{
+    int retval = 1;
+    ZipResolveType resolve_type = entry->resolved;
+
+    /* Don't bother if we've failed to resolve this entry before. */
+    BAIL_IF_MACRO(resolve_type == ZIP_BROKEN_FILE, PHYSFS_ERR_CORRUPT, 0);
+    BAIL_IF_MACRO(resolve_type == ZIP_BROKEN_SYMLINK, PHYSFS_ERR_CORRUPT, 0);
+
+    /* uhoh...infinite symlink loop! */
+    BAIL_IF_MACRO(resolve_type == ZIP_RESOLVING, PHYSFS_ERR_SYMLINK_LOOP, 0);
+
+    /*
+     * We fix up the offset to point to the actual data on the
+     *  first open, since we don't want to seek across the whole file on
+     *  archive open (can be SLOW on large, CD-stored files), but we
+     *  need to check the local file header...not just for corruption,
+     *  but since it stores offset info the central directory does not.
+     */
+    if (resolve_type != ZIP_RESOLVED)
+    {
+        entry->resolved = ZIP_RESOLVING;
+
+        retval = zip_parse_local(io, entry);
+        if (retval)
+        {
+            /*
+             * If it's a symlink, find the original file. This will cause
+             *  resolution of other entries (other symlinks and, eventually,
+             *  the real file) if all goes well.
+             */
+            if (resolve_type == ZIP_UNRESOLVED_SYMLINK)
+                retval = zip_resolve_symlink(io, info, entry);
+        } /* if */
+
+        if (resolve_type == ZIP_UNRESOLVED_SYMLINK)
+            entry->resolved = ((retval) ? ZIP_RESOLVED : ZIP_BROKEN_SYMLINK);
+        else if (resolve_type == ZIP_UNRESOLVED_FILE)
+            entry->resolved = ((retval) ? ZIP_RESOLVED : ZIP_BROKEN_FILE);
+    } /* if */
+
+    return retval;
+} /* zip_resolve */
+
+
+static int zip_version_does_symlinks(PHYSFS_uint32 version)
+{
+    int retval = 0;
+    PHYSFS_uint8 hosttype = (PHYSFS_uint8) ((version >> 8) & 0xFF);
+
+    switch (hosttype)
+    {
+            /*
+             * These are the platforms that can NOT build an archive with
+             *  symlinks, according to the Info-ZIP project.
+             */
+        case 0:  /* FS_FAT_  */
+        case 1:  /* AMIGA_   */
+        case 2:  /* VMS_     */
+        case 4:  /* VM_CSM_  */
+        case 6:  /* FS_HPFS_ */
+        case 11: /* FS_NTFS_ */
+        case 14: /* FS_VFAT_ */
+        case 13: /* ACORN_   */
+        case 15: /* MVS_     */
+        case 18: /* THEOS_   */
+            break;  /* do nothing. */
+
+        default:  /* assume the rest to be unix-like. */
+            retval = 1;
+            break;
+    } /* switch */
+
+    return retval;
+} /* zip_version_does_symlinks */
+
+
+static int zip_entry_is_symlink(const ZIPentry *entry)
+{
+    return ((entry->resolved == ZIP_UNRESOLVED_SYMLINK) ||
+            (entry->resolved == ZIP_BROKEN_SYMLINK) ||
+            (entry->symlink));
+} /* zip_entry_is_symlink */
+
+
+static int zip_has_symlink_attr(ZIPentry *entry, PHYSFS_uint32 extern_attr)
+{
+    PHYSFS_uint16 xattr = ((extern_attr >> 16) & 0xFFFF);
+    return ( (zip_version_does_symlinks(entry->version)) &&
+             (entry->uncompressed_size > 0) &&
+             ((xattr & UNIX_FILETYPE_MASK) == UNIX_FILETYPE_SYMLINK) );
+} /* zip_has_symlink_attr */
+
+
+static PHYSFS_sint64 zip_dos_time_to_physfs_time(PHYSFS_uint32 dostime)
+{
+    PHYSFS_uint32 dosdate;
+    struct tm unixtime;
+    memset(&unixtime, '\0', sizeof (unixtime));
+
+    dosdate = (PHYSFS_uint32) ((dostime >> 16) & 0xFFFF);
+    dostime &= 0xFFFF;
+
+    /* dissect date */
+    unixtime.tm_year = ((dosdate >> 9) & 0x7F) + 80;
+    unixtime.tm_mon  = ((dosdate >> 5) & 0x0F) - 1;
+    unixtime.tm_mday = ((dosdate     ) & 0x1F);
+
+    /* dissect time */
+    unixtime.tm_hour = ((dostime >> 11) & 0x1F);
+    unixtime.tm_min  = ((dostime >>  5) & 0x3F);
+    unixtime.tm_sec  = ((dostime <<  1) & 0x3E);
+
+    /* let mktime calculate daylight savings time. */
+    unixtime.tm_isdst = -1;
+
+    return ((PHYSFS_sint64) mktime(&unixtime));
+} /* zip_dos_time_to_physfs_time */
+
+
+static int zip_load_entry(PHYSFS_Io *io, const int zip64, ZIPentry *entry,
+                          PHYSFS_uint64 ofs_fixup)
+{
+    PHYSFS_uint16 fnamelen, extralen, commentlen;
+    PHYSFS_uint32 external_attr;
+    PHYSFS_uint32 starting_disk;
+    PHYSFS_uint64 offset;
+    PHYSFS_uint16 ui16;
+    PHYSFS_uint32 ui32;
+    PHYSFS_sint64 si64;
+
+    /* sanity check with central directory signature... */
+    BAIL_IF_MACRO(!readui32(io, &ui32), ERRPASS, 0);
+    BAIL_IF_MACRO(ui32 != ZIP_CENTRAL_DIR_SIG, PHYSFS_ERR_CORRUPT, 0);
+
+    /* Get the pertinent parts of the record... */
+    BAIL_IF_MACRO(!readui16(io, &entry->version), ERRPASS, 0);
+    BAIL_IF_MACRO(!readui16(io, &entry->version_needed), ERRPASS, 0);
+    BAIL_IF_MACRO(!readui16(io, &ui16), ERRPASS, 0);  /* general bits */
+    BAIL_IF_MACRO(!readui16(io, &entry->compression_method), ERRPASS, 0);
+    BAIL_IF_MACRO(!readui32(io, &ui32), ERRPASS, 0);
+    entry->last_mod_time = zip_dos_time_to_physfs_time(ui32);
+    BAIL_IF_MACRO(!readui32(io, &entry->crc), ERRPASS, 0);
+    BAIL_IF_MACRO(!readui32(io, &ui32), ERRPASS, 0);
+    entry->compressed_size = (PHYSFS_uint64) ui32;
+    BAIL_IF_MACRO(!readui32(io, &ui32), ERRPASS, 0);
+    entry->uncompressed_size = (PHYSFS_uint64) ui32;
+    BAIL_IF_MACRO(!readui16(io, &fnamelen), ERRPASS, 0);
+    BAIL_IF_MACRO(!readui16(io, &extralen), ERRPASS, 0);
+    BAIL_IF_MACRO(!readui16(io, &commentlen), ERRPASS, 0);
+    BAIL_IF_MACRO(!readui16(io, &ui16), ERRPASS, 0);
+    starting_disk = (PHYSFS_uint32) ui16;
+    BAIL_IF_MACRO(!readui16(io, &ui16), ERRPASS, 0);  /* internal file attribs */
+    BAIL_IF_MACRO(!readui32(io, &external_attr), ERRPASS, 0);
+    BAIL_IF_MACRO(!readui32(io, &ui32), ERRPASS, 0);
+    offset = (PHYSFS_uint64) ui32;
+
+    entry->symlink = NULL;  /* will be resolved later, if necessary. */
+    entry->resolved = (zip_has_symlink_attr(entry, external_attr)) ?
+                            ZIP_UNRESOLVED_SYMLINK : ZIP_UNRESOLVED_FILE;
+
+    entry->name = (char *) allocator.Malloc(fnamelen + 1);
+    BAIL_IF_MACRO(entry->name == NULL, PHYSFS_ERR_OUT_OF_MEMORY, 0);
+    if (!__PHYSFS_readAll(io, entry->name, fnamelen))
+        goto zip_load_entry_puked;
+
+    entry->name[fnamelen] = '\0';  /* null-terminate the filename. */
+    zip_convert_dos_path(entry, entry->name);
+
+    si64 = io->tell(io);
+    if (si64 == -1)
+        goto zip_load_entry_puked;
+
+    /*
+     * The actual sizes didn't fit in 32-bits; look for the Zip64
+     *  extended information extra field...
+     */
+    if ( (zip64) &&
+         ((offset == 0xFFFFFFFF) ||
+          (starting_disk == 0xFFFFFFFF) ||
+          (entry->compressed_size == 0xFFFFFFFF) ||
+          (entry->uncompressed_size == 0xFFFFFFFF)) )
+    {
+        int found = 0;
+        PHYSFS_uint16 sig, len;
+        while (extralen > 4)
+        {
+            if (!readui16(io, &sig))
+                goto zip_load_entry_puked;
+            else if (!readui16(io, &len))
+                goto zip_load_entry_puked;
+
+            si64 += 4 + len;
+            extralen -= 4 + len;
+            if (sig != ZIP64_EXTENDED_INFO_EXTRA_FIELD_SIG)
+            {
+                if (!io->seek(io, si64))
+                    goto zip_load_entry_puked;
+                continue;
+            } /* if */
+
+            found = 1;
+            break;
+        } /* while */
+
+        GOTO_IF_MACRO(!found, PHYSFS_ERR_CORRUPT, zip_load_entry_puked);
+
+        if (entry->uncompressed_size == 0xFFFFFFFF)
+        {
+            GOTO_IF_MACRO(len < 8, PHYSFS_ERR_CORRUPT, zip_load_entry_puked);
+            if (!readui64(io, &entry->uncompressed_size))
+                goto zip_load_entry_puked;
+            len -= 8;
+        } /* if */
+
+        if (entry->compressed_size == 0xFFFFFFFF)
+        {
+            GOTO_IF_MACRO(len < 8, PHYSFS_ERR_CORRUPT, zip_load_entry_puked);
+            if (!readui64(io, &entry->compressed_size))
+                goto zip_load_entry_puked;
+            len -= 8;
+        } /* if */
+
+        if (offset == 0xFFFFFFFF)
+        {
+            GOTO_IF_MACRO(len < 8, PHYSFS_ERR_CORRUPT, zip_load_entry_puked);
+            if (!readui64(io, &offset))
+                goto zip_load_entry_puked;
+            len -= 8;
+        } /* if */
+
+        if (starting_disk == 0xFFFFFFFF)
+        {
+            GOTO_IF_MACRO(len < 8, PHYSFS_ERR_CORRUPT, zip_load_entry_puked);
+            if (!readui32(io, &starting_disk))
+                goto zip_load_entry_puked;
+            len -= 4;
+        } /* if */
+
+        GOTO_IF_MACRO(len != 0, PHYSFS_ERR_CORRUPT, zip_load_entry_puked);
+    } /* if */
+
+    GOTO_IF_MACRO(starting_disk != 0, PHYSFS_ERR_CORRUPT, zip_load_entry_puked);
+
+    entry->offset = offset + ofs_fixup;
+
+    /* seek to the start of the next entry in the central directory... */
+    if (!io->seek(io, si64 + extralen + commentlen))
+        goto zip_load_entry_puked;
+
+    return 1;  /* success. */
+
+zip_load_entry_puked:
+    allocator.Free(entry->name);
+    return 0;  /* failure. */
+} /* zip_load_entry */
+
+
+static int zip_entry_cmp(void *_a, size_t one, size_t two)
+{
+    if (one != two)
+    {
+        const ZIPentry *a = (const ZIPentry *) _a;
+        return strcmp(a[one].name, a[two].name);
+    } /* if */
+
+    return 0;
+} /* zip_entry_cmp */
+
+
+static void zip_entry_swap(void *_a, size_t one, size_t two)
+{
+    if (one != two)
+    {
+        ZIPentry tmp;
+        ZIPentry *first = &(((ZIPentry *) _a)[one]);
+        ZIPentry *second = &(((ZIPentry *) _a)[two]);
+        memcpy(&tmp, first, sizeof (ZIPentry));
+        memcpy(first, second, sizeof (ZIPentry));
+        memcpy(second, &tmp, sizeof (ZIPentry));
+    } /* if */
+} /* zip_entry_swap */
+
+
+static int zip_load_entries(PHYSFS_Io *io, ZIPinfo *info,
+                            const PHYSFS_uint64 data_ofs,
+                            const PHYSFS_uint64 central_ofs)
+{
+    const PHYSFS_uint64 max = info->entryCount;
+    const int zip64 = info->zip64;
+    PHYSFS_uint64 i;
+
+    BAIL_IF_MACRO(!io->seek(io, central_ofs), ERRPASS, 0);
+
+    info->entries = (ZIPentry *) allocator.Malloc(sizeof (ZIPentry) * max);
+    BAIL_IF_MACRO(!info->entries, PHYSFS_ERR_OUT_OF_MEMORY, 0);
+
+    for (i = 0; i < max; i++)
+    {
+        if (!zip_load_entry(io, zip64, &info->entries[i], data_ofs))
+        {
+            zip_free_entries(info->entries, i);
+            return 0;
+        } /* if */
+    } /* for */
+
+    __PHYSFS_sort(info->entries, (size_t) max, zip_entry_cmp, zip_entry_swap);
+    return 1;
+} /* zip_load_entries */
+
+
+static PHYSFS_sint64 zip64_find_end_of_central_dir(PHYSFS_Io *io,
+                                                   PHYSFS_sint64 _pos,
+                                                   PHYSFS_uint64 offset)
+{
+    /*
+     * Naturally, the offset is useless to us; it is the offset from the
+     *  start of file, which is meaningless if we've appended this .zip to
+     *  a self-extracting .exe. We need to find this on our own. It should
+     *  be directly before the locator record, but the record in question,
+     *  like the original end-of-central-directory record, ends with a
+     *  variable-length field. Unlike the original, which has to store the
+     *  size of that variable-length field in a 16-bit int and thus has to be
+     *  within 64k, the new one gets 64-bits.
+     *
+     * Fortunately, the only currently-specified record for that variable
+     *  length block is some weird proprietary thing that deals with EBCDIC
+     *  and tape backups or something. So we don't seek far.
+     */
+
+    PHYSFS_uint32 ui32;
+    const PHYSFS_uint64 pos = (PHYSFS_uint64) _pos;
+
+    assert(_pos > 0);
+
+    /* Try offset specified in the Zip64 end of central directory locator. */
+    /* This works if the entire PHYSFS_Io is the zip file. */
+    BAIL_IF_MACRO(!io->seek(io, offset), ERRPASS, -1);
+    BAIL_IF_MACRO(!readui32(io, &ui32), ERRPASS, -1);
+    if (ui32 == ZIP64_END_OF_CENTRAL_DIR_SIG)
+        return offset;
+
+    /* Try 56 bytes before the Zip64 end of central directory locator. */
+    /* This works if the record isn't variable length and is version 1. */
+    if (pos > 56)
+    {
+        BAIL_IF_MACRO(!io->seek(io, pos-56), ERRPASS, -1);
+        BAIL_IF_MACRO(!readui32(io, &ui32), ERRPASS, -1);
+        if (ui32 == ZIP64_END_OF_CENTRAL_DIR_SIG)
+            return pos-56;
+    } /* if */
+
+    /* Try 84 bytes before the Zip64 end of central directory locator. */
+    /* This works if the record isn't variable length and is version 2. */
+    if (pos > 84)
+    {
+        BAIL_IF_MACRO(!io->seek(io, pos-84), ERRPASS, -1);
+        BAIL_IF_MACRO(!readui32(io, &ui32), ERRPASS, -1);
+        if (ui32 == ZIP64_END_OF_CENTRAL_DIR_SIG)
+            return pos-84;
+    } /* if */
+
+    /* Ok, brute force: we know it's between (offset) and (pos) somewhere. */
+    /*  Just try moving back at most 256k. Oh well. */
+    if ((offset < pos) && (pos > 4))
+    {
+        /* we assume you can eat this stack if you handle Zip64 files. */
+        PHYSFS_uint8 buf[256 * 1024];
+        PHYSFS_uint64 len = pos - offset;
+        PHYSFS_sint32 i;
+
+        if (len > sizeof (buf))
+            len = sizeof (buf);
+
+        BAIL_IF_MACRO(!io->seek(io, pos - len), ERRPASS, -1);
+        BAIL_IF_MACRO(!__PHYSFS_readAll(io, buf, len), ERRPASS, -1);
+        for (i = (PHYSFS_sint32) (len - 4); i >= 0; i--)
+        {
+            if (buf[i] != 0x50)
+                continue;
+            if ( (buf[i+1] == 0x4b) &&
+                 (buf[i+2] == 0x06) &&
+                 (buf[i+3] == 0x06) )
+                return pos - (len - i);
+        } /* for */
+    } /* if */
+
+    BAIL_MACRO(PHYSFS_ERR_CORRUPT, -1);  /* didn't find it. */
+} /* zip64_find_end_of_central_dir */
+
+
+static int zip64_parse_end_of_central_dir(PHYSFS_Io *io, ZIPinfo *info,
+                                          PHYSFS_uint64 *data_start,
+                                          PHYSFS_uint64 *dir_ofs,
+                                          PHYSFS_sint64 pos)
+{
+    PHYSFS_uint64 ui64;
+    PHYSFS_uint32 ui32;
+    PHYSFS_uint16 ui16;
+
+    /* We should be positioned right past the locator signature. */
+
+    if ((pos < 0) || (!io->seek(io, pos)))
+        return 0;
+
+    BAIL_IF_MACRO(!readui32(io, &ui32), ERRPASS, 0);
+    if (ui32 != ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIG)
+        return -1;  /* it's not a Zip64 archive. Not an error, though! */
+
+    info->zip64 = 1;
+
+    /* number of the disk with the start of the central directory. */
+    BAIL_IF_MACRO(!readui32(io, &ui32), ERRPASS, 0);
+    BAIL_IF_MACRO(ui32 != 0, PHYSFS_ERR_CORRUPT, 0);
+
+    /* offset of Zip64 end of central directory record. */
+    BAIL_IF_MACRO(!readui64(io, &ui64), ERRPASS, 0);
+
+    /* total number of disks */
+    BAIL_IF_MACRO(!readui32(io, &ui32), ERRPASS, 0);
+    BAIL_IF_MACRO(ui32 != 1, PHYSFS_ERR_CORRUPT, 0);
+
+    pos = zip64_find_end_of_central_dir(io, pos, ui64);
+    if (pos < 0)
+        return 0;  /* oh well. */
+
+    /*
+     * For self-extracting archives, etc, there's crapola in the file
+     *  before the zipfile records; we calculate how much data there is
+     *  prepended by determining how far the zip64-end-of-central-directory
+     *  offset is from where it is supposed to be...the difference in bytes
+     *  is how much arbitrary data is at the start of the physical file.
+     */
+    assert(((PHYSFS_uint64) pos) >= ui64);
+    *data_start = ((PHYSFS_uint64) pos) - ui64;
+
+    BAIL_IF_MACRO(!io->seek(io, pos), ERRPASS, 0);
+
+    /* check signature again, just in case. */
+    BAIL_IF_MACRO(!readui32(io, &ui32), ERRPASS, 0);
+    BAIL_IF_MACRO(ui32 != ZIP64_END_OF_CENTRAL_DIR_SIG, PHYSFS_ERR_CORRUPT, 0);
+
+    /* size of Zip64 end of central directory record. */
+    BAIL_IF_MACRO(!readui64(io, &ui64), ERRPASS, 0);
+
+    /* version made by. */
+    BAIL_IF_MACRO(!readui16(io, &ui16), ERRPASS, 0);
+
+    /* version needed to extract. */
+    BAIL_IF_MACRO(!readui16(io, &ui16), ERRPASS, 0);
+
+    /* number of this disk. */
+    BAIL_IF_MACRO(!readui32(io, &ui32), ERRPASS, 0);
+    BAIL_IF_MACRO(ui32 != 0, PHYSFS_ERR_CORRUPT, 0);
+
+    /* number of disk with start of central directory record. */
+    BAIL_IF_MACRO(!readui32(io, &ui32), ERRPASS, 0);
+    BAIL_IF_MACRO(ui32 != 0, PHYSFS_ERR_CORRUPT, 0);
+
+    /* total number of entries in the central dir on this disk */
+    BAIL_IF_MACRO(!readui64(io, &ui64), ERRPASS, 0);
+
+    /* total number of entries in the central dir */
+    BAIL_IF_MACRO(!readui64(io, &info->entryCount), ERRPASS, 0);
+    BAIL_IF_MACRO(ui64 != info->entryCount, PHYSFS_ERR_CORRUPT, 0);
+
+    /* size of the central directory */
+    BAIL_IF_MACRO(!readui64(io, &ui64), ERRPASS, 0);
+
+    /* offset of central directory */
+    BAIL_IF_MACRO(!readui64(io, dir_ofs), ERRPASS, 0);
+
+    /* Since we know the difference, fix up the central dir offset... */
+    *dir_ofs += *data_start;
+
+    /*
+     * There are more fields here, for encryption and feature-specific things,
+     *  but we don't care about any of them at the moment.
+     */
+
+    return 1;  /* made it. */
+} /* zip64_parse_end_of_central_dir */
+
+
+static int zip_parse_end_of_central_dir(PHYSFS_Io *io, ZIPinfo *info,
+                                        PHYSFS_uint64 *data_start,
+                                        PHYSFS_uint64 *dir_ofs)
+{
+    PHYSFS_uint16 entryCount16;
+    PHYSFS_uint32 offset32;
+    PHYSFS_uint32 ui32;
+    PHYSFS_uint16 ui16;
+    PHYSFS_sint64 len;
+    PHYSFS_sint64 pos;
+    int rc;
+
+    /* find the end-of-central-dir record, and seek to it. */
+    pos = zip_find_end_of_central_dir(io, &len);
+    BAIL_IF_MACRO(pos == -1, ERRPASS, 0);
+    BAIL_IF_MACRO(!io->seek(io, pos), ERRPASS, 0);
+
+    /* check signature again, just in case. */
+    BAIL_IF_MACRO(!readui32(io, &ui32), ERRPASS, 0);
+    BAIL_IF_MACRO(ui32 != ZIP_END_OF_CENTRAL_DIR_SIG, PHYSFS_ERR_CORRUPT, 0);
+
+    /* Seek back to see if "Zip64 end of central directory locator" exists. */
+    /* this record is 20 bytes before end-of-central-dir */
+    rc = zip64_parse_end_of_central_dir(io, info, data_start, dir_ofs, pos-20);
+    BAIL_IF_MACRO(rc == 0, ERRPASS, 0);
+    if (rc == 1)
+        return 1;  /* we're done here. */
+
+    assert(rc == -1);  /* no error, just not a Zip64 archive. */
+
+    /* Not Zip64? Seek back to where we were and keep processing. */
+    BAIL_IF_MACRO(!io->seek(io, pos + 4), ERRPASS, 0);
+
+    /* number of this disk */
+    BAIL_IF_MACRO(!readui16(io, &ui16), ERRPASS, 0);
+    BAIL_IF_MACRO(ui16 != 0, PHYSFS_ERR_CORRUPT, 0);
+
+    /* number of the disk with the start of the central directory */
+    BAIL_IF_MACRO(!readui16(io, &ui16), ERRPASS, 0);
+    BAIL_IF_MACRO(ui16 != 0, PHYSFS_ERR_CORRUPT, 0);
+
+    /* total number of entries in the central dir on this disk */
+    BAIL_IF_MACRO(!readui16(io, &ui16), ERRPASS, 0);
+
+    /* total number of entries in the central dir */
+    BAIL_IF_MACRO(!readui16(io, &entryCount16), ERRPASS, 0);
+    BAIL_IF_MACRO(ui16 != entryCount16, PHYSFS_ERR_CORRUPT, 0);
+
+    info->entryCount = entryCount16;
+
+    /* size of the central directory */
+    BAIL_IF_MACRO(!readui32(io, &ui32), ERRPASS, 0);
+
+    /* offset of central directory */
+    BAIL_IF_MACRO(!readui32(io, &offset32), ERRPASS, 0);
+    *dir_ofs = (PHYSFS_uint64) offset32;
+    BAIL_IF_MACRO(pos < (*dir_ofs + ui32), PHYSFS_ERR_CORRUPT, 0);
+
+    /*
+     * For self-extracting archives, etc, there's crapola in the file
+     *  before the zipfile records; we calculate how much data there is
+     *  prepended by determining how far the central directory offset is
+     *  from where it is supposed to be (start of end-of-central-dir minus
+     *  sizeof central dir)...the difference in bytes is how much arbitrary
+     *  data is at the start of the physical file.
+     */
+    *data_start = (PHYSFS_uint64) (pos - (*dir_ofs + ui32));
+
+    /* Now that we know the difference, fix up the central dir offset... */
+    *dir_ofs += *data_start;
+
+    /* zipfile comment length */
+    BAIL_IF_MACRO(!readui16(io, &ui16), ERRPASS, 0);
+
+    /*
+     * Make sure that the comment length matches to the end of file...
+     *  If it doesn't, we're either in the wrong part of the file, or the
+     *  file is corrupted, but we give up either way.
+     */
+    BAIL_IF_MACRO((pos + 22 + ui16) != len, PHYSFS_ERR_CORRUPT, 0);
+
+    return 1;  /* made it. */
+} /* zip_parse_end_of_central_dir */
+
+
+static void *ZIP_openArchive(PHYSFS_Io *io, const char *name, int forWriting)
+{
+    ZIPinfo *info = NULL;
+    PHYSFS_uint64 data_start;
+    PHYSFS_uint64 cent_dir_ofs;
+
+    assert(io != NULL);  /* shouldn't ever happen. */
+
+    BAIL_IF_MACRO(forWriting, PHYSFS_ERR_READ_ONLY, NULL);
+    BAIL_IF_MACRO(!isZip(io), ERRPASS, NULL);
+
+    info = (ZIPinfo *) allocator.Malloc(sizeof (ZIPinfo));
+    BAIL_IF_MACRO(!info, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
+    memset(info, '\0', sizeof (ZIPinfo));
+    info->io = io;
+
+    if (!zip_parse_end_of_central_dir(io, info, &data_start, &cent_dir_ofs))
+        goto ZIP_openarchive_failed;
+
+    if (!zip_load_entries(io, info, data_start, cent_dir_ofs))
+        goto ZIP_openarchive_failed;
+
+    return info;
+
+ZIP_openarchive_failed:
+    if (info != NULL)
+        allocator.Free(info);
+
+    return NULL;
+} /* ZIP_openArchive */
+
+
+static PHYSFS_sint64 zip_find_start_of_dir(ZIPinfo *info, const char *path,
+                                            int stop_on_first_find)
+{
+    PHYSFS_sint64 lo = 0;
+    PHYSFS_sint64 hi = (PHYSFS_sint64) (info->entryCount - 1);
+    PHYSFS_sint64 middle;
+    PHYSFS_uint32 dlen = (PHYSFS_uint32) strlen(path);
+    PHYSFS_sint64 retval = -1;
+    const char *name;
+    int rc;
+
+    if (*path == '\0')  /* root dir? */
+        return 0;
+
+    if ((dlen > 0) && (path[dlen - 1] == '/')) /* ignore trailing slash. */
+        dlen--;
+
+    while (lo <= hi)
+    {
+        middle = lo + ((hi - lo) / 2);
+        name = info->entries[middle].name;
+        rc = strncmp(path, name, dlen);
+        if (rc == 0)
+        {
+            char ch = name[dlen];
+            if ('/' < ch) /* make sure this isn't just a substr match. */
+                rc = -1;
+            else if ('/' > ch)
+                rc = 1;
+            else 
+            {
+                if (stop_on_first_find) /* Just checking dir's existance? */
+                    return middle;
+
+                if (name[dlen + 1] == '\0') /* Skip initial dir entry. */
+                    return (middle + 1);
+
+                /* there might be more entries earlier in the list. */
+                retval = middle;
+                hi = middle - 1;
+            } /* else */
+        } /* if */
+
+        if (rc > 0)
+            lo = middle + 1;
+        else
+            hi = middle - 1;
+    } /* while */
+
+    return retval;
+} /* zip_find_start_of_dir */
+
+
+/*
+ * Moved to seperate function so we can use alloca then immediately throw
+ *  away the allocated stack space...
+ */
+static void doEnumCallback(PHYSFS_EnumFilesCallback cb, void *callbackdata,
+                           const char *odir, const char *str, PHYSFS_sint32 ln)
+{
+    char *newstr = __PHYSFS_smallAlloc(ln + 1);
+    if (newstr == NULL)
+        return;
+
+    memcpy(newstr, str, ln);
+    newstr[ln] = '\0';
+    cb(callbackdata, odir, newstr);
+    __PHYSFS_smallFree(newstr);
+} /* doEnumCallback */
+
+
+static void ZIP_enumerateFiles(PHYSFS_Dir *opaque, const char *dname,
+                               int omitSymLinks, PHYSFS_EnumFilesCallback cb,
+                               const char *origdir, void *callbackdata)
+{
+    ZIPinfo *info = ((ZIPinfo *) opaque);
+    PHYSFS_sint32 dlen, dlen_inc;
+    PHYSFS_sint64 i, max;
+
+    i = zip_find_start_of_dir(info, dname, 0);
+    if (i == -1)  /* no such directory. */
+        return;
+
+    dlen = (PHYSFS_sint32) strlen(dname);
+    if ((dlen > 0) && (dname[dlen - 1] == '/')) /* ignore trailing slash. */
+        dlen--;
+
+    dlen_inc = ((dlen > 0) ? 1 : 0) + dlen;
+    max = (PHYSFS_sint64) info->entryCount;
+    while (i < max)
+    {
+        char *e = info->entries[i].name;
+        if ((dlen) && ((strncmp(e, dname, dlen) != 0) || (e[dlen] != '/')))
+            break;  /* past end of this dir; we're done. */
+
+        if ((omitSymLinks) && (zip_entry_is_symlink(&info->entries[i])))
+            i++;
+        else
+        {
+            char *add = e + dlen_inc;
+            char *ptr = strchr(add, '/');
+            PHYSFS_sint32 ln = (PHYSFS_sint32) ((ptr) ? ptr-add : strlen(add));
+            doEnumCallback(cb, callbackdata, origdir, add, ln);
+            ln += dlen_inc;  /* point past entry to children... */
+
+            /* increment counter and skip children of subdirs... */
+            while ((++i < max) && (ptr != NULL))
+            {
+                char *e_new = info->entries[i].name;
+                if ((strncmp(e, e_new, ln) != 0) || (e_new[ln] != '/'))
+                    break;
+            } /* while */
+        } /* else */
+    } /* while */
+} /* ZIP_enumerateFiles */
+
+
+static PHYSFS_Io *zip_get_io(PHYSFS_Io *io, ZIPinfo *inf, ZIPentry *entry)
+{
+    int success;
+    PHYSFS_Io *retval = io->duplicate(io);
+    BAIL_IF_MACRO(!retval, ERRPASS, NULL);
+
+    /* !!! FIXME: if you open a dir here, it should bail ERR_NOT_A_FILE */
+
+    /* (inf) can be NULL if we already resolved. */
+    success = (inf == NULL) || zip_resolve(retval, inf, entry);
+    if (success)
+    {
+        PHYSFS_sint64 offset;
+        offset = ((entry->symlink) ? entry->symlink->offset : entry->offset);
+        success = retval->seek(retval, offset);
+    } /* if */
+
+    if (!success)
+    {
+        retval->destroy(retval);
+        retval = NULL;
+    } /* if */
+
+    return retval;
+} /* zip_get_io */
+
+
+static PHYSFS_Io *ZIP_openRead(PHYSFS_Dir *opaque, const char *fnm,
+                               int *fileExists)
+{
+    PHYSFS_Io *retval = NULL;
+    ZIPinfo *info = (ZIPinfo *) opaque;
+    ZIPentry *entry = zip_find_entry(info, fnm, NULL);
+    ZIPfileinfo *finfo = NULL;
+
+    *fileExists = (entry != NULL);
+    BAIL_IF_MACRO(!entry, ERRPASS, NULL);
+
+    retval = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
+    GOTO_IF_MACRO(!retval, PHYSFS_ERR_OUT_OF_MEMORY, ZIP_openRead_failed);
+
+    finfo = (ZIPfileinfo *) allocator.Malloc(sizeof (ZIPfileinfo));
+    GOTO_IF_MACRO(!finfo, PHYSFS_ERR_OUT_OF_MEMORY, ZIP_openRead_failed);
+    memset(finfo, '\0', sizeof (ZIPfileinfo));
+
+    finfo->io = zip_get_io(info->io, info, entry);
+    GOTO_IF_MACRO(!finfo->io, ERRPASS, ZIP_openRead_failed);
+    finfo->entry = ((entry->symlink != NULL) ? entry->symlink : entry);
+    initializeZStream(&finfo->stream);
+
+    if (finfo->entry->compression_method != COMPMETH_NONE)
+    {
+        finfo->buffer = (PHYSFS_uint8 *) allocator.Malloc(ZIP_READBUFSIZE);
+        if (!finfo->buffer)
+            GOTO_MACRO(PHYSFS_ERR_OUT_OF_MEMORY, ZIP_openRead_failed);
+        else if (zlib_err(inflateInit2(&finfo->stream, -MAX_WBITS)) != Z_OK)
+            goto ZIP_openRead_failed;
+    } /* if */
+
+    memcpy(retval, &ZIP_Io, sizeof (PHYSFS_Io));
+    retval->opaque = finfo;
+
+    return retval;
+
+ZIP_openRead_failed:
+    if (finfo != NULL)
+    {
+        if (finfo->io != NULL)
+            finfo->io->destroy(finfo->io);
+
+        if (finfo->buffer != NULL)
+        {
+            allocator.Free(finfo->buffer);
+            inflateEnd(&finfo->stream);
+        } /* if */
+
+        allocator.Free(finfo);
+    } /* if */
+
+    if (retval != NULL)
+        allocator.Free(retval);
+
+    return NULL;
+} /* ZIP_openRead */
+
+
+static PHYSFS_Io *ZIP_openWrite(PHYSFS_Dir *opaque, const char *filename)
+{
+    BAIL_MACRO(PHYSFS_ERR_READ_ONLY, NULL);
+} /* ZIP_openWrite */
+
+
+static PHYSFS_Io *ZIP_openAppend(PHYSFS_Dir *opaque, const char *filename)
+{
+    BAIL_MACRO(PHYSFS_ERR_READ_ONLY, NULL);
+} /* ZIP_openAppend */
+
+
+static void ZIP_closeArchive(PHYSFS_Dir *opaque)
+{
+    ZIPinfo *zi = (ZIPinfo *) (opaque);
+    zi->io->destroy(zi->io);
+    zip_free_entries(zi->entries, zi->entryCount);
+    allocator.Free(zi);
+} /* ZIP_closeArchive */
+
+
+static int ZIP_remove(PHYSFS_Dir *opaque, const char *name)
+{
+    BAIL_MACRO(PHYSFS_ERR_READ_ONLY, 0);
+} /* ZIP_remove */
+
+
+static int ZIP_mkdir(PHYSFS_Dir *opaque, const char *name)
+{
+    BAIL_MACRO(PHYSFS_ERR_READ_ONLY, 0);
+} /* ZIP_mkdir */
+
+
+static int ZIP_stat(PHYSFS_Dir *opaque, const char *filename, int *exists,
+                    PHYSFS_Stat *stat)
+{
+    int isDir = 0;
+    const ZIPinfo *info = (const ZIPinfo *) opaque;
+    const ZIPentry *entry = zip_find_entry(info, filename, &isDir);
+
+    /* !!! FIXME: does this need to resolve entries here? */
+
+    *exists = isDir || (entry != 0);
+    if (!*exists)
+        return 0;
+
+    if (isDir)
+    {
+        stat->filesize = 0;
+        stat->filetype = PHYSFS_FILETYPE_DIRECTORY;
+    } /* if */
+
+    else if (zip_entry_is_symlink(entry))
+    {
+        stat->filesize = 0;
+        stat->filetype = PHYSFS_FILETYPE_SYMLINK;
+    } /* else if */
+
+    else
+    {
+        stat->filesize = (PHYSFS_sint64) entry->uncompressed_size;
+        stat->filetype = PHYSFS_FILETYPE_REGULAR;
+    } /* else */
+
+    stat->modtime = ((entry) ? entry->last_mod_time : 0);
+    stat->createtime = stat->modtime;
+    stat->accesstime = 0;
+    stat->readonly = 1; /* .zip files are always read only */
+
+    return 1;
+} /* ZIP_stat */
+
+
+const PHYSFS_Archiver __PHYSFS_Archiver_ZIP =
+{
+    {
+        "ZIP",
+        "PkZip/WinZip/Info-Zip compatible",
+        "Ryan C. Gordon <icculus@icculus.org>",
+        "http://icculus.org/physfs/",
+    },
+    ZIP_openArchive,        /* openArchive() method    */
+    ZIP_enumerateFiles,     /* enumerateFiles() method */
+    ZIP_openRead,           /* openRead() method       */
+    ZIP_openWrite,          /* openWrite() method      */
+    ZIP_openAppend,         /* openAppend() method     */
+    ZIP_remove,             /* remove() method         */
+    ZIP_mkdir,              /* mkdir() method          */
+    ZIP_closeArchive,       /* closeArchive() method   */
+    ZIP_stat                /* stat() method           */
+};
+
+#endif  /* defined PHYSFS_SUPPORTS_ZIP */
+
+/* end of zip.c ... */
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/misc/physfs/src/physfs.c	Sat Nov 17 20:30:32 2012 -0500
@@ -0,0 +1,2744 @@
+/**
+ * PhysicsFS; a portable, flexible file i/o abstraction.
+ *
+ * Documentation is in physfs.h. It's verbose, honest.  :)
+ *
+ * Please see the file LICENSE.txt in the source's root directory.
+ *
+ *  This file written by Ryan C. Gordon.
+ */
+
+/* !!! FIXME: ERR_PAST_EOF shouldn't trigger for reads. Just return zero. */
+/* !!! FIXME: use snprintf(), not sprintf(). */
+
+#define __PHYSICSFS_INTERNAL__
+#include "physfs_internal.h"
+
+
+typedef struct __PHYSFS_DIRHANDLE__
+{
+    void *opaque;  /* Instance data unique to the archiver. */
+    char *dirName;  /* Path to archive in platform-dependent notation. */
+    char *mountPoint; /* Mountpoint in virtual file tree. */
+    const PHYSFS_Archiver *funcs;  /* Ptr to archiver info for this handle. */
+    struct __PHYSFS_DIRHANDLE__ *next;  /* linked list stuff. */
+} DirHandle;
+
+
+typedef struct __PHYSFS_FILEHANDLE__
+{
+    PHYSFS_Io *io;  /* Instance data unique to the archiver for this file. */
+    PHYSFS_uint8 forReading; /* Non-zero if reading, zero if write/append */
+    const DirHandle *dirHandle;  /* Archiver instance that created this */
+    PHYSFS_uint8 *buffer;  /* Buffer, if set (NULL otherwise). Don't touch! */
+    PHYSFS_uint32 bufsize;  /* Bufsize, if set (0 otherwise). Don't touch! */
+    PHYSFS_uint32 buffill;  /* Buffer fill size. Don't touch! */
+    PHYSFS_uint32 bufpos;  /* Buffer position. Don't touch! */
+    struct __PHYSFS_FILEHANDLE__ *next;  /* linked list stuff. */
+} FileHandle;
+
+
+typedef struct __PHYSFS_ERRSTATETYPE__
+{
+    void *tid;
+    PHYSFS_ErrorCode code;
+    struct __PHYSFS_ERRSTATETYPE__ *next;
+} ErrState;
+
+
+/* The various i/o drivers...some of these may not be compiled in. */
+extern const PHYSFS_Archiver __PHYSFS_Archiver_ZIP;
+extern const PHYSFS_Archiver __PHYSFS_Archiver_LZMA;
+extern const PHYSFS_Archiver __PHYSFS_Archiver_GRP;
+extern const PHYSFS_Archiver __PHYSFS_Archiver_QPAK;
+extern const PHYSFS_Archiver __PHYSFS_Archiver_HOG;
+extern const PHYSFS_Archiver __PHYSFS_Archiver_MVL;
+extern const PHYSFS_Archiver __PHYSFS_Archiver_WAD;
+extern const PHYSFS_Archiver __PHYSFS_Archiver_DIR;
+extern const PHYSFS_Archiver __PHYSFS_Archiver_ISO9660;
+
+static const PHYSFS_Archiver *staticArchivers[] =
+{
+#if PHYSFS_SUPPORTS_ZIP
+    &__PHYSFS_Archiver_ZIP,
+#endif
+#if PHYSFS_SUPPORTS_7Z
+    &__PHYSFS_Archiver_LZMA,
+#endif
+#if PHYSFS_SUPPORTS_GRP
+    &__PHYSFS_Archiver_GRP,
+#endif
+#if PHYSFS_SUPPORTS_QPAK
+    &__PHYSFS_Archiver_QPAK,
+#endif
+#if PHYSFS_SUPPORTS_HOG
+    &__PHYSFS_Archiver_HOG,
+#endif
+#if PHYSFS_SUPPORTS_MVL
+    &__PHYSFS_Archiver_MVL,
+#endif
+#if PHYSFS_SUPPORTS_WAD
+    &__PHYSFS_Archiver_WAD,
+#endif
+#if PHYSFS_SUPPORTS_ISO9660
+    &__PHYSFS_Archiver_ISO9660,
+#endif
+    NULL
+};
+
+
+
+/* General PhysicsFS state ... */
+static int initialized = 0;
+static ErrState *errorStates = NULL;
+static DirHandle *searchPath = NULL;
+static DirHandle *writeDir = NULL;
+static FileHandle *openWriteList = NULL;
+static FileHandle *openReadList = NULL;
+static char *baseDir = NULL;
+static char *userDir = NULL;
+static char *prefDir = NULL;
+static int allowSymLinks = 0;
+static const PHYSFS_Archiver **archivers = NULL;
+static const PHYSFS_ArchiveInfo **archiveInfo = NULL;
+
+/* mutexes ... */
+static void *errorLock = NULL;     /* protects error message list.        */
+static void *stateLock = NULL;     /* protects other PhysFS static state. */
+
+/* allocator ... */
+static int externalAllocator = 0;
+PHYSFS_Allocator allocator;
+
+
+/* PHYSFS_Io implementation for i/o to physical filesystem... */
+
+/* !!! FIXME: maybe refcount the paths in a string pool? */
+typedef struct __PHYSFS_NativeIoInfo
+{
+    void *handle;
+    const char *path;
+    int mode;   /* 'r', 'w', or 'a' */
+} NativeIoInfo;
+
+static PHYSFS_sint64 nativeIo_read(PHYSFS_Io *io, void *buf, PHYSFS_uint64 len)
+{
+    NativeIoInfo *info = (NativeIoInfo *) io->opaque;
+    return __PHYSFS_platformRead(info->handle, buf, len);
+} /* nativeIo_read */
+
+static PHYSFS_sint64 nativeIo_write(PHYSFS_Io *io, const void *buffer,
+                                    PHYSFS_uint64 len)
+{
+    NativeIoInfo *info = (NativeIoInfo *) io->opaque;
+    return __PHYSFS_platformWrite(info->handle, buffer, len);
+} /* nativeIo_write */
+
+static int nativeIo_seek(PHYSFS_Io *io, PHYSFS_uint64 offset)
+{
+    NativeIoInfo *info = (NativeIoInfo *) io->opaque;
+    return __PHYSFS_platformSeek(info->handle, offset);
+} /* nativeIo_seek */
+
+static PHYSFS_sint64 nativeIo_tell(PHYSFS_Io *io)
+{
+    NativeIoInfo *info = (NativeIoInfo *) io->opaque;
+    return __PHYSFS_platformTell(info->handle);
+} /* nativeIo_tell */
+
+static PHYSFS_sint64 nativeIo_length(PHYSFS_Io *io)
+{
+    NativeIoInfo *info = (NativeIoInfo *) io->opaque;
+    return __PHYSFS_platformFileLength(info->handle);
+} /* nativeIo_length */
+
+static PHYSFS_Io *nativeIo_duplicate(PHYSFS_Io *io)
+{
+    NativeIoInfo *info = (NativeIoInfo *) io->opaque;
+    return __PHYSFS_createNativeIo(info->path, info->mode);
+} /* nativeIo_duplicate */
+
+static int nativeIo_flush(PHYSFS_Io *io)
+{
+    return __PHYSFS_platformFlush(io->opaque);
+} /* nativeIo_flush */
+
+static void nativeIo_destroy(PHYSFS_Io *io)
+{
+    NativeIoInfo *info = (NativeIoInfo *) io->opaque;
+    __PHYSFS_platformClose(info->handle);
+    allocator.Free((void *) info->path);
+    allocator.Free(info);
+    allocator.Free(io);
+} /* nativeIo_destroy */
+
+static const PHYSFS_Io __PHYSFS_nativeIoInterface =
+{
+    CURRENT_PHYSFS_IO_API_VERSION, NULL,
+    nativeIo_read,
+    nativeIo_write,
+    nativeIo_seek,
+    nativeIo_tell,
+    nativeIo_length,
+    nativeIo_duplicate,
+    nativeIo_flush,
+    nativeIo_destroy
+};
+
+PHYSFS_Io *__PHYSFS_createNativeIo(const char *path, const int mode)
+{
+    PHYSFS_Io *io = NULL;
+    NativeIoInfo *info = NULL;
+    void *handle = NULL;
+    char *pathdup = NULL;
+
+    assert((mode == 'r') || (mode == 'w') || (mode == 'a'));
+
+    io = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
+    GOTO_IF_MACRO(!io, PHYSFS_ERR_OUT_OF_MEMORY, createNativeIo_failed);
+    info = (NativeIoInfo *) allocator.Malloc(sizeof (NativeIoInfo));
+    GOTO_IF_MACRO(!info, PHYSFS_ERR_OUT_OF_MEMORY, createNativeIo_failed);
+    pathdup = (char *) allocator.Malloc(strlen(path) + 1);
+    GOTO_IF_MACRO(!pathdup, PHYSFS_ERR_OUT_OF_MEMORY, createNativeIo_failed);
+
+    if (mode == 'r')
+        handle = __PHYSFS_platformOpenRead(path);
+    else if (mode == 'w')
+        handle = __PHYSFS_platformOpenWrite(path);
+    else if (mode == 'a')
+        handle = __PHYSFS_platformOpenAppend(path);
+
+    GOTO_IF_MACRO(!handle, ERRPASS, createNativeIo_failed);
+
+    strcpy(pathdup, path);
+    info->handle = handle;
+    info->path = pathdup;
+    info->mode = mode;
+    memcpy(io, &__PHYSFS_nativeIoInterface, sizeof (*io));
+    io->opaque = info;
+    return io;
+
+createNativeIo_failed:
+    if (handle != NULL) __PHYSFS_platformClose(handle);
+    if (pathdup != NULL) allocator.Free(pathdup);
+    if (info != NULL) allocator.Free(info);
+    if (io != NULL) allocator.Free(io);
+    return NULL;
+} /* __PHYSFS_createNativeIo */
+
+
+/* PHYSFS_Io implementation for i/o to a memory buffer... */
+
+typedef struct __PHYSFS_MemoryIoInfo
+{
+    const PHYSFS_uint8 *buf;
+    PHYSFS_uint64 len;
+    PHYSFS_uint64 pos;
+    PHYSFS_Io *parent;
+    volatile PHYSFS_uint32 refcount;
+    void (*destruct)(void *);
+} MemoryIoInfo;
+
+static PHYSFS_sint64 memoryIo_read(PHYSFS_Io *io, void *buf, PHYSFS_uint64 len)
+{
+    MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
+    const PHYSFS_uint64 avail = info->len - info->pos;
+    assert(avail <= info->len);
+
+    if (avail == 0)
+        return 0;  /* we're at EOF; nothing to do. */
+
+    if (len > avail)
+        len = avail;
+
+    memcpy(buf, info->buf + info->pos, (size_t) len);
+    info->pos += len;
+    return len;
+} /* memoryIo_read */
+
+static PHYSFS_sint64 memoryIo_write(PHYSFS_Io *io, const void *buffer,
+                                    PHYSFS_uint64 len)
+{
+    BAIL_MACRO(PHYSFS_ERR_OPEN_FOR_READING, -1);
+} /* memoryIo_write */
+
+static int memoryIo_seek(PHYSFS_Io *io, PHYSFS_uint64 offset)
+{
+    MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
+    BAIL_IF_MACRO(offset > info->len, PHYSFS_ERR_PAST_EOF, 0);
+    info->pos = offset;
+    return 1;
+} /* memoryIo_seek */
+
+static PHYSFS_sint64 memoryIo_tell(PHYSFS_Io *io)
+{
+    const MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
+    return (PHYSFS_sint64) info->pos;
+} /* memoryIo_tell */
+
+static PHYSFS_sint64 memoryIo_length(PHYSFS_Io *io)
+{
+    const MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
+    return (PHYSFS_sint64) info->len;
+} /* memoryIo_length */
+
+static PHYSFS_Io *memoryIo_duplicate(PHYSFS_Io *io)
+{
+    MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
+    MemoryIoInfo *newinfo = NULL;
+    PHYSFS_Io *parent = info->parent;
+    PHYSFS_Io *retval = NULL;
+
+    /* avoid deep copies. */
+    assert((!parent) || (!((MemoryIoInfo *) parent->opaque)->parent) );
+
+    /* share the buffer between duplicates. */
+    if (parent != NULL)  /* dup the parent, increment its refcount. */
+        return parent->duplicate(parent);
+
+    /* we're the parent. */
+
+    retval = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
+    BAIL_IF_MACRO(!retval, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
+    newinfo = (MemoryIoInfo *) allocator.Malloc(sizeof (MemoryIoInfo));
+    if (!newinfo)
+    {
+        allocator.Free(retval);
+        BAIL_MACRO(PHYSFS_ERR_OUT_OF_MEMORY, NULL);
+    } /* if */
+
+    /* !!! FIXME: want lockless atomic increment. */
+    __PHYSFS_platformGrabMutex(stateLock);
+    info->refcount++;
+    __PHYSFS_platformReleaseMutex(stateLock);
+
+    memset(newinfo, '\0', sizeof (*info));
+    newinfo->buf = info->buf;
+    newinfo->len = info->len;
+    newinfo->pos = 0;
+    newinfo->parent = io;
+    newinfo->refcount = 0;
+    newinfo->destruct = NULL;
+
+    memcpy(retval, io, sizeof (*retval));
+    retval->opaque = newinfo;
+    return retval;
+} /* memoryIo_duplicate */
+
+static int memoryIo_flush(PHYSFS_Io *io) { return 1;  /* it's read-only. */ }
+
+static void memoryIo_destroy(PHYSFS_Io *io)
+{
+    MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
+    PHYSFS_Io *parent = info->parent;
+    int should_die = 0;
+
+    if (parent != NULL)
+    {
+        assert(info->buf == ((MemoryIoInfo *) info->parent->opaque)->buf);
+        assert(info->len == ((MemoryIoInfo *) info->parent->opaque)->len);
+        assert(info->refcount == 0);
+        assert(info->destruct == NULL);
+        allocator.Free(info);
+        allocator.Free(io);
+        parent->destroy(parent);  /* decrements refcount. */
+        return;
+    } /* if */
+
+    /* we _are_ the parent. */
+    assert(info->refcount > 0);  /* even in a race, we hold a reference. */
+
+    /* !!! FIXME: want lockless atomic decrement. */
+    __PHYSFS_platformGrabMutex(stateLock);
+    info->refcount--;
+    should_die = (info->refcount == 0);
+    __PHYSFS_platformReleaseMutex(stateLock);
+
+    if (should_die)
+    {
+        void (*destruct)(void *) = info->destruct;
+        void *buf = (void *) info->buf;
+        io->opaque = NULL;  /* kill this here in case of race. */
+        allocator.Free(info);
+        allocator.Free(io);
+        if (destruct != NULL)
+            destruct(buf);
+    } /* if */
+} /* memoryIo_destroy */
+
+
+static const PHYSFS_Io __PHYSFS_memoryIoInterface =
+{
+    CURRENT_PHYSFS_IO_API_VERSION, NULL,
+    memoryIo_read,
+    memoryIo_write,
+    memoryIo_seek,
+    memoryIo_tell,
+    memoryIo_length,
+    memoryIo_duplicate,
+    memoryIo_flush,
+    memoryIo_destroy
+};
+
+PHYSFS_Io *__PHYSFS_createMemoryIo(const void *buf, PHYSFS_uint64 len,
+                                   void (*destruct)(void *))
+{
+    PHYSFS_Io *io = NULL;
+    MemoryIoInfo *info = NULL;
+
+    io = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
+    GOTO_IF_MACRO(!io, PHYSFS_ERR_OUT_OF_MEMORY, createMemoryIo_failed);
+    info = (MemoryIoInfo *) allocator.Malloc(sizeof (MemoryIoInfo));
+    GOTO_IF_MACRO(!info, PHYSFS_ERR_OUT_OF_MEMORY, createMemoryIo_failed);
+
+    memset(info, '\0', sizeof (*info));
+    info->buf = (const PHYSFS_uint8 *) buf;
+    info->len = len;
+    info->pos = 0;
+    info->parent = NULL;
+    info->refcount = 1;
+    info->destruct = destruct;
+
+    memcpy(io, &__PHYSFS_memoryIoInterface, sizeof (*io));
+    io->opaque = info;
+    return io;
+
+createMemoryIo_failed:
+    if (info != NULL) allocator.Free(info);
+    if (io != NULL) allocator.Free(io);
+    return NULL;
+} /* __PHYSFS_createMemoryIo */
+
+
+/* PHYSFS_Io implementation for i/o to a PHYSFS_File... */
+
+static PHYSFS_sint64 handleIo_read(PHYSFS_Io *io, void *buf, PHYSFS_uint64 len)
+{
+    return PHYSFS_readBytes((PHYSFS_File *) io->opaque, buf, len);
+} /* handleIo_read */
+
+static PHYSFS_sint64 handleIo_write(PHYSFS_Io *io, const void *buffer,
+                                    PHYSFS_uint64 len)
+{
+    return PHYSFS_writeBytes((PHYSFS_File *) io->opaque, buffer, len);
+} /* handleIo_write */
+
+static int handleIo_seek(PHYSFS_Io *io, PHYSFS_uint64 offset)
+{
+    return PHYSFS_seek((PHYSFS_File *) io->opaque, offset);
+} /* handleIo_seek */
+
+static PHYSFS_sint64 handleIo_tell(PHYSFS_Io *io)
+{
+    return PHYSFS_tell((PHYSFS_File *) io->opaque);
+} /* handleIo_tell */
+
+static PHYSFS_sint64 handleIo_length(PHYSFS_Io *io)
+{
+    return PHYSFS_fileLength((PHYSFS_File *) io->opaque);
+} /* handleIo_length */
+
+static PHYSFS_Io *handleIo_duplicate(PHYSFS_Io *io)
+{
+    /*
+     * There's no duplicate at the PHYSFS_File level, so we break the
+     *  abstraction. We're allowed to: we're physfs.c!
+     */
+    FileHandle *origfh = (FileHandle *) io->opaque;
+    FileHandle *newfh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
+    PHYSFS_Io *retval = NULL;
+
+    GOTO_IF_MACRO(!newfh, PHYSFS_ERR_OUT_OF_MEMORY, handleIo_dupe_failed);
+    memset(newfh, '\0', sizeof (*newfh));
+
+    retval = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
+    GOTO_IF_MACRO(!retval, PHYSFS_ERR_OUT_OF_MEMORY, handleIo_dupe_failed);
+
+#if 0  /* we don't buffer the duplicate, at least not at the moment. */
+    if (origfh->buffer != NULL)
+    {
+        newfh->buffer = (PHYSFS_uint8 *) allocator.Malloc(origfh->bufsize);
+        if (!newfh->buffer)
+            GOTO_MACRO(PHYSFS_ERR_OUT_OF_MEMORY, handleIo_dupe_failed);
+        newfh->bufsize = origfh->bufsize;
+    } /* if */
+#endif
+
+    newfh->io = origfh->io->duplicate(origfh->io);
+    GOTO_IF_MACRO(!newfh->io, ERRPASS, handleIo_dupe_failed);
+
+    newfh->forReading = origfh->forReading;
+    newfh->dirHandle = origfh->dirHandle;
+
+    __PHYSFS_platformGrabMutex(stateLock);
+    if (newfh->forReading)
+    {
+        newfh->next = openReadList;
+        openReadList = newfh;
+    } /* if */
+    else
+    {
+        newfh->next = openWriteList;
+        openWriteList = newfh;
+    } /* else */
+    __PHYSFS_platformReleaseMutex(stateLock);
+
+    memcpy(retval, io, sizeof (PHYSFS_Io));
+    retval->opaque = newfh;
+    return retval;
+    
+handleIo_dupe_failed:
+    if (newfh)
+    {
+        if (newfh->io != NULL) newfh->io->destroy(newfh->io);
+        if (newfh->buffer != NULL) allocator.Free(newfh->buffer);
+        allocator.Free(newfh);
+    } /* if */
+
+    return NULL;
+} /* handleIo_duplicate */
+
+static int handleIo_flush(PHYSFS_Io *io)
+{
+    return PHYSFS_flush((PHYSFS_File *) io->opaque);
+} /* handleIo_flush */
+
+static void handleIo_destroy(PHYSFS_Io *io)
+{
+    if (io->opaque != NULL)
+        PHYSFS_close((PHYSFS_File *) io->opaque);
+    allocator.Free(io);
+} /* handleIo_destroy */
+
+static const PHYSFS_Io __PHYSFS_handleIoInterface =
+{
+    CURRENT_PHYSFS_IO_API_VERSION, NULL,
+    handleIo_read,
+    handleIo_write,
+    handleIo_seek,
+    handleIo_tell,
+    handleIo_length,
+    handleIo_duplicate,
+    handleIo_flush,
+    handleIo_destroy
+};
+
+static PHYSFS_Io *__PHYSFS_createHandleIo(PHYSFS_File *f)
+{
+    PHYSFS_Io *io = (PHYSFS_Io *) allocator.Malloc(sizeof (PHYSFS_Io));
+    BAIL_IF_MACRO(!io, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
+    memcpy(io, &__PHYSFS_handleIoInterface, sizeof (*io));
+    io->opaque = f;
+    return io;
+} /* __PHYSFS_createHandleIo */
+
+
+/* functions ... */
+
+typedef struct
+{
+    char **list;
+    PHYSFS_uint32 size;
+    PHYSFS_ErrorCode errcode;
+} EnumStringListCallbackData;
+
+static void enumStringListCallback(void *data, const char *str)
+{
+    void *ptr;
+    char *newstr;
+    EnumStringListCallbackData *pecd = (EnumStringListCallbackData *) data;
+
+    if (pecd->errcode)
+        return;
+
+    ptr = allocator.Realloc(pecd->list, (pecd->size + 2) * sizeof (char *));
+    newstr = (char *) allocator.Malloc(strlen(str) + 1);
+    if (ptr != NULL)
+        pecd->list = (char **) ptr;
+
+    if ((ptr == NULL) || (newstr == NULL))
+    {
+        pecd->errcode = PHYSFS_ERR_OUT_OF_MEMORY;
+        pecd->list[pecd->size] = NULL;
+        PHYSFS_freeList(pecd->list);
+        return;
+    } /* if */
+
+    strcpy(newstr, str);
+    pecd->list[pecd->size] = newstr;
+    pecd->size++;
+} /* enumStringListCallback */
+
+
+static char **doEnumStringList(void (*func)(PHYSFS_StringCallback, void *))
+{
+    EnumStringListCallbackData ecd;
+    memset(&ecd, '\0', sizeof (ecd));
+    ecd.list = (char **) allocator.Malloc(sizeof (char *));
+    BAIL_IF_MACRO(!ecd.list, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
+    func(enumStringListCallback, &ecd);
+
+    if (ecd.errcode)
+    {
+        __PHYSFS_setError(ecd.errcode);
+        return NULL;
+    } /* if */
+
+    ecd.list[ecd.size] = NULL;
+    return ecd.list;
+} /* doEnumStringList */
+
+
+static void __PHYSFS_bubble_sort(void *a, size_t lo, size_t hi,
+                                 int (*cmpfn)(void *, size_t, size_t),
+                                 void (*swapfn)(void *, size_t, size_t))
+{
+    size_t i;
+    int sorted;
+
+    do
+    {
+        sorted = 1;
+        for (i = lo; i < hi; i++)
+        {
+            if (cmpfn(a, i, i + 1) > 0)
+            {
+                swapfn(a, i, i + 1);
+                sorted = 0;
+            } /* if */
+        } /* for */
+    } while (!sorted);
+} /* __PHYSFS_bubble_sort */
+
+
+static void __PHYSFS_quick_sort(void *a, size_t lo, size_t hi,
+                         int (*cmpfn)(void *, size_t, size_t),
+                         void (*swapfn)(void *, size_t, size_t))
+{
+    size_t i;
+    size_t j;
+    size_t v;
+
+    if ((hi - lo) <= PHYSFS_QUICKSORT_THRESHOLD)
+        __PHYSFS_bubble_sort(a, lo, hi, cmpfn, swapfn);
+    else
+    {
+        i = (hi + lo) / 2;
+
+        if (cmpfn(a, lo, i) > 0) swapfn(a, lo, i);
+        if (cmpfn(a, lo, hi) > 0) swapfn(a, lo, hi);
+        if (cmpfn(a, i, hi) > 0) swapfn(a, i, hi);
+
+        j = hi - 1;
+        swapfn(a, i, j);
+        i = lo;
+        v = j;
+        while (1)
+        {
+            while(cmpfn(a, ++i, v) < 0) { /* do nothing */ }
+            while(cmpfn(a, --j, v) > 0) { /* do nothing */ }
+            if (j < i)
+                break;
+            swapfn(a, i, j);
+        } /* while */
+        if (i != (hi-1))
+            swapfn(a, i, hi-1);
+        __PHYSFS_quick_sort(a, lo, j, cmpfn, swapfn);
+        __PHYSFS_quick_sort(a, i+1, hi, cmpfn, swapfn);
+    } /* else */
+} /* __PHYSFS_quick_sort */
+
+
+void __PHYSFS_sort(void *entries, size_t max,
+                   int (*cmpfn)(void *, size_t, size_t),
+                   void (*swapfn)(void *, size_t, size_t))
+{
+    /*
+     * Quicksort w/ Bubblesort fallback algorithm inspired by code from here:
+     *   http://www.cs.ubc.ca/spider/harrison/Java/sorting-demo.html
+     */
+    if (max > 0)
+        __PHYSFS_quick_sort(entries, 0, max - 1, cmpfn, swapfn);
+} /* __PHYSFS_sort */
+
+
+static ErrState *findErrorForCurrentThread(void)
+{
+    ErrState *i;
+    void *tid;
+
+    if (errorLock != NULL)
+        __PHYSFS_platformGrabMutex(errorLock);
+
+    if (errorStates != NULL)
+    {
+        tid = __PHYSFS_platformGetThreadID();
+
+        for (i = errorStates; i != NULL; i = i->next)
+        {
+            if (i->tid == tid)
+            {
+                if (errorLock != NULL)
+                    __PHYSFS_platformReleaseMutex(errorLock);
+                return i;
+            } /* if */
+        } /* for */
+    } /* if */
+
+    if (errorLock != NULL)
+        __PHYSFS_platformReleaseMutex(errorLock);
+
+    return NULL;   /* no error available. */
+} /* findErrorForCurrentThread */
+
+
+void __PHYSFS_setError(const PHYSFS_ErrorCode errcode)
+{
+    ErrState *err;
+
+    if (!errcode)
+        return;
+
+    err = findErrorForCurrentThread();
+    if (err == NULL)
+    {
+        err = (ErrState *) allocator.Malloc(sizeof (ErrState));
+        if (err == NULL)
+            return;   /* uhh...? */
+
+        memset(err, '\0', sizeof (ErrState));
+        err->tid = __PHYSFS_platformGetThreadID();
+
+        if (errorLock != NULL)
+            __PHYSFS_platformGrabMutex(errorLock);
+
+        err->next = errorStates;
+        errorStates = err;
+
+        if (errorLock != NULL)
+            __PHYSFS_platformReleaseMutex(errorLock);
+    } /* if */
+
+    err->code = errcode;
+} /* __PHYSFS_setError */
+
+
+PHYSFS_ErrorCode PHYSFS_getLastErrorCode(void)
+{
+    ErrState *err = findErrorForCurrentThread();
+    const PHYSFS_ErrorCode retval = (err) ? err->code : PHYSFS_ERR_OK;
+    if (err)
+        err->code = PHYSFS_ERR_OK;
+    return retval;
+} /* PHYSFS_getLastErrorCode */
+
+
+PHYSFS_DECL const char *PHYSFS_getErrorByCode(PHYSFS_ErrorCode code)
+{
+    switch (code)
+    {
+        case PHYSFS_ERR_OK: return "no error";
+        case PHYSFS_ERR_OTHER_ERROR: return "unknown error";
+        case PHYSFS_ERR_OUT_OF_MEMORY: return "out of memory";
+        case PHYSFS_ERR_NOT_INITIALIZED: return "not initialized";
+        case PHYSFS_ERR_IS_INITIALIZED: return "already initialized";
+        case PHYSFS_ERR_ARGV0_IS_NULL: return "argv[0] is NULL";
+        case PHYSFS_ERR_UNSUPPORTED: return "unsupported";
+        case PHYSFS_ERR_PAST_EOF: return "past end of file";
+        case PHYSFS_ERR_FILES_STILL_OPEN: return "files still open";
+        case PHYSFS_ERR_INVALID_ARGUMENT: return "invalid argument";
+        case PHYSFS_ERR_NOT_MOUNTED: return "not mounted";
+        case PHYSFS_ERR_NO_SUCH_PATH: return "no such path";
+        case PHYSFS_ERR_SYMLINK_FORBIDDEN: return "symlinks are forbidden";
+        case PHYSFS_ERR_NO_WRITE_DIR: return "write directory is not set";
+        case PHYSFS_ERR_OPEN_FOR_READING: return "file open for reading";
+        case PHYSFS_ERR_OPEN_FOR_WRITING: return "file open for writing";
+        case PHYSFS_ERR_NOT_A_FILE: return "not a file";
+        case PHYSFS_ERR_READ_ONLY: return "read-only filesystem";
+        case PHYSFS_ERR_CORRUPT: return "corrupted";
+        case PHYSFS_ERR_SYMLINK_LOOP: return "infinite symbolic link loop";
+        case PHYSFS_ERR_IO: return "i/o error";
+        case PHYSFS_ERR_PERMISSION: return "permission denied";
+        case PHYSFS_ERR_NO_SPACE: return "no space available for writing";
+        case PHYSFS_ERR_BAD_FILENAME: return "filename is illegal or insecure";
+        case PHYSFS_ERR_BUSY: return "tried to modify a file the OS needs";
+        case PHYSFS_ERR_DIR_NOT_EMPTY: return "directory isn't empty";
+        case PHYSFS_ERR_OS_ERROR: return "OS reported an error";
+    } /* switch */
+
+    return NULL;  /* don't know this error code. */
+} /* PHYSFS_getErrorByCode */
+
+
+void PHYSFS_setErrorCode(PHYSFS_ErrorCode code)
+{
+    __PHYSFS_setError(code);
+} /* PHYSFS_setErrorCode */
+
+
+const char *PHYSFS_getLastError(void)
+{
+    const PHYSFS_ErrorCode err = PHYSFS_getLastErrorCode();
+    return (err) ? PHYSFS_getErrorByCode(err) : NULL;
+} /* PHYSFS_getLastError */
+
+
+/* MAKE SURE that errorLock is held before calling this! */
+static void freeErrorStates(void)
+{
+    ErrState *i;
+    ErrState *next;
+
+    for (i = errorStates; i != NULL; i = next)
+    {
+        next = i->next;
+        allocator.Free(i);
+    } /* for */
+
+    errorStates = NULL;
+} /* freeErrorStates */
+
+
+void PHYSFS_getLinkedVersion(PHYSFS_Version *ver)
+{
+    if (ver != NULL)
+    {
+        ver->major = PHYSFS_VER_MAJOR;
+        ver->minor = PHYSFS_VER_MINOR;
+        ver->patch = PHYSFS_VER_PATCH;
+    } /* if */
+} /* PHYSFS_getLinkedVersion */
+
+
+static const char *find_filename_extension(const char *fname)
+{
+    const char *retval = NULL;
+    if (fname != NULL)
+    {
+        const char *p = strchr(fname, '.');
+        retval = p;
+
+        while (p != NULL)
+        {
+            p = strchr(p + 1, '.');
+            if (p != NULL)
+                retval = p;
+        } /* while */
+
+        if (retval != NULL)
+            retval++;  /* skip '.' */
+    } /* if */
+
+    return retval;
+} /* find_filename_extension */
+
+
+static DirHandle *tryOpenDir(PHYSFS_Io *io, const PHYSFS_Archiver *funcs,
+                             const char *d, int forWriting)
+{
+    DirHandle *retval = NULL;
+    void *opaque = NULL;
+
+    if (io != NULL)
+        BAIL_IF_MACRO(!io->seek(io, 0), ERRPASS, NULL);
+
+    opaque = funcs->openArchive(io, d, forWriting);
+    if (opaque != NULL)
+    {
+        retval = (DirHandle *) allocator.Malloc(sizeof (DirHandle));
+        if (retval == NULL)
+            funcs->closeArchive(opaque);
+        else
+        {
+            memset(retval, '\0', sizeof (DirHandle));
+            retval->mountPoint = NULL;
+            retval->funcs = funcs;
+            retval->opaque = opaque;
+        } /* else */
+    } /* if */
+
+    return retval;
+} /* tryOpenDir */
+
+
+static DirHandle *openDirectory(PHYSFS_Io *io, const char *d, int forWriting)
+{
+    DirHandle *retval = NULL;
+    const PHYSFS_Archiver **i;
+    const char *ext;
+
+    assert((io != NULL) || (d != NULL));
+
+    if (io == NULL)
+    {
+        /* DIR gets first shot (unlike the rest, it doesn't deal with files). */
+        retval = tryOpenDir(io, &__PHYSFS_Archiver_DIR, d, forWriting);
+        if (retval != NULL)
+            return retval;
+
+        io = __PHYSFS_createNativeIo(d, forWriting ? 'w' : 'r');
+        BAIL_IF_MACRO(!io, ERRPASS, 0);
+    } /* if */
+
+    ext = find_filename_extension(d);
+    if (ext != NULL)
+    {
+        /* Look for archivers with matching file extensions first... */
+        for (i = archivers; (*i != NULL) && (retval == NULL); i++)
+        {
+            if (__PHYSFS_stricmpASCII(ext, (*i)->info.extension) == 0)
+                retval = tryOpenDir(io, *i, d, forWriting);
+        } /* for */
+
+        /* failing an exact file extension match, try all the others... */
+        for (i = archivers; (*i != NULL) && (retval == NULL); i++)
+        {
+            if (__PHYSFS_stricmpASCII(ext, (*i)->info.extension) != 0)
+                retval = tryOpenDir(io, *i, d, forWriting);
+        } /* for */
+    } /* if */
+
+    else  /* no extension? Try them all. */
+    {
+        for (i = archivers; (*i != NULL) && (retval == NULL); i++)
+            retval = tryOpenDir(io, *i, d, forWriting);
+    } /* else */
+
+    BAIL_IF_MACRO(!retval, PHYSFS_ERR_UNSUPPORTED, NULL);
+    return retval;
+} /* openDirectory */
+
+
+/*
+ * Make a platform-independent path string sane. Doesn't actually check the
+ *  file hierarchy, it just cleans up the string.
+ *  (dst) must be a buffer at least as big as (src), as this is where the
+ *  cleaned up string is deposited.
+ * If there are illegal bits in the path (".." entries, etc) then we
+ *  return zero and (dst) is undefined. Non-zero if the path was sanitized.
+ */
+static int sanitizePlatformIndependentPath(const char *src, char *dst)
+{
+    char *prev;
+    char ch;
+
+    while (*src == '/')  /* skip initial '/' chars... */
+        src++;
+
+    prev = dst;
+    do
+    {
+        ch = *(src++);
+
+        if ((ch == ':') || (ch == '\\'))  /* illegal chars in a physfs path. */
+            BAIL_MACRO(PHYSFS_ERR_BAD_FILENAME, 0);
+
+        if (ch == '/')   /* path separator. */
+        {
+            *dst = '\0';  /* "." and ".." are illegal pathnames. */
+            if ((strcmp(prev, ".") == 0) || (strcmp(prev, "..") == 0))
+                BAIL_MACRO(PHYSFS_ERR_BAD_FILENAME, 0);
+
+            while (*src == '/')   /* chop out doubles... */
+                src++;
+
+            if (*src == '\0') /* ends with a pathsep? */
+                break;  /* we're done, don't add final pathsep to dst. */
+
+            prev = dst + 1;
+        } /* if */
+
+        *(dst++) = ch;
+    } while (ch != '\0');
+
+    return 1;
+} /* sanitizePlatformIndependentPath */
+
+
+/*
+ * Figure out if (fname) is part of (h)'s mountpoint. (fname) must be an
+ *  output from sanitizePlatformIndependentPath(), so that it is in a known
+ *  state.
+ *
+ * This only finds legitimate segments of a mountpoint. If the mountpoint is
+ *  "/a/b/c" and (fname) is "/a/b/c", "/", or "/a/b/c/d", then the results are
+ *  all zero. "/a/b" will succeed, though.
+ */
+static int partOfMountPoint(DirHandle *h, char *fname)
+{
+    /* !!! FIXME: This code feels gross. */
+    int rc;
+    size_t len, mntpntlen;
+
+    if (h->mountPoint == NULL)
+        return 0;
+    else if (*fname == '\0')
+        return 1;
+
+    len = strlen(fname);
+    mntpntlen = strlen(h->mountPoint);
+    if (len > mntpntlen)  /* can't be a subset of mountpoint. */
+        return 0;
+
+    /* if true, must be not a match or a complete match, but not a subset. */
+    if ((len + 1) == mntpntlen)
+        return 0;
+
+    rc = strncmp(fname, h->mountPoint, len); /* !!! FIXME: case insensitive? */
+    if (rc != 0)
+        return 0;  /* not a match. */
+
+    /* make sure /a/b matches /a/b/ and not /a/bc ... */
+    return h->mountPoint[len] == '/';
+} /* partOfMountPoint */
+
+
+static DirHandle *createDirHandle(PHYSFS_Io *io, const char *newDir,
+                                  const char *mountPoint, int forWriting)
+{
+    DirHandle *dirHandle = NULL;
+    char *tmpmntpnt = NULL;
+
+    if (mountPoint != NULL)
+    {
+        const size_t len = strlen(mountPoint) + 1;
+        tmpmntpnt = (char *) __PHYSFS_smallAlloc(len);
+        GOTO_IF_MACRO(!tmpmntpnt, PHYSFS_ERR_OUT_OF_MEMORY, badDirHandle);
+        if (!sanitizePlatformIndependentPath(mountPoint, tmpmntpnt))
+            goto badDirHandle;
+        mountPoint = tmpmntpnt;  /* sanitized version. */
+    } /* if */
+
+    dirHandle = openDirectory(io, newDir, forWriting);
+    GOTO_IF_MACRO(!dirHandle, ERRPASS, badDirHandle);
+
+    if (newDir == NULL)
+        dirHandle->dirName = NULL;
+    else
+    {
+        dirHandle->dirName = (char *) allocator.Malloc(strlen(newDir) + 1);
+        if (!dirHandle->dirName)
+            GOTO_MACRO(PHYSFS_ERR_OUT_OF_MEMORY, badDirHandle);
+        strcpy(dirHandle->dirName, newDir);
+    } /* else */
+
+    if ((mountPoint != NULL) && (*mountPoint != '\0'))
+    {
+        dirHandle->mountPoint = (char *)allocator.Malloc(strlen(mountPoint)+2);
+        if (!dirHandle->mountPoint)
+            GOTO_MACRO(PHYSFS_ERR_OUT_OF_MEMORY, badDirHandle);
+        strcpy(dirHandle->mountPoint, mountPoint);
+        strcat(dirHandle->mountPoint, "/");
+    } /* if */
+
+    __PHYSFS_smallFree(tmpmntpnt);
+    return dirHandle;
+
+badDirHandle:
+    if (dirHandle != NULL)
+    {
+        dirHandle->funcs->closeArchive(dirHandle->opaque);
+        allocator.Free(dirHandle->dirName);
+        allocator.Free(dirHandle->mountPoint);
+        allocator.Free(dirHandle);
+    } /* if */
+
+    __PHYSFS_smallFree(tmpmntpnt);
+    return NULL;
+} /* createDirHandle */
+
+
+/* MAKE SURE you've got the stateLock held before calling this! */
+static int freeDirHandle(DirHandle *dh, FileHandle *openList)
+{
+    FileHandle *i;
+
+    if (dh == NULL)
+        return 1;
+
+    for (i = openList; i != NULL; i = i->next)
+        BAIL_IF_MACRO(i->dirHandle == dh, PHYSFS_ERR_FILES_STILL_OPEN, 0);
+
+    dh->funcs->closeArchive(dh->opaque);
+    allocator.Free(dh->dirName);
+    allocator.Free(dh->mountPoint);
+    allocator.Free(dh);
+    return 1;
+} /* freeDirHandle */
+
+
+static char *calculateBaseDir(const char *argv0)
+{
+    const char dirsep = __PHYSFS_platformDirSeparator;
+    char *retval = NULL;
+    char *ptr = NULL;
+
+    /* Give the platform layer first shot at this. */
+    retval = __PHYSFS_platformCalcBaseDir(argv0);
+    if (retval != NULL)
+        return retval;
+
+    /* We need argv0 to go on. */
+    BAIL_IF_MACRO(argv0 == NULL, PHYSFS_ERR_ARGV0_IS_NULL, NULL);
+
+    ptr = strrchr(argv0, dirsep);
+    if (ptr != NULL)
+    {
+        const size_t size = ((size_t) (ptr - argv0)) + 1;
+        retval = (char *) allocator.Malloc(size + 1);
+        BAIL_IF_MACRO(!retval, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
+        memcpy(retval, argv0, size);
+        retval[size] = '\0';
+        return retval;
+    } /* if */
+
+    /* argv0 wasn't helpful. */
+    BAIL_MACRO(PHYSFS_ERR_INVALID_ARGUMENT, NULL);
+} /* calculateBaseDir */
+
+
+static int initializeMutexes(void)
+{
+    errorLock = __PHYSFS_platformCreateMutex();
+    if (errorLock == NULL)
+        goto initializeMutexes_failed;
+
+    stateLock = __PHYSFS_platformCreateMutex();
+    if (stateLock == NULL)
+        goto initializeMutexes_failed;
+
+    return 1;  /* success. */
+
+initializeMutexes_failed:
+    if (errorLock != NULL)
+        __PHYSFS_platformDestroyMutex(errorLock);
+
+    if (stateLock != NULL)
+        __PHYSFS_platformDestroyMutex(stateLock);
+
+    errorLock = stateLock = NULL;
+    return 0;  /* failed. */
+} /* initializeMutexes */
+
+
+static void setDefaultAllocator(void);
+
+static int initStaticArchivers(void)
+{
+    const size_t numStaticArchivers = __PHYSFS_ARRAYLEN(staticArchivers);
+    const size_t len = numStaticArchivers * sizeof (void *);
+    size_t i;
+
+    assert(numStaticArchivers > 0);  /* seriously, none at all?! */
+    assert(staticArchivers[numStaticArchivers - 1] == NULL);
+
+    archiveInfo = (const PHYSFS_ArchiveInfo **) allocator.Malloc(len);
+    BAIL_IF_MACRO(!archiveInfo, PHYSFS_ERR_OUT_OF_MEMORY, 0);
+    archivers = (const PHYSFS_Archiver **) allocator.Malloc(len);
+    BAIL_IF_MACRO(!archivers, PHYSFS_ERR_OUT_OF_MEMORY, 0);
+
+    for (i = 0; i < numStaticArchivers - 1; i++)
+        archiveInfo[i] = &staticArchivers[i]->info;
+    archiveInfo[numStaticArchivers - 1] = NULL;
+
+    memcpy(archivers, staticArchivers, len);
+
+    return 1;
+} /* initStaticArchivers */
+
+
+static int doDeinit(void);
+
+int PHYSFS_init(const char *argv0)
+{
+    BAIL_IF_MACRO(initialized, PHYSFS_ERR_IS_INITIALIZED, 0);
+
+    if (!externalAllocator)
+        setDefaultAllocator();
+
+    if ((allocator.Init != NULL) && (!allocator.Init())) return 0;
+
+    if (!__PHYSFS_platformInit())
+    {
+        if (allocator.Deinit != NULL) allocator.Deinit();
+        return 0;
+    } /* if */
+
+    /* everything below here can be cleaned up safely by doDeinit(). */
+
+    if (!initializeMutexes()) goto initFailed;
+
+    baseDir = calculateBaseDir(argv0);
+    if (!baseDir) goto initFailed;
+
+    userDir = __PHYSFS_platformCalcUserDir();
+    if (!userDir) goto initFailed;
+
+    /* Platform layer is required to append a dirsep. */
+    assert(baseDir[strlen(baseDir) - 1] == __PHYSFS_platformDirSeparator);
+    assert(userDir[strlen(userDir) - 1] == __PHYSFS_platformDirSeparator);
+
+    if (!initStaticArchivers()) goto initFailed;
+
+    initialized = 1;
+
+    /* This makes sure that the error subsystem is initialized. */
+    __PHYSFS_setError(PHYSFS_getLastErrorCode());
+
+    return 1;
+
+initFailed:
+    doDeinit();
+    return 0;
+} /* PHYSFS_init */
+
+
+/* MAKE SURE you hold stateLock before calling this! */
+static int closeFileHandleList(FileHandle **list)
+{
+    FileHandle *i;
+    FileHandle *next = NULL;
+
+    for (i = *list; i != NULL; i = next)
+    {
+        PHYSFS_Io *io = i->io;
+        next = i->next;
+
+        if (!io->flush(io))
+        {
+            *list = i;
+            return 0;
+        } /* if */
+
+        io->destroy(io);
+        allocator.Free(i);
+    } /* for */
+
+    *list = NULL;
+    return 1;
+} /* closeFileHandleList */
+
+
+/* MAKE SURE you hold the stateLock before calling this! */
+static void freeSearchPath(void)
+{
+    DirHandle *i;
+    DirHandle *next = NULL;
+
+    closeFileHandleList(&openReadList);
+
+    if (searchPath != NULL)
+    {
+        for (i = searchPath; i != NULL; i = next)
+        {
+            next = i->next;
+            freeDirHandle(i, openReadList);
+        } /* for */
+        searchPath = NULL;
+    } /* if */
+} /* freeSearchPath */
+
+
+static int doDeinit(void)
+{
+    BAIL_IF_MACRO(!__PHYSFS_platformDeinit(), ERRPASS, 0);
+
+    closeFileHandleList(&openWriteList);
+    BAIL_IF_MACRO(!PHYSFS_setWriteDir(NULL), PHYSFS_ERR_FILES_STILL_OPEN, 0);
+
+    freeSearchPath();
+    freeErrorStates();
+
+    if (baseDir != NULL)
+    {
+        allocator.Free(baseDir);
+        baseDir = NULL;
+    } /* if */
+
+    if (userDir != NULL)
+    {
+        allocator.Free(userDir);
+        userDir = NULL;
+    } /* if */
+
+    if (prefDir != NULL)
+    {
+        allocator.Free(prefDir);
+        prefDir = NULL;
+    } /* if */
+
+    if (archiveInfo != NULL)
+    {
+        allocator.Free(archiveInfo);
+        archiveInfo = NULL;
+    } /* if */
+
+    if (archivers != NULL)
+    {
+        allocator.Free(archivers);
+        archivers = NULL;
+    } /* if */
+
+    allowSymLinks = 0;
+    initialized = 0;
+
+    if (errorLock) __PHYSFS_platformDestroyMutex(errorLock);
+    if (stateLock) __PHYSFS_platformDestroyMutex(stateLock);
+
+    if (allocator.Deinit != NULL)
+        allocator.Deinit();
+
+    errorLock = stateLock = NULL;
+    return 1;
+} /* doDeinit */
+
+
+int PHYSFS_deinit(void)
+{
+    BAIL_IF_MACRO(!initialized, PHYSFS_ERR_NOT_INITIALIZED, 0);
+    return doDeinit();
+} /* PHYSFS_deinit */
+
+
+int PHYSFS_isInit(void)
+{
+    return initialized;
+} /* PHYSFS_isInit */
+
+
+const PHYSFS_ArchiveInfo **PHYSFS_supportedArchiveTypes(void)
+{
+    BAIL_IF_MACRO(!initialized, PHYSFS_ERR_NOT_INITIALIZED, NULL);
+    return archiveInfo;
+} /* PHYSFS_supportedArchiveTypes */
+
+
+void PHYSFS_freeList(void *list)
+{
+    void **i;
+    if (list != NULL)
+    {
+        for (i = (void **) list; *i != NULL; i++)
+            allocator.Free(*i);
+
+        allocator.Free(list);
+    } /* if */
+} /* PHYSFS_freeList */
+
+
+const char *PHYSFS_getDirSeparator(void)
+{
+    static char retval[2] = { __PHYSFS_platformDirSeparator, '\0' };
+    return retval;
+} /* PHYSFS_getDirSeparator */
+
+
+char **PHYSFS_getCdRomDirs(void)
+{
+    return doEnumStringList(__PHYSFS_platformDetectAvailableCDs);
+} /* PHYSFS_getCdRomDirs */
+
+
+void PHYSFS_getCdRomDirsCallback(PHYSFS_StringCallback callback, void *data)
+{
+    __PHYSFS_platformDetectAvailableCDs(callback, data);
+} /* PHYSFS_getCdRomDirsCallback */
+
+
+const char *PHYSFS_getPrefDir(const char *org, const char *app)
+{
+    const char dirsep = __PHYSFS_platformDirSeparator;
+    PHYSFS_Stat statbuf;
+    char *ptr = NULL;
+    char *endstr = NULL;
+    int exists = 0;
+
+    BAIL_IF_MACRO(!initialized, PHYSFS_ERR_NOT_INITIALIZED, 0);
+    BAIL_IF_MACRO(!org, PHYSFS_ERR_INVALID_ARGUMENT, NULL);
+    BAIL_IF_MACRO(*org == '\0', PHYSFS_ERR_INVALID_ARGUMENT, NULL);
+    BAIL_IF_MACRO(!app, PHYSFS_ERR_INVALID_ARGUMENT, NULL);
+    BAIL_IF_MACRO(*app == '\0', PHYSFS_ERR_INVALID_ARGUMENT, NULL);
+
+    allocator.Free(prefDir);
+    prefDir = __PHYSFS_platformCalcPrefDir(org, app);
+    BAIL_IF_MACRO(!prefDir, ERRPASS, NULL);
+
+    assert(strlen(prefDir) > 0);
+    endstr = prefDir + (strlen(prefDir) - 1);
+    assert(*endstr == dirsep);
+    *endstr = '\0';  /* mask out the final dirsep for now. */
+
+    if (!__PHYSFS_platformStat(prefDir, &exists, &statbuf))
+    {
+        for (ptr = strchr(prefDir, dirsep); ptr; ptr = strchr(ptr+1, dirsep))
+        {
+            *ptr = '\0';
+            __PHYSFS_platformMkDir(prefDir);
+            *ptr = dirsep;
+        } /* for */
+
+        if (!__PHYSFS_platformMkDir(prefDir))
+        {
+            allocator.Free(prefDir);
+            prefDir = NULL;
+        } /* if */
+    } /* if */
+
+    *endstr = dirsep;  /* readd the final dirsep. */
+
+    return prefDir;
+} /* PHYSFS_getPrefDir */
+
+
+const char *PHYSFS_getBaseDir(void)
+{
+    return baseDir;   /* this is calculated in PHYSFS_init()... */
+} /* PHYSFS_getBaseDir */
+
+
+const char *__PHYSFS_getUserDir(void)  /* not deprecated internal version. */
+{
+    return userDir;   /* this is calculated in PHYSFS_init()... */
+} /* __PHYSFS_getUserDir */
+
+
+const char *PHYSFS_getUserDir(void)
+{
+    return __PHYSFS_getUserDir();
+} /* PHYSFS_getUserDir */
+
+
+const char *PHYSFS_getWriteDir(void)
+{
+    const char *retval = NULL;
+
+    __PHYSFS_platformGrabMutex(stateLock);
+    if (writeDir != NULL)
+        retval = writeDir->dirName;
+    __PHYSFS_platformReleaseMutex(stateLock);
+
+    return retval;
+} /* PHYSFS_getWriteDir */
+
+
+int PHYSFS_setWriteDir(const char *newDir)
+{
+    int retval = 1;
+
+    __PHYSFS_platformGrabMutex(stateLock);
+
+    if (writeDir != NULL)
+    {
+        BAIL_IF_MACRO_MUTEX(!freeDirHandle(writeDir, openWriteList), ERRPASS,
+                            stateLock, 0);
+        writeDir = NULL;
+    } /* if */
+
+    if (newDir != NULL)
+    {
+        /* !!! FIXME: PHYSFS_Io shouldn't be NULL */
+        writeDir = createDirHandle(NULL, newDir, NULL, 1);
+        retval = (writeDir != NULL);
+    } /* if */
+
+    __PHYSFS_platformReleaseMutex(stateLock);
+
+    return retval;
+} /* PHYSFS_setWriteDir */
+
+
+static int doMount(PHYSFS_Io *io, const char *fname,
+                   const char *mountPoint, int appendToPath)
+{
+    DirHandle *dh;
+    DirHandle *prev = NULL;
+    DirHandle *i;
+
+    if (mountPoint == NULL)
+        mountPoint = "/";
+
+    __PHYSFS_platformGrabMutex(stateLock);
+
+    if (fname != NULL)
+    {
+        for (i = searchPath; i != NULL; i = i->next)
+        {
+            /* already in search path? */
+            if ((i->dirName != NULL) && (strcmp(fname, i->dirName) == 0))
+                BAIL_MACRO_MUTEX(ERRPASS, stateLock, 1);
+            prev = i;
+        } /* for */
+    } /* if */
+
+    dh = createDirHandle(io, fname, mountPoint, 0);
+    BAIL_IF_MACRO_MUTEX(!dh, ERRPASS, stateLock, 0);
+
+    if (appendToPath)
+    {
+        if (prev == NULL)
+            searchPath = dh;
+        else
+            prev->next = dh;
+    } /* if */
+    else
+    {
+        dh->next = searchPath;
+        searchPath = dh;
+    } /* else */
+
+    __PHYSFS_platformReleaseMutex(stateLock);
+    return 1;
+} /* doMount */
+
+
+int PHYSFS_mountIo(PHYSFS_Io *io, const char *fname,
+                   const char *mountPoint, int appendToPath)
+{
+    BAIL_IF_MACRO(!io, PHYSFS_ERR_INVALID_ARGUMENT, 0);
+    BAIL_IF_MACRO(io->version != 0, PHYSFS_ERR_UNSUPPORTED, 0);
+    return doMount(io, fname, mountPoint, appendToPath);
+} /* PHYSFS_mountIo */
+
+
+int PHYSFS_mountMemory(const void *buf, PHYSFS_uint64 len, void (*del)(void *),
+                       const char *fname, const char *mountPoint,
+                       int appendToPath)
+{
+    int retval = 0;
+    PHYSFS_Io *io = NULL;
+
+    BAIL_IF_MACRO(!buf, PHYSFS_ERR_INVALID_ARGUMENT, 0);
+
+    io = __PHYSFS_createMemoryIo(buf, len, del);
+    BAIL_IF_MACRO(!io, ERRPASS, 0);
+    retval = doMount(io, fname, mountPoint, appendToPath);
+    if (!retval)
+    {
+        /* docs say not to call (del) in case of failure, so cheat. */
+        MemoryIoInfo *info = (MemoryIoInfo *) io->opaque;
+        info->destruct = NULL;
+        io->destroy(io);
+    } /* if */
+
+    return retval;
+} /* PHYSFS_mountMemory */
+
+
+int PHYSFS_mountHandle(PHYSFS_File *file, const char *fname,
+                       const char *mountPoint, int appendToPath)
+{
+    int retval = 0;
+    PHYSFS_Io *io = NULL;
+
+    BAIL_IF_MACRO(file == NULL, PHYSFS_ERR_INVALID_ARGUMENT, 0);
+
+    io = __PHYSFS_createHandleIo(file);
+    BAIL_IF_MACRO(!io, ERRPASS, 0);
+    retval = doMount(io, fname, mountPoint, appendToPath);
+    if (!retval)
+    {
+        /* docs say not to destruct in case of failure, so cheat. */
+        io->opaque = NULL;
+        io->destroy(io);
+    } /* if */
+
+    return retval;
+} /* PHYSFS_mountHandle */
+
+
+int PHYSFS_mount(const char *newDir, const char *mountPoint, int appendToPath)
+{
+    BAIL_IF_MACRO(!newDir, PHYSFS_ERR_INVALID_ARGUMENT, 0);
+    return doMount(NULL, newDir, mountPoint, appendToPath);
+} /* PHYSFS_mount */
+
+
+int PHYSFS_addToSearchPath(const char *newDir, int appendToPath)
+{
+    return doMount(NULL, newDir, NULL, appendToPath);
+} /* PHYSFS_addToSearchPath */
+
+
+int PHYSFS_removeFromSearchPath(const char *oldDir)
+{
+    return PHYSFS_unmount(oldDir);
+} /* PHYSFS_removeFromSearchPath */
+
+
+int PHYSFS_unmount(const char *oldDir)
+{
+    DirHandle *i;
+    DirHandle *prev = NULL;
+    DirHandle *next = NULL;
+
+    BAIL_IF_MACRO(oldDir == NULL, PHYSFS_ERR_INVALID_ARGUMENT, 0);
+
+    __PHYSFS_platformGrabMutex(stateLock);
+    for (i = searchPath; i != NULL; i = i->next)
+    {
+        if (strcmp(i->dirName, oldDir) == 0)
+        {
+            next = i->next;
+            BAIL_IF_MACRO_MUTEX(!freeDirHandle(i, openReadList), ERRPASS,
+                                stateLock, 0);
+
+            if (prev == NULL)
+                searchPath = next;
+            else
+                prev->next = next;
+
+            BAIL_MACRO_MUTEX(ERRPASS, stateLock, 1);
+        } /* if */
+        prev = i;
+    } /* for */
+
+    BAIL_MACRO_MUTEX(PHYSFS_ERR_NOT_MOUNTED, stateLock, 0);
+} /* PHYSFS_unmount */
+
+
+char **PHYSFS_getSearchPath(void)
+{
+    return doEnumStringList(PHYSFS_getSearchPathCallback);
+} /* PHYSFS_getSearchPath */
+
+
+const char *PHYSFS_getMountPoint(const char *dir)
+{
+    DirHandle *i;
+    __PHYSFS_platformGrabMutex(stateLock);
+    for (i = searchPath; i != NULL; i = i->next)
+    {
+        if (strcmp(i->dirName, dir) == 0)
+        {
+            const char *retval = ((i->mountPoint) ? i->mountPoint : "/");
+            __PHYSFS_platformReleaseMutex(stateLock);
+            return retval;
+        } /* if */
+    } /* for */
+    __PHYSFS_platformReleaseMutex(stateLock);
+
+    BAIL_MACRO(PHYSFS_ERR_NOT_MOUNTED, NULL);
+} /* PHYSFS_getMountPoint */
+
+
+void PHYSFS_getSearchPathCallback(PHYSFS_StringCallback callback, void *data)
+{
+    DirHandle *i;
+
+    __PHYSFS_platformGrabMutex(stateLock);
+
+    for (i = searchPath; i != NULL; i = i->next)
+        callback(data, i->dirName);
+
+    __PHYSFS_platformReleaseMutex(stateLock);
+} /* PHYSFS_getSearchPathCallback */
+
+
+/* Split out to avoid stack allocation in a loop. */
+static void setSaneCfgAddPath(const char *i, const size_t l, const char *dirsep,
+                              int archivesFirst)
+{
+    const char *d = PHYSFS_getRealDir(i);
+    const size_t allocsize = strlen(d) + strlen(dirsep) + l + 1;
+    char *str = (char *) __PHYSFS_smallAlloc(allocsize);
+    if (str != NULL)
+    {
+        sprintf(str, "%s%s%s", d, dirsep, i);
+        PHYSFS_mount(str, NULL, archivesFirst == 0);
+        __PHYSFS_smallFree(str);
+    } /* if */
+} /* setSaneCfgAddPath */
+
+
+int PHYSFS_setSaneConfig(const char *organization, const char *appName,
+                         const char *archiveExt, int includeCdRoms,
+                         int archivesFirst)
+{
+    const char *dirsep = PHYSFS_getDirSeparator();
+    const char *basedir;
+    const char *prefdir;
+
+    BAIL_IF_MACRO(!initialized, PHYSFS_ERR_NOT_INITIALIZED, 0);
+
+    prefdir = PHYSFS_getPrefDir(organization, appName);
+    BAIL_IF_MACRO(!prefdir, ERRPASS, 0);
+
+    basedir = PHYSFS_getBaseDir();
+    BAIL_IF_MACRO(!basedir, ERRPASS, 0);
+
+    BAIL_IF_MACRO(!PHYSFS_setWriteDir(prefdir), PHYSFS_ERR_NO_WRITE_DIR, 0);
+
+    /* Put write dir first in search path... */
+    PHYSFS_mount(prefdir, NULL, 0);
+
+    /* Put base path on search path... */
+    PHYSFS_mount(basedir, NULL, 1);
+
+    /* handle CD-ROMs... */
+    if (includeCdRoms)
+    {
+        char **cds = PHYSFS_getCdRomDirs();
+        char **i;
+        for (i = cds; *i != NULL; i++)
+            PHYSFS_mount(*i, NULL, 1);
+        PHYSFS_freeList(cds);
+    } /* if */
+
+    /* Root out archives, and add them to search path... */
+    if (archiveExt != NULL)
+    {
+        char **rc = PHYSFS_enumerateFiles("/");
+        char **i;
+        size_t extlen = strlen(archiveExt);
+        char *ext;
+
+        for (i = rc; *i != NULL; i++)
+        {
+            size_t l = strlen(*i);
+            if ((l > extlen) && ((*i)[l - extlen - 1] == '.'))
+            {
+                ext = (*i) + (l - extlen);
+                if (__PHYSFS_stricmpASCII(ext, archiveExt) == 0)
+                    setSaneCfgAddPath(*i, l, dirsep, archivesFirst);
+            } /* if */
+        } /* for */
+
+        PHYSFS_freeList(rc);
+    } /* if */
+
+    return 1;
+} /* PHYSFS_setSaneConfig */
+
+
+void PHYSFS_permitSymbolicLinks(int allow)
+{
+    allowSymLinks = allow;
+} /* PHYSFS_permitSymbolicLinks */
+
+
+int PHYSFS_symbolicLinksPermitted(void)
+{
+    return allowSymLinks;
+} /* PHYSFS_symbolicLinksPermitted */
+
+
+/*
+ * Verify that (fname) (in platform-independent notation), in relation
+ *  to (h) is secure. That means that each element of fname is checked
+ *  for symlinks (if they aren't permitted). This also allows for quick
+ *  rejection of files that exist outside an archive's mountpoint.
+ *
+ * With some exceptions (like PHYSFS_mkdir(), which builds multiple subdirs
+ *  at a time), you should always pass zero for "allowMissing" for efficiency.
+ *
+ * (fname) must point to an output from sanitizePlatformIndependentPath(),
+ *  since it will make sure that path names are in the right format for
+ *  passing certain checks. It will also do checks for "insecure" pathnames
+ *  like ".." which should be done once instead of once per archive. This also
+ *  gives us license to treat (fname) as scratch space in this function.
+ *
+ * Returns non-zero if string is safe, zero if there's a security issue.
+ *  PHYSFS_getLastError() will specify what was wrong. (*fname) will be
+ *  updated to point past any mount point elements so it is prepared to
+ *  be used with the archiver directly.
+ */
+static int verifyPath(DirHandle *h, char **_fname, int allowMissing)
+{
+    char *fname = *_fname;
+    int retval = 1;
+    char *start;
+    char *end;
+
+    if (*fname == '\0')  /* quick rejection. */
+        return 1;
+
+    /* !!! FIXME: This codeblock sucks. */
+    if (h->mountPoint != NULL)  /* NULL mountpoint means "/". */
+    {
+        size_t mntpntlen = strlen(h->mountPoint);
+        size_t len = strlen(fname);
+        assert(mntpntlen > 1); /* root mount points should be NULL. */
+        /* not under the mountpoint, so skip this archive. */
+        BAIL_IF_MACRO(len < mntpntlen-1, PHYSFS_ERR_NO_SUCH_PATH, 0);
+        /* !!! FIXME: Case insensitive? */
+        retval = strncmp(h->mountPoint, fname, mntpntlen-1);
+        BAIL_IF_MACRO(retval != 0, PHYSFS_ERR_NO_SUCH_PATH, 0);
+        if (len > mntpntlen-1)  /* corner case... */
+            BAIL_IF_MACRO(fname[mntpntlen-1]!='/', PHYSFS_ERR_NO_SUCH_PATH, 0);
+        fname += mntpntlen-1;  /* move to start of actual archive path. */
+        if (*fname == '/')
+            fname++;
+        *_fname = fname;  /* skip mountpoint for later use. */
+        retval = 1;  /* may be reset, below. */
+    } /* if */
+
+    start = fname;
+    if (!allowSymLinks)
+    {
+        while (1)
+        {
+            PHYSFS_Stat statbuf;
+            int rc = 0;
+            end = strchr(start, '/');
+
+            if (end != NULL) *end = '\0';
+            rc = h->funcs->stat(h->opaque, fname, &retval, &statbuf);
+            if (rc)
+                rc = (statbuf.filetype == PHYSFS_FILETYPE_SYMLINK);
+            if (end != NULL) *end = '/';
+
+            /* insecure path (has a disallowed symlink in it)? */
+            BAIL_IF_MACRO(rc, PHYSFS_ERR_SYMLINK_FORBIDDEN, 0);
+
+            /* break out early if path element is missing. */
+            if (!retval)
+            {
+                /*
+                 * We need to clear it if it's the last element of the path,
+                 *  since this might be a non-existant file we're opening
+                 *  for writing...
+                 */
+                if ((end == NULL) || (allowMissing))
+                    retval = 1;
+                break;
+            } /* if */
+
+            if (end == NULL)
+                break;
+
+            start = end + 1;
+        } /* while */
+    } /* if */
+
+    return retval;
+} /* verifyPath */
+
+
+static int doMkdir(const char *_dname, char *dname)
+{
+    DirHandle *h;
+    char *start;
+    char *end;
+    int retval = 0;
+    int exists = 1;  /* force existance check on first path element. */
+
+    BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_dname, dname), ERRPASS, 0);
+
+    __PHYSFS_platformGrabMutex(stateLock);
+    BAIL_IF_MACRO_MUTEX(!writeDir, PHYSFS_ERR_NO_WRITE_DIR, stateLock, 0);
+    h = writeDir;
+    BAIL_IF_MACRO_MUTEX(!verifyPath(h, &dname, 1), ERRPASS, stateLock, 0);
+
+    start = dname;
+    while (1)
+    {
+        end = strchr(start, '/');
+        if (end != NULL)
+            *end = '\0';
+
+        /* only check for existance if all parent dirs existed, too... */
+        if (exists)
+        {
+            PHYSFS_Stat statbuf;
+            const int rc = h->funcs->stat(h->opaque, dname, &exists, &statbuf);
+            retval = ((rc) && (statbuf.filetype == PHYSFS_FILETYPE_DIRECTORY));
+        } /* if */
+
+        if (!exists)
+            retval = h->funcs->mkdir(h->opaque, dname);
+
+        if (!retval)
+            break;
+
+        if (end == NULL)
+            break;
+
+        *end = '/';
+        start = end + 1;
+    } /* while */
+
+    __PHYSFS_platformReleaseMutex(stateLock);
+    return retval;
+} /* doMkdir */
+
+
+int PHYSFS_mkdir(const char *_dname)
+{
+    int retval = 0;
+    char *dname;
+    size_t len;
+
+    BAIL_IF_MACRO(!_dname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
+    len = strlen(_dname) + 1;
+    dname = (char *) __PHYSFS_smallAlloc(len);
+    BAIL_IF_MACRO(!dname, PHYSFS_ERR_OUT_OF_MEMORY, 0);
+    retval = doMkdir(_dname, dname);
+    __PHYSFS_smallFree(dname);
+    return retval;
+} /* PHYSFS_mkdir */
+
+
+static int doDelete(const char *_fname, char *fname)
+{
+    int retval;
+    DirHandle *h;
+    BAIL_IF_MACRO(!sanitizePlatformIndependentPath(_fname, fname), ERRPASS, 0);
+
+    __PHYSFS_platformGrabMutex(stateLock);
+
+    BAIL_IF_MACRO_MUTEX(!writeDir, PHYSFS_ERR_NO_WRITE_DIR, stateLock, 0);
+    h = writeDir;
+    BAIL_IF_MACRO_MUTEX(!verifyPath(h, &fname, 0), ERRPASS, stateLock, 0);
+    retval = h->funcs->remove(h->opaque, fname);
+
+    __PHYSFS_platformReleaseMutex(stateLock);
+    return retval;
+} /* doDelete */
+
+
+int PHYSFS_delete(const char *_fname)
+{
+    int retval;
+    char *fname;
+    size_t len;
+
+    BAIL_IF_MACRO(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
+    len = strlen(_fname) + 1;
+    fname = (char *) __PHYSFS_smallAlloc(len);
+    BAIL_IF_MACRO(!fname, PHYSFS_ERR_OUT_OF_MEMORY, 0);
+    retval = doDelete(_fname, fname);
+    __PHYSFS_smallFree(fname);
+    return retval;
+} /* PHYSFS_delete */
+
+
+const char *PHYSFS_getRealDir(const char *_fname)
+{
+    const char *retval = NULL;
+    char *fname = NULL;
+    size_t len;
+
+    BAIL_IF_MACRO(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, NULL);
+    len = strlen(_fname) + 1;
+    fname = __PHYSFS_smallAlloc(len);
+    BAIL_IF_MACRO(!fname, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
+    if (sanitizePlatformIndependentPath(_fname, fname))
+    {
+        DirHandle *i;
+        __PHYSFS_platformGrabMutex(stateLock);
+        for (i = searchPath; i != NULL; i = i->next)
+        {
+            char *arcfname = fname;
+            if (partOfMountPoint(i, arcfname))
+            {
+                retval = i->dirName;
+                break;
+            } /* if */
+            else if (verifyPath(i, &arcfname, 0))
+            {
+                PHYSFS_Stat statbuf;
+                int exists = 0;
+                if (i->funcs->stat(i->opaque, arcfname, &exists, &statbuf))
+                {
+                    if (exists)
+                        retval = i->dirName;
+                    break;
+                } /* if */
+            } /* if */
+        } /* for */
+        __PHYSFS_platformReleaseMutex(stateLock);
+    } /* if */
+
+    __PHYSFS_smallFree(fname);
+    return retval;
+} /* PHYSFS_getRealDir */
+
+
+static int locateInStringList(const char *str,
+                              char **list,
+                              PHYSFS_uint32 *pos)
+{
+    PHYSFS_uint32 len = *pos;
+    PHYSFS_uint32 half_len;
+    PHYSFS_uint32 lo = 0;
+    PHYSFS_uint32 middle;
+    int cmp;
+
+    while (len > 0)
+    {
+        half_len = len >> 1;
+        middle = lo + half_len;
+        cmp = strcmp(list[middle], str);
+
+        if (cmp == 0)  /* it's in the list already. */
+            return 1;
+        else if (cmp > 0)
+            len = half_len;
+        else
+        {
+            lo = middle + 1;
+            len -= half_len + 1;
+        } /* else */
+    } /* while */
+
+    *pos = lo;
+    return 0;
+} /* locateInStringList */
+
+
+static void enumFilesCallback(void *data, const char *origdir, const char *str)
+{
+    PHYSFS_uint32 pos;
+    void *ptr;
+    char *newstr;
+    EnumStringListCallbackData *pecd = (EnumStringListCallbackData *) data;
+
+    /*
+     * See if file is in the list already, and if not, insert it in there
+     *  alphabetically...
+     */
+    pos = pecd->size;
+    if (locateInStringList(str, pecd->list, &pos))
+        return;  /* already in the list. */
+
+    ptr = allocator.Realloc(pecd->list, (pecd->size + 2) * sizeof (char *));
+    newstr = (char *) allocator.Malloc(strlen(str) + 1);
+    if (ptr != NULL)
+        pecd->list = (char **) ptr;
+
+    if ((ptr == NULL) || (newstr == NULL))
+        return;  /* better luck next time. */
+
+    strcpy(newstr, str);
+
+    if (pos != pecd->size)
+    {
+        memmove(&pecd->list[pos+1], &pecd->list[pos],
+                 sizeof (char *) * ((pecd->size) - pos));
+    } /* if */
+
+    pecd->list[pos] = newstr;
+    pecd->size++;
+} /* enumFilesCallback */
+
+
+char **PHYSFS_enumerateFiles(const char *path)
+{
+    EnumStringListCallbackData ecd;
+    memset(&ecd, '\0', sizeof (ecd));
+    ecd.list = (char **) allocator.Malloc(sizeof (char *));
+    BAIL_IF_MACRO(!ecd.list, PHYSFS_ERR_OUT_OF_MEMORY, NULL);
+    PHYSFS_enumerateFilesCallback(path, enumFilesCallback, &ecd);
+    ecd.list[ecd.size] = NULL;
+    return ecd.list;
+} /* PHYSFS_enumerateFiles */
+
+
+/*
+ * Broke out to seperate function so we can use stack allocation gratuitously.
+ */
+static void enumerateFromMountPoint(DirHandle *i, const char *arcfname,
+                                    PHYSFS_EnumFilesCallback callback,
+                                    const char *_fname, void *data)
+{
+    const size_t len = strlen(arcfname);
+    char *ptr = NULL;
+    char *end = NULL;
+    const size_t slen = strlen(i->mountPoint) + 1;
+    char *mountPoint = (char *) __PHYSFS_smallAlloc(slen);
+
+    if (mountPoint == NULL)
+        return;  /* oh well. */
+
+    strcpy(mountPoint, i->mountPoint);
+    ptr = mountPoint + ((len) ? len + 1 : 0);
+    end = strchr(ptr, '/');
+    assert(end);  /* should always find a terminating '/'. */
+    *end = '\0';
+    callback(data, _fname, ptr);
+    __PHYSFS_smallFree(mountPoint);
+} /* enumerateFromMountPoint */
+
+
+/* !!! FIXME: this should report error conditions. */
+void PHYSFS_enumerateFilesCallback(const char *_fname,
+                                   PHYSFS_EnumFilesCallback callback,
+                                   void *data)
+{
+    size_t len;
+    char *fname;
+
+    BAIL_IF_MACRO(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, ) /*0*/;
+    BAIL_IF_MACRO(!callback, PHYSFS_ERR_INVALID_ARGUMENT, ) /*0*/;
+
+    len = strlen(_fname) + 1;
+    fname = (char *) __PHYSFS_smallAlloc(len);
+    BAIL_IF_MACRO(!fname, PHYSFS_ERR_OUT_OF_MEMORY, ) /*0*/;
+
+    if (sanitizePlatformIndependentPath(_fname, fname))
+    {
+        DirHandle *i;
+        int noSyms;
+
+        __PHYSFS_platformGrabMutex(stateLock);
+        noSyms = !allowSymLinks;
+        for (i = searchPath; i != NULL; i = i->next)
+        {
+            char *arcfname = fname;
+            if (partOfMountPoint(i, arcfname))
+                enumerateFromMountPoint(i, arcfname, callback, _fname, data);
+
+            else if (verifyPath(i, &arcfname, 0))
+            {
+                i->funcs->enumerateFiles(i->opaque, arcfname, noSyms,
+                                         callback, _fname, data);
+            } /* else if */
+        } /* for */
+        __PHYSFS_platformReleaseMutex(stateLock);
+    } /* if */
+
+    __PHYSFS_smallFree(fname);
+} /* PHYSFS_enumerateFilesCallback */
+
+
+int PHYSFS_exists(const char *fname)
+{
+    return (PHYSFS_getRealDir(fname) != NULL);
+} /* PHYSFS_exists */
+
+
+PHYSFS_sint64 PHYSFS_getLastModTime(const char *fname)
+{
+    PHYSFS_Stat statbuf;
+    BAIL_IF_MACRO(!PHYSFS_stat(fname, &statbuf), ERRPASS, -1);
+    return statbuf.modtime;
+} /* PHYSFS_getLastModTime */
+
+
+int PHYSFS_isDirectory(const char *fname)
+{
+    PHYSFS_Stat statbuf;
+    BAIL_IF_MACRO(!PHYSFS_stat(fname, &statbuf), ERRPASS, 0);
+    return (statbuf.filetype == PHYSFS_FILETYPE_DIRECTORY);
+} /* PHYSFS_isDirectory */
+
+
+int PHYSFS_isSymbolicLink(const char *fname)
+{
+    PHYSFS_Stat statbuf;
+    BAIL_IF_MACRO(!PHYSFS_stat(fname, &statbuf), ERRPASS, 0);
+    return (statbuf.filetype == PHYSFS_FILETYPE_SYMLINK);
+} /* PHYSFS_isSymbolicLink */
+
+
+static PHYSFS_File *doOpenWrite(const char *_fname, int appending)
+{
+    FileHandle *fh = NULL;
+    size_t len;
+    char *fname;
+
+    BAIL_IF_MACRO(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
+    len = strlen(_fname) + 1;
+    fname = (char *) __PHYSFS_smallAlloc(len);
+    BAIL_IF_MACRO(!fname, PHYSFS_ERR_OUT_OF_MEMORY, 0);
+
+    if (sanitizePlatformIndependentPath(_fname, fname))
+    {
+        PHYSFS_Io *io = NULL;
+        DirHandle *h = NULL;
+        const PHYSFS_Archiver *f;
+
+        __PHYSFS_platformGrabMutex(stateLock);
+
+        GOTO_IF_MACRO(!writeDir, PHYSFS_ERR_NO_WRITE_DIR, doOpenWriteEnd);
+
+        h = writeDir;
+        GOTO_IF_MACRO(!verifyPath(h, &fname, 0), ERRPASS, doOpenWriteEnd);
+
+        f = h->funcs;
+        if (appending)
+            io = f->openAppend(h->opaque, fname);
+        else
+            io = f->openWrite(h->opaque, fname);
+
+        GOTO_IF_MACRO(!io, ERRPASS, doOpenWriteEnd);
+
+        fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
+        if (fh == NULL)
+        {
+            io->destroy(io);
+            GOTO_MACRO(PHYSFS_ERR_OUT_OF_MEMORY, doOpenWriteEnd);
+        } /* if */
+        else
+        {
+            memset(fh, '\0', sizeof (FileHandle));
+            fh->io = io;
+            fh->dirHandle = h;
+            fh->next = openWriteList;
+            openWriteList = fh;
+        } /* else */
+
+        doOpenWriteEnd:
+        __PHYSFS_platformReleaseMutex(stateLock);
+    } /* if */
+
+    __PHYSFS_smallFree(fname);
+    return ((PHYSFS_File *) fh);
+} /* doOpenWrite */
+
+
+PHYSFS_File *PHYSFS_openWrite(const char *filename)
+{
+    return doOpenWrite(filename, 0);
+} /* PHYSFS_openWrite */
+
+
+PHYSFS_File *PHYSFS_openAppend(const char *filename)
+{
+    return doOpenWrite(filename, 1);
+} /* PHYSFS_openAppend */
+
+
+PHYSFS_File *PHYSFS_openRead(const char *_fname)
+{
+    FileHandle *fh = NULL;
+    char *fname;
+    size_t len;
+
+    BAIL_IF_MACRO(!_fname, PHYSFS_ERR_INVALID_ARGUMENT, 0);
+    len = strlen(_fname) + 1;
+    fname = (char *) __PHYSFS_smallAlloc(len);
+    BAIL_IF_MACRO(!fname, PHYSFS_ERR_OUT_OF_MEMORY, 0);
+
+    if (sanitizePlatformIndependentPath(_fname, fname))
+    {
+        int fileExists = 0;
+        DirHandle *i = NULL;
+        PHYSFS_Io *io = NULL;
+
+        __PHYSFS_platformGrabMutex(stateLock);
+
+        GOTO_IF_MACRO(!searchPath, PHYSFS_ERR_NO_SUCH_PATH, openReadEnd);
+
+        for (i = searchPath; (i != NULL) && (!fileExists); i = i->next)
+        {
+            char *arcfname = fname;
+            if (verifyPath(i, &arcfname, 0))
+            {
+                io = i->funcs->openRead(i->opaque, arcfname, &fileExists);
+                if (io)
+                    break;
+            } /* if */
+        } /* for */
+
+        GOTO_IF_MACRO(!io, ERRPASS, openReadEnd);
+
+        fh = (FileHandle *) allocator.Malloc(sizeof (FileHandle));
+        if (fh == NULL)
+        {
+            io->destroy(io);
+            GOTO_MACRO(PHYSFS_ERR_OUT_OF_MEMORY, openReadEnd);
+        } /* if */
+
+        memset(fh, '\0', sizeof (FileHandle));
+        fh->io = io;
+        fh->forReading = 1;
+        fh->dirHandle = i;
+        fh->next = openReadList;
+        openReadList = fh;
+
+        openReadEnd:
+        __PHYSFS_platformReleaseMutex(stateLock);
+    } /* if */
+
+    __PHYSFS_smallFree(fname);
+    return ((PHYSFS_File *) fh);
+} /* PHYSFS_openRead */
+
+
+static int closeHandleInOpenList(FileHandle **list, FileHandle *handle)
+{
+    FileHandle *prev = NULL;
+    FileHandle *i;
+    int rc = 1;
+
+    for (i = *list; i != NULL; i = i->next)
+    {
+        if (i == handle)  /* handle is in this list? */
+        {
+            PHYSFS_Io *io = handle->io;
+            PHYSFS_uint8 *tmp = handle->buffer;
+            rc = PHYSFS_flush((PHYSFS_File *) handle);
+            if (!rc)
+                return -1;
+            io->destroy(io);
+
+            if (tmp != NULL)  /* free any associated buffer. */
+                allocator.Free(tmp);
+
+            if (prev == NULL)
+                *list = handle->next;
+            else
+                prev->next = handle->next;
+
+            allocator.Free(handle);
+            return 1;
+        } /* if */
+        prev = i;
+    } /* for */
+
+    return 0;
+} /* closeHandleInOpenList */
+
+
+int PHYSFS_close(PHYSFS_File *_handle)
+{
+    FileHandle *handle = (FileHandle *) _handle;
+    int rc;
+
+    __PHYSFS_platformGrabMutex(stateLock);
+
+    /* -1 == close failure. 0 == not found. 1 == success. */
+    rc = closeHandleInOpenList(&openReadList, handle);
+    BAIL_IF_MACRO_MUTEX(rc == -1, ERRPASS, stateLock, 0);
+    if (!rc)
+    {
+        rc = closeHandleInOpenList(&openWriteList, handle);
+        BAIL_IF_MACRO_MUTEX(rc == -1, ERRPASS, stateLock, 0);
+    } /* if */
+
+    __PHYSFS_platformReleaseMutex(stateLock);
+    BAIL_IF_MACRO(!rc, PHYSFS_ERR_INVALID_ARGUMENT, 0);
+    return 1;
+} /* PHYSFS_close */
+
+
+static PHYSFS_sint64 doBufferedRead(FileHandle *fh, void *buffer,
+                                    PHYSFS_uint64 len)
+{
+    PHYSFS_Io *io = NULL;
+    PHYSFS_sint64 retval = 0;
+    PHYSFS_uint32 buffered = 0;
+    PHYSFS_sint64 rc = 0;
+
+    if (len == 0)
+        return 0;
+
+    buffered = fh->buffill - fh->bufpos;
+    if (buffered >= len)  /* totally in the buffer, just copy and return! */
+    {
+        memcpy(buffer, fh->buffer + fh->bufpos, (size_t) len);
+        fh->bufpos += (PHYSFS_uint32) len;
+        return (PHYSFS_sint64) len;
+    } /* else if */
+
+    if (buffered > 0) /* partially in the buffer... */
+    {
+        memcpy(buffer, fh->buffer + fh->bufpos, (size_t) buffered);
+        buffer = ((PHYSFS_uint8 *) buffer) + buffered;
+        len -= buffered;
+        retval = buffered;
+        fh->buffill = fh->bufpos = 0;
+    } /* if */
+
+    /* if you got here, the buffer is drained and we still need bytes. */
+    assert(len > 0);
+
+    io = fh->io;
+    if (len >= fh->bufsize)  /* need more than the buffer takes. */
+    {
+        /* leave buffer empty, go right to output instead. */
+        rc = io->read(io, buffer, len);
+        if (rc < 0)
+            return ((retval == 0) ? rc : retval);
+        return retval + rc;
+    } /* if */
+
+    /* need less than buffer can take. Fill buffer. */
+    rc = io->read(io, fh->buffer, fh->bufsize);
+    if (rc < 0)
+        return ((retval == 0) ? rc : retval);
+
+    assert(fh->bufpos == 0);
+    fh->buffill = (PHYSFS_uint32) rc;
+    rc = doBufferedRead(fh, buffer, len);  /* go from the start, again. */
+    if (rc < 0)
+        return ((retval == 0) ? rc : retval);
+
+    return retval + rc;
+} /* doBufferedRead */
+
+
+PHYSFS_sint64 PHYSFS_read(PHYSFS_File *handle, void *buffer,
+                          PHYSFS_uint32 size, PHYSFS_uint32 count)
+{
+    const PHYSFS_uint64 len = ((PHYSFS_uint64) size) * ((PHYSFS_uint64) count);
+    const PHYSFS_sint64 retval = PHYSFS_readBytes(handle, buffer, len);
+    return ( (retval <= 0) ? retval : (retval / ((PHYSFS_sint64) size)) );
+} /* PHYSFS_read */
+
+
+PHYSFS_sint64 PHYSFS_readBytes(PHYSFS_File *handle, void *buffer,
+                               PHYSFS_uint64 len)
+{
+    FileHandle *fh = (FileHandle *) handle;
+
+#ifdef PHYSFS_NO_64BIT_SUPPORT
+    const PHYSFS_uint64 maxlen = __PHYSFS_UI64(0x7FFFFFFF);
+#else
+    const PHYSFS_uint64 maxlen = __PHYSFS_UI64(0x7FFFFFFFFFFFFFFF);
+#endif
+
+    if (!__PHYSFS_ui64FitsAddressSpace(len))
+        BAIL_MACRO(PHYSFS_ERR_INVALID_ARGUMENT, -1);
+
+    BAIL_IF_MACRO(len > maxlen, PHYSFS_ERR_INVALID_ARGUMENT, -1);
+    BAIL_IF_MACRO(!fh->forReading, PHYSFS_ERR_OPEN_FOR_WRITING, -1);
+    BAIL_IF_MACRO(len == 0, ERRPASS, 0);
+    if (fh->buffer)
+        return doBufferedRead(fh, buffer, len);
+
+    return fh->io->read(fh->io, buffer, len);
+} /* PHYSFS_readBytes */
+
+
+static PHYSFS_sint64 doBufferedWrite(PHYSFS_File *handle, const void *buffer,
+                                     PHYSFS_uint64 len)
+{
+    FileHandle *fh = (FileHandle *) handle;
+
+    /* whole thing fits in the buffer? */
+    if ( (((PHYSFS_uint64) fh->buffill) + len) < fh->bufsize )
+    {
+        memcpy(fh->buffer + fh->buffill, buffer, (size_t) len);
+        fh->buffill += (PHYSFS_uint32) len;
+        return (PHYSFS_sint64) len;
+    } /* if */
+
+    /* would overflow buffer. Flush and then write the new objects, too. */
+    BAIL_IF_MACRO(!PHYSFS_flush(handle), ERRPASS, -1);
+    return fh->io->write(fh->io, buffer, len);
+} /* doBufferedWrite */
+
+
+PHYSFS_sint64 PHYSFS_write(PHYSFS_File *handle, const void *buffer,
+                           PHYSFS_uint32 size, PHYSFS_uint32 count)
+{
+    const PHYSFS_uint64 len = ((PHYSFS_uint64) size) * ((PHYSFS_uint64) count);
+    const PHYSFS_sint64 retval = PHYSFS_writeBytes(handle, buffer, len);
+    return ( (retval <= 0) ? retval : (retval / ((PHYSFS_sint64) size)) );
+} /* PHYSFS_write */
+
+
+PHYSFS_sint64 PHYSFS_writeBytes(PHYSFS_File *handle, const void *buffer,
+                                PHYSFS_uint64 len)
+{
+    FileHandle *fh = (FileHandle *) handle;
+
+#ifdef PHYSFS_NO_64BIT_SUPPORT
+    const PHYSFS_uint64 maxlen = __PHYSFS_UI64(0x7FFFFFFF);
+#else
+    const PHYSFS_uint64 maxlen = __PHYSFS_UI64(0x7FFFFFFFFFFFFFFF);
+#endif
+
+    if (!__PHYSFS_ui64FitsAddressSpace(len))
+        BAIL_MACRO(PHYSFS_ERR_INVALID_ARGUMENT, -1);
+
+    BAIL_IF_MACRO(len > maxlen, PHYSFS_ERR_INVALID_ARGUMENT, -1);
+    BAIL_IF_MACRO(fh->forReading, PHYSFS_ERR_OPEN_FOR_READING, -1);
+    BAIL_IF_MACRO(len == 0, ERRPASS, 0);
+    if (fh->buffer)
+        return doBufferedWrite(handle, buffer, len);
+
+    return fh->io->write(fh->io, buffer, len);
+} /* PHYSFS_write */
+
+
+int PHYSFS_eof(PHYSFS_File *handle)
+{
+    FileHandle *fh = (FileHandle *) handle;
+
+    if (!fh->forReading)  /* never EOF on files opened for write/append. */
+        return 0;
+
+    /* can't be eof if buffer isn't empty */
+    if (fh->bufpos == fh->buffill)
+    {
+        /* check the Io. */
+        PHYSFS_Io *io = fh->io;
+        const PHYSFS_sint64 pos = io->tell(io);
+        const PHYSFS_sint64 len = io->length(io);
+        if ((pos < 0) || (len < 0))
+            return 0;  /* beats me. */
+        return (pos >= len);
+    } /* if */
+
+    return 0;
+} /* PHYSFS_eof */
+
+
+PHYSFS_sint64 PHYSFS_tell(PHYSFS_File *handle)
+{
+    FileHandle *fh = (FileHandle *) handle;
+    const PHYSFS_sint64 pos = fh->io->tell(fh->io);
+    const PHYSFS_sint64 retval = fh->forReading ?
+                                 (pos - fh->buffill) + fh->bufpos :
+                                 (pos + fh->buffill);
+    return retval;
+} /* PHYSFS_tell */
+
+
+int PHYSFS_seek(PHYSFS_File *handle, PHYSFS_uint64 pos)
+{
+    FileHandle *fh = (FileHandle *) handle;
+    BAIL_IF_MACRO(!PHYSFS_flush(handle), ERRPASS, 0);
+
+    if (fh->buffer && fh->forReading)
+    {
+        /* avoid throwing away our precious buffer if seeking within it. */
+        PHYSFS_sint64 offset = pos - PHYSFS_tell(handle);
+        if ( /* seeking within the already-buffered range? */
+            ((offset >= 0) && (offset <= fh->buffill - fh->bufpos)) /* fwd */
+            || ((offset < 0) && (-offset <= fh->bufpos)) /* backward */ )
+        {
+            fh->bufpos += (PHYSFS_uint32) offset;
+            return 1; /* successful seek */
+        } /* if */
+    } /* if */
+
+    /* we have to fall back to a 'raw' seek. */
+    fh->buffill = fh->bufpos = 0;
+    return fh->io->seek(fh->io, pos);
+} /* PHYSFS_seek */
+
+
+PHYSFS_sint64 PHYSFS_fileLength(PHYSFS_File *handle)
+{
+    PHYSFS_Io *io = ((FileHandle *) handle)->io;
+    return io->length(io);
+} /* PHYSFS_filelength */
+
+
+int PHYSFS_setBuffer(PHYSFS_File *handle, PHYSFS_uint64 _bufsize)
+{
+    FileHandle *fh = (FileHandle *) handle;
+    PHYSFS_uint32 bufsize;
+
+    /* !!! FIXME: actually, why use 32 bits here? */
+    /*BAIL_IF_MACRO(_bufsize > 0xFFFFFFFF, "buffer must fit in 32-bits", 0);*/
+    BAIL_IF_MACRO(_bufsize > 0xFFFFFFFF, PHYSFS_ERR_INVALID_ARGUMENT, 0);
+    bufsize = (PHYSFS_uint32) _bufsize;
+
+    BAIL_IF_MACRO(!PHYSFS_flush(handle), ERRPASS, 0);
+
+    /*
+     * For reads, we need to move the file pointer to where it would be
+     *  if we weren't buffering, so that the next read will get the
+     *  right chunk of stuff from the file. PHYSFS_flush() handles writes.
+     */
+    if ((fh->forReading) && (fh->buffill != fh->bufpos))
+    {
+        PHYSFS_uint64 pos;
+        const PHYSFS_sint64 curpos = fh->io->tell(fh->io);
+        BAIL_IF_MACRO(curpos == -1, ERRPASS, 0);
+        pos = ((curpos - fh->buffill) + fh->bufpos);
+        BAIL_IF_MACRO(!fh->io->seek(fh->io, pos), ERRPASS, 0);
+    } /* if */
+
+    if (bufsize == 0)  /* delete existing buffer. */
+    {
+        if (fh->buffer)
+        {
+            allocator.Free(fh->buffer);
+            fh->buffer = NULL;
+        } /* if */
+    } /* if */
+
+    else
+    {
+        PHYSFS_uint8 *newbuf;
+        newbuf = (PHYSFS_uint8 *) allocator.Realloc(fh->buffer, bufsize);
+        BAIL_IF_MACRO(!newbuf, PHYSFS_ERR_OUT_OF_MEMORY, 0);
+        fh->buffer = newbuf;
+    } /* else */
+
+    fh->bufsize = bufsize;
+    fh->buffill = fh->bufpos = 0;
+    return 1;
+} /* PHYSFS_setBuffer */
+
+
+int PHYSFS_flush(PHYSFS_File *handle)
+{
+    FileHandle *fh = (FileHandle *) handle;
+    PHYSFS_Io *io;
+    PHYSFS_sint64 rc;
+
+    if ((fh->forReading) || (fh->bufpos == fh->buffill))
+        return 1;  /* open for read or buffer empty are successful no-ops. */
+
+    /* dump buffer to disk. */
+    io = fh->io;
+    rc = io->write(io, fh->buffer + fh->bufp