Index: code/branches/gamestates2/src/libraries/core/Core.cc
===================================================================
--- code/branches/gamestates2/src/libraries/core/Core.cc	(revision 6595)
+++ code/branches/gamestates2/src/libraries/core/Core.cc	(revision 6662)
@@ -78,4 +78,5 @@
 
     SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file");
+    SetCommandLineSwitch(noIOConsole).information("Use this if you don't want to use the IOConsole (for instance for Lua debugging)");
 #ifdef ORXONOX_PLATFORM_WINDOWS
     SetCommandLineArgument(limitToCPU, 1).information("Limits the program to one CPU/core (1, 2, 3, etc.). Default is the first core (faster than off)");
@@ -88,4 +89,5 @@
         , consoleCommandDestroyer_(CommandExecutor::destroyExternalCommands)
         , bGraphicsLoaded_(false)
+        , bStartIOConsole_(true)
     {
         // Set the hard coded fixed paths
@@ -149,5 +151,10 @@
 
         // create persistent io console
-        this->ioConsole_.reset(new IOConsole());
+        if (CommandLineParser::getValue("noIOConsole").getBool())
+        {
+            ModifyConfigValue(bStartIOConsole_, tset, false);
+        }
+        if (this->bStartIOConsole_)
+            this->ioConsole_.reset(new IOConsole());
 
         // creates the class hierarchy for all classes with factories
@@ -193,4 +200,6 @@
             .description("If true, all random actions are different each time you start the game")
             .callback(this, &Core::initRandomNumberGenerator);
+        SetConfigValue(bStartIOConsole_, true)
+            .description("Set to false if you don't want to use the IOConsole (for Lua debugging for instance)");
     }
 
@@ -327,5 +336,6 @@
         }
         // Process console events and status line
-        this->ioConsole_->preUpdate(time);
+        if (this->ioConsole_ != NULL)
+            this->ioConsole_->preUpdate(time);
         // Process thread commands
         this->tclThreadManager_->preUpdate(time);
Index: code/branches/gamestates2/src/libraries/core/Core.h
===================================================================
--- code/branches/gamestates2/src/libraries/core/Core.h	(revision 6595)
+++ code/branches/gamestates2/src/libraries/core/Core.h	(revision 6662)
@@ -97,5 +97,5 @@
             scoped_ptr<TclBind>           tclBind_;
             scoped_ptr<TclThreadManager>  tclThreadManager_;
-            scoped_ptr<Scope<ScopeID::Root> >     rootScope_;
+            scoped_ptr<Scope<ScopeID::Root> > rootScope_;
             // graphical
             scoped_ptr<GraphicsManager>   graphicsManager_;     //!< Interface to OGRE
@@ -108,4 +108,5 @@
             std::string                   language_;                   //!< The language
             bool                          bInitRandomNumberGenerator_; //!< If true, srand(time(0)) is called
+            bool                          bStartIOConsole_;            //!< Set to false if you don't want to use the IOConsole
 
             static Core*                  singletonPtr_s;
Index: code/branches/gamestates2/src/libraries/core/GUIManager.cc
===================================================================
--- code/branches/gamestates2/src/libraries/core/GUIManager.cc	(revision 6595)
+++ code/branches/gamestates2/src/libraries/core/GUIManager.cc	(revision 6662)
@@ -253,17 +253,25 @@
     }
 
-    const std::string& GUIManager::createInputState(const std::string& name, TriBool::Value showMouse, TriBool::Value useKeyboard, bool bBlockJoyStick)
+    const std::string& GUIManager::createInputState(const std::string& name, TriBool::Value showCursor, TriBool::Value useKeyboard, bool bBlockJoyStick)
     {
         InputState* state = InputManager::getInstance().createInputState(name);
 
-        if (GraphicsManager::getInstance().isFullScreen() && showMouse == TriBool::True ||
-           !GraphicsManager::getInstance().isFullScreen() && showMouse == TriBool::False)
+        /* Table that maps isFullScreen() and showCursor to mouseExclusive
+        isFullscreen / showCursor | True  | False | Dontcare
+        ----------------------------------------------------
+        true                      | True  | True  | Dontcare
+        ----------------------------------------------------
+        false                     | False | True  | Dontcare
+        */
+        if (showCursor == TriBool::Dontcare)
+            state->setMouseExclusive(TriBool::Dontcare);
+        else if (GraphicsManager::getInstance().isFullScreen() || showCursor == TriBool::False)
             state->setMouseExclusive(TriBool::True);
         else
-            state->setMouseExclusive(TriBool::Dontcare);
-
-        if (showMouse == TriBool::True)
+            state->setMouseExclusive(TriBool::False);
+
+        if (showCursor == TriBool::True)
             state->setMouseHandler(this);
-        else if (showMouse == TriBool::False)
+        else if (showCursor == TriBool::False)
             state->setMouseHandler(&InputHandler::EMPTY);
 
Index: code/branches/gamestates2/src/libraries/core/GUIManager.h
===================================================================
--- code/branches/gamestates2/src/libraries/core/GUIManager.h	(revision 6595)
+++ code/branches/gamestates2/src/libraries/core/GUIManager.h	(revision 6662)
@@ -81,5 +81,5 @@
         void setBackground(const std::string& name);
 
-        const std::string& createInputState(const std::string& name, TriBool::Value showMouse = TriBool::True, TriBool::Value useKeyboard = TriBool::True, bool bBlockJoyStick = false); // tolua_export
+        const std::string& createInputState(const std::string& name, TriBool::Value showCursor = TriBool::True, TriBool::Value useKeyboard = TriBool::True, bool bBlockJoyStick = false); // tolua_export
 
         void setCamera(Ogre::Camera* camera);
Index: code/branches/gamestates2/src/libraries/core/LuaState.cc
===================================================================
--- code/branches/gamestates2/src/libraries/core/LuaState.cc	(revision 6595)
+++ code/branches/gamestates2/src/libraries/core/LuaState.cc	(revision 6662)
@@ -37,4 +37,7 @@
 
 #include "util/Debug.h"
+#include "util/Exception.h"
+#include "util/ScopeGuard.h"
+#include "IOConsole.h"
 #include "Resource.h"
 #include "ToluaBindCore.h"
@@ -54,4 +57,5 @@
         // Create new lua state and configure it
         luaState_ = lua_open();
+        Loki::ScopeGuard luaStateGuard = Loki::MakeGuard(&lua_close, luaState_);
 #if LUA_VERSION_NUM == 501
         luaL_openlibs(luaState_);
@@ -78,5 +82,8 @@
 
         // Parse init script
-        this->doFile("LuaStateInit.lua");
+        if (!this->doFile("LuaStateInit.lua"))
+            ThrowException(InitialisationFailed, "Running LuaStateInit.lua failed");
+
+        luaStateGuard.Dismiss();
     }
 
@@ -96,14 +103,17 @@
     }
 
-    void LuaState::includeFile(const std::string& filename)
+    bool LuaState::includeFile(const std::string& filename)
     {
         shared_ptr<ResourceInfo> sourceInfo = this->getFileInfo(filename);
         if (sourceInfo != NULL)
-            this->includeString(Resource::open(sourceInfo)->getAsString(), sourceInfo);
-        else
-            COUT(2) << "LuaState: Cannot include file '" << filename << "'." << std::endl;
-    }
-
-    void LuaState::includeString(const std::string& code, const shared_ptr<ResourceInfo>& sourceFileInfo)
+            return this->includeString(Resource::open(sourceInfo)->getAsString(), sourceInfo);
+        else
+        {
+            COUT(2) << "LuaState: Cannot include file '" << filename << "' (not found)." << std::endl;
+            return false;
+        }
+    }
+
+    bool LuaState::includeString(const std::string& code, const shared_ptr<ResourceInfo>& sourceFileInfo)
     {
         // Parse string with provided include parser (otherwise don't preparse at all)
@@ -114,17 +124,36 @@
             luaInput = code;
 
-        this->doString(luaInput, sourceFileInfo);
-    }
-
-    void LuaState::doFile(const std::string& filename)
+        if (sourceFileInfo != NULL)
+        {
+            // Also fill a map with the actual source code. This is just for the include* commands
+            // where the content of sourceFileInfo->filename doesn't match 'code'
+            this->sourceCodeMap_[sourceFileInfo->filename] = code;
+        }
+
+        bool returnValue = this->doString(luaInput, sourceFileInfo);
+
+        if (sourceFileInfo != NULL)
+        {
+            // Delete source code entry
+            if (sourceFileInfo != NULL)
+                this->sourceCodeMap_.erase(sourceFileInfo->filename);
+        }
+
+        return returnValue;
+    }
+
+    bool LuaState::doFile(const std::string& filename)
     {
         shared_ptr<ResourceInfo> sourceInfo = this->getFileInfo(filename);
         if (sourceInfo != NULL)
-            this->doString(Resource::open(sourceInfo)->getAsString(), sourceInfo);
-        else
-            COUT(2) << "LuaState: Cannot do file '" << filename << "'." << std::endl;
-    }
-
-    void LuaState::doString(const std::string& code, const shared_ptr<ResourceInfo>& sourceFileInfo)
+            return this->doString(Resource::open(sourceInfo)->getAsString(), sourceInfo);
+        else
+        {
+            COUT(2) << "LuaState: Cannot do file '" << filename << "' (not found)." << std::endl;
+            return false;
+        }
+    }
+
+    bool LuaState::doString(const std::string& code, const shared_ptr<ResourceInfo>& sourceFileInfo)
     {
         // Save the old source file info
@@ -134,31 +163,82 @@
             sourceFileInfo_ = sourceFileInfo;
 
-        int error = 0;
+        std::string chunkname;
+        if (sourceFileInfo != NULL)
+        {
+            // Provide lua_load with the filename for debug purposes
+            // The '@' is a Lua convention to identify the chunk name as filename
+            chunkname = '@' + sourceFileInfo->filename;
+        }
+        else
+        {
+            // Use the code string to identify the chunk
+            chunkname = code;
+        }
+
+        // Push custom error handler that uses the debugger
+        int errorHandler = 1;
+        lua_getglobal(this->luaState_, "errorHandler");
+        if (lua_isnil(this->luaState_, -1))
+        {
+            lua_pop(this->luaState_, 1);
+            errorHandler = 0;
+        }
+
 #if LUA_VERSION_NUM != 501
         LoadS ls;
         ls.s = code.c_str();
         ls.size = code.size();
-        error = lua_load(luaState_, &orxonox::LuaState::lua_Chunkreader, &ls, code.c_str());
+        int error = lua_load(luaState_, &orxonox::LuaState::lua_Chunkreader, &ls, chunkname.c_str());
 #else
-        error = luaL_loadstring(luaState_, code.c_str());
+        int error = luaL_loadbuffer(luaState_, code.c_str(), code.size(), chunkname.c_str());
 #endif
 
-        // execute the chunk
+        switch (error)
+        {
+        case LUA_ERRSYNTAX: // Syntax error
+            COUT(1) << "Lua syntax error: " << lua_tostring(luaState_, -1) << std::endl;
+            break;
+        case LUA_ERRMEM:    // Memory allocation error
+            COUT(1) << "Lua memory allocation error: Consult your dentist immediately!" << std::endl;
+            lua_pop(luaState_, 1);
+            break;
+        }
+
         if (error == 0)
-            error = lua_pcall(luaState_, 0, 1, 0);
+        {
+            // Execute the chunk in protected mode with an error handler function (stack index)
+            error = lua_pcall(luaState_, 0, 1, errorHandler);
+
+            switch (error)
+            {
+            case LUA_ERRRUN: // Runtime error
+                // Remove error string from stack (we already display the error in the
+                // 'errorHandler' Lua function in LuaStateInit.lua)
+                lua_pop(luaState_, 1);
+                break;
+            case LUA_ERRERR: // Error in the error handler
+                COUT(1) << "Lua error in error handler: " << lua_tostring(luaState_, -1) << std::endl;
+                break;
+            case LUA_ERRMEM: // Memory allocation error
+                COUT(1) << "Lua memory allocation error: Consult your dentist immediately!" << std::endl;
+                lua_pop(luaState_, 1);
+                break;
+            }
+        }
+
         if (error != 0)
         {
-            std::string origin;
-            if (sourceFileInfo != NULL)
-                origin = " originating from " + sourceFileInfo_->filename;
-            COUT(1) << "Error in Lua-script" << origin << ": " << lua_tostring(luaState_, -1) << std::endl;
-            // return value is nil
+            // Push a nil return value
             lua_pushnil(luaState_);
         }
-        // push return value because it will get lost since the return value of this function is void
+
+        // Set return value to a global variable because we cannot return a table in this function
+        // here. It would work for numbers, pointers and strings, but certainly not for Lua tables.
         lua_setglobal(luaState_, "LuaStateReturnValue");
 
         // Load the old info again
         sourceFileInfo_ = oldSourceFileInfo;
+
+        return (error == 0);
     }
 
@@ -180,4 +260,24 @@
         else
             return true;
+    }
+
+    //! Returns the content of a file
+    std::string LuaState::getSourceCode(const std::string& filename)
+    {
+        // Try the internal map first to get the actual Lua code
+        // and not just some pseudo Lua-XML code when using include* commands
+        std::map<std::string, std::string>::const_iterator it = this->sourceCodeMap_.find(filename);
+        if (it != this->sourceCodeMap_.end())
+            return it->second;
+        shared_ptr<ResourceInfo> info = Resource::getInfo(filename);
+        if (info == NULL)
+            return "";
+        else
+            return Resource::open(info)->getAsString();
+    }
+
+    bool LuaState::usingIOConsole() const
+    {
+        return IOConsole::exists();
     }
 
Index: code/branches/gamestates2/src/libraries/core/LuaState.h
===================================================================
--- code/branches/gamestates2/src/libraries/core/LuaState.h	(revision 6595)
+++ code/branches/gamestates2/src/libraries/core/LuaState.h	(revision 6662)
@@ -71,13 +71,14 @@
         ~LuaState();
 
-        void doFile(const std::string& filename); // tolua_export
-        void doString(const std::string& code, const shared_ptr<ResourceInfo>& sourceFileInfo = shared_ptr<ResourceInfo>());
+        bool doFile(const std::string& filename); // tolua_export
+        bool doString(const std::string& code, const shared_ptr<ResourceInfo>& sourceFileInfo = shared_ptr<ResourceInfo>());
 
-        void includeFile(const std::string& filename); // tolua_export
-        void includeString(const std::string& code, const shared_ptr<ResourceInfo>& sourceFileInfo = shared_ptr<ResourceInfo>());
+        bool includeFile(const std::string& filename); // tolua_export
+        bool includeString(const std::string& code, const shared_ptr<ResourceInfo>& sourceFileInfo = shared_ptr<ResourceInfo>());
 
         void luaPrint(const std::string& str); // tolua_export
         void luaLog(unsigned int level, const std::string& message); // tolua_export
         bool fileExists(const std::string& filename); // tolua_export
+        std::string getSourceCode(const std::string& filename); // tolua_export
 
         const std::stringstream& getOutput() const { return output_; }
@@ -91,4 +92,6 @@
 
         Functor* createLuaFunctor(const std::string& code) { return new LuaFunctor(code, this); } // tolua_export
+        //! Tells about whether IOConsole was activated. The Lua debugger only works with a normal console.
+        bool usingIOConsole() const; // tolua_export
 
         static bool addToluaInterface(int (*function)(lua_State*), const std::string& name);
@@ -114,4 +117,5 @@
         bool bIsRunning_;
         shared_ptr<ResourceInfo> sourceFileInfo_;
+        std::map<std::string, std::string> sourceCodeMap_;
         std::string (*includeParseFunction_)(const std::string&);
 
Index: code/branches/gamestates2/src/libraries/core/Resource.cc
===================================================================
--- code/branches/gamestates2/src/libraries/core/Resource.cc	(revision 6595)
+++ code/branches/gamestates2/src/libraries/core/Resource.cc	(revision 6662)
@@ -29,5 +29,7 @@
 #include "Resource.h"
 
+#include <boost/filesystem/path.hpp>
 #include <OgreException.h>
+#include <OgreFileSystem.h>
 #include <OgreResourceGroupManager.h>
 
@@ -89,4 +91,10 @@
                 ptr->group = group;
                 ptr->size = it->uncompressedSize;
+                if (dynamic_cast<Ogre::FileSystemArchive*>(it->archive) != NULL)
+                {
+                    boost::filesystem::path base(it->archive->getName());
+                    base /= it->filename;
+                    ptr->fileSystemPath = base.string();
+                }
                 return ptr;
             }
Index: code/branches/gamestates2/src/libraries/core/Resource.h
===================================================================
--- code/branches/gamestates2/src/libraries/core/Resource.h	(revision 6595)
+++ code/branches/gamestates2/src/libraries/core/Resource.h	(revision 6662)
@@ -57,4 +57,6 @@
         //! Uncompressed size
         size_t size;
+        //! Absolute file path ("" for files not on filesystem)
+        std::string fileSystemPath;
     };
 
Index: code/branches/gamestates2/src/libraries/core/input/InputDevice.h
===================================================================
--- code/branches/gamestates2/src/libraries/core/input/InputDevice.h	(revision 6595)
+++ code/branches/gamestates2/src/libraries/core/input/InputDevice.h	(revision 6662)
@@ -159,5 +159,5 @@
             for (unsigned int iB = 0; iB < pressedButtons_.size(); ++iB)
                 for (unsigned int iS = 0; iS < inputStates_.size(); ++iS)
-                    inputStates_[iS]->buttonEvent<ButtonEvent::THold, Traits>(
+                    inputStates_[iS]->buttonEvent<ButtonEvent::THold, Traits::ButtonTypeParam>(
                         this->getDeviceID(), static_cast<DeviceClass*>(this)->getButtonEventArg(pressedButtons_[iB]));
 
@@ -196,5 +196,5 @@
             // Call states
             for (unsigned int i = 0; i < inputStates_.size(); ++i)
-                inputStates_[i]->buttonEvent<ButtonEvent::TPress, Traits>(this->getDeviceID(), static_cast<DeviceClass*>(this)->getButtonEventArg(button));
+                inputStates_[i]->buttonEvent<ButtonEvent::TPress, Traits::ButtonTypeParam>(this->getDeviceID(), static_cast<DeviceClass*>(this)->getButtonEventArg(button));
         }
 
@@ -218,5 +218,5 @@
             // Call states
             for (unsigned int i = 0; i < inputStates_.size(); ++i)
-                inputStates_[i]->buttonEvent<ButtonEvent::TRelease, Traits>(this->getDeviceID(), static_cast<DeviceClass*>(this)->getButtonEventArg(button));
+                inputStates_[i]->buttonEvent<ButtonEvent::TRelease, Traits::ButtonTypeParam>(this->getDeviceID(), static_cast<DeviceClass*>(this)->getButtonEventArg(button));
         }
 
Index: code/branches/gamestates2/src/libraries/core/input/InputHandler.h
===================================================================
--- code/branches/gamestates2/src/libraries/core/input/InputHandler.h	(revision 6595)
+++ code/branches/gamestates2/src/libraries/core/input/InputHandler.h	(revision 6662)
@@ -112,15 +112,15 @@
         virtual ~InputHandler() { }
 
-        template<class T> void buttonEvent(unsigned int device, const T& button, ButtonEvent::TPress)
+        template<class T> void buttonEvent(unsigned int device, T button, ButtonEvent::TPress)
             { this->buttonPressed(button); }
-        template<class T> void buttonEvent(unsigned int device, const T& button, ButtonEvent::TRelease)
+        template<class T> void buttonEvent(unsigned int device, T button, ButtonEvent::TRelease)
             { this->buttonReleased(button); }
-        template<class T> void buttonEvent(unsigned int device, const T& button, ButtonEvent::THold)
+        template<class T> void buttonEvent(unsigned int device, T button, ButtonEvent::THold)
             { this->buttonHeld(button); }
-        void buttonEvent(unsigned int device, JoyStickButtonCode::ByEnum button, ButtonEvent::TPress)
+        template<> void buttonEvent<JoyStickButtonCode::ByEnum>(unsigned int device, JoyStickButtonCode::ByEnum button, ButtonEvent::TPress)
             { this->buttonPressed(device - InputDeviceEnumerator::FirstJoyStick, button); }
-        void buttonEvent(unsigned int device, JoyStickButtonCode::ByEnum button, ButtonEvent::TRelease)
+        template<> void buttonEvent<JoyStickButtonCode::ByEnum>(unsigned int device, JoyStickButtonCode::ByEnum button, ButtonEvent::TRelease)
             { this->buttonReleased(device - InputDeviceEnumerator::FirstJoyStick, button); }
-        void buttonEvent(unsigned int device, JoyStickButtonCode::ByEnum button, ButtonEvent::THold)
+        template<> void buttonEvent<JoyStickButtonCode::ByEnum>(unsigned int device, JoyStickButtonCode::ByEnum button, ButtonEvent::THold)
             { this->buttonHeld(device - InputDeviceEnumerator::FirstJoyStick, button); }
 
Index: code/branches/gamestates2/src/libraries/core/input/InputManager.cc
===================================================================
--- code/branches/gamestates2/src/libraries/core/input/InputManager.cc	(revision 6595)
+++ code/branches/gamestates2/src/libraries/core/input/InputManager.cc	(revision 6662)
@@ -95,4 +95,7 @@
         CCOUT(4) << "Constructing..." << std::endl;
 
+        // Allocate space for the function call buffer
+        this->callBuffer_.reserve(16);
+
         this->setConfigValues();
 
@@ -266,12 +269,17 @@
         CCOUT(3) << "Destroying..." << std::endl;
 
+        // Leave all active InputStates (except "empty")
+        while (this->activeStates_.size() > 1)
+            this->leaveState(this->activeStates_.rbegin()->second->getName());
+        this->activeStates_.clear();
+
         // Destroy calibrator helper handler and state
         this->destroyState("calibrator");
         // Destroy KeyDetector and state
         calibratorCallbackHandler_->destroy();
-        // destroy the empty InputState
+        // Destroy the empty InputState
         this->destroyStateInternal(this->emptyState_);
 
-        // destroy all user InputStates
+        // Destroy all user InputStates
         while (statesByName_.size() > 0)
             this->destroyStateInternal(statesByName_.rbegin()->second);
@@ -335,12 +343,5 @@
     void InputManager::reload()
     {
-        if (internalState_ & Ticking)
-        {
-            // We cannot destroy OIS right now, because reload was probably
-            // caused by a user clicking on a GUI item. The stack trace would then
-            // include an OIS method. So it would be a very bad thing to destroy it..
-            internalState_ |= ReloadRequest;
-        }
-        else if (internalState_ & Calibrating)
+        if (internalState_ & Calibrating)
             CCOUT(2) << "Warning: Cannot reload input system. Joy sticks are currently being calibrated." << std::endl;
         else
@@ -351,5 +352,5 @@
     void InputManager::reloadInternal()
     {
-        CCOUT(3) << "Reloading ..." << std::endl;
+        CCOUT(4) << "Reloading ..." << std::endl;
 
         this->destroyDevices();
@@ -357,5 +358,4 @@
 
         internalState_ &= ~Bad;
-        internalState_ &= ~ReloadRequest;
         CCOUT(4) << "Reloading complete." << std::endl;
     }
@@ -370,68 +370,4 @@
         if (internalState_ & Bad)
             ThrowException(General, "InputManager was not correctly reloaded.");
-
-        else if (internalState_ & ReloadRequest)
-            reloadInternal();
-
-        // check for states to leave
-        if (!stateLeaveRequests_.empty())
-        {
-            for (std::set<InputState*>::iterator it = stateLeaveRequests_.begin();
-                it != stateLeaveRequests_.end(); ++it)
-            {
-                (*it)->left();
-                // just to be sure that the state actually is registered
-                assert(statesByName_.find((*it)->getName()) != statesByName_.end());
-
-                activeStates_.erase((*it)->getPriority());
-                if ((*it)->getPriority() < InputStatePriority::HighPriority)
-                    (*it)->setPriority(0);
-                updateActiveStates();
-            }
-            stateLeaveRequests_.clear();
-        }
-
-        // check for states to enter
-        if (!stateEnterRequests_.empty())
-        {
-            for (std::set<InputState*>::const_iterator it = stateEnterRequests_.begin();
-                it != stateEnterRequests_.end(); ++it)
-            {
-                // just to be sure that the state actually is registered
-                assert(statesByName_.find((*it)->getName()) != statesByName_.end());
-
-                if ((*it)->getPriority() == 0)
-                {
-                    // Get smallest possible priority between 1 and maxStateStackSize_s
-                    for (std::map<int, InputState*>::reverse_iterator rit = activeStates_.rbegin();
-                        rit != activeStates_.rend(); ++rit)
-                    {
-                        if (rit->first < InputStatePriority::HighPriority)
-                        {
-                            (*it)->setPriority(rit->first + 1);
-                            break;
-                        }
-                    }
-                    // In case no normal handler was on the stack
-                    if ((*it)->getPriority() == 0)
-                        (*it)->setPriority(1);
-                }
-                activeStates_[(*it)->getPriority()] = (*it);
-                updateActiveStates();
-                (*it)->entered();
-            }
-            stateEnterRequests_.clear();
-        }
-
-        // check for states to destroy
-        if (!stateDestroyRequests_.empty())
-        {
-            for (std::set<InputState*>::iterator it = stateDestroyRequests_.begin();
-                it != stateDestroyRequests_.end(); ++it)
-            {
-                destroyStateInternal((*it));
-            }
-            stateDestroyRequests_.clear();
-        }
 
         // check whether a state has changed its EMPTY situation
@@ -448,17 +384,25 @@
             updateActiveStates();
 
-        // mark that we now start capturing and distributing input
-        internalState_ |= Ticking;
-
-        // Capture all the input and handle it
+        // Capture all the input and collect the function calls
+        // No event gets triggered here yet!
         BOOST_FOREACH(InputDevice* device, devices_)
             if (device != NULL)
                 device->update(time);
 
-        // Update the states
+        // Collect functions calls for the update
         for (unsigned int i = 0; i < activeStatesTicked_.size(); ++i)
             activeStatesTicked_[i]->update(time.getDeltaTime());
 
-        internalState_ &= ~Ticking;
+        // Execute all cached function calls in order
+        // Why so complicated? The problem is that an InputHandler could trigger
+        // a reload that would destroy the OIS devices or it could even leave and
+        // then destroy its own InputState. That would of course lead to access
+        // violations.
+        // If we delay the calls, then OIS and and the InputStates are not anymore
+        // in the call stack and can therefore be edited.
+        for (size_t i = 0; i < this->callBuffer_.size(); ++i)
+            this->callBuffer_[i]();
+
+        this->callBuffer_.clear();
     }
 
@@ -470,5 +414,4 @@
     void InputManager::updateActiveStates()
     {
-        assert((internalState_ & InputManager::Ticking) == 0);
         // temporary resize
         for (unsigned int i = 0; i < devices_.size(); ++i)
@@ -622,23 +565,28 @@
         // get pointer from the map with all stored handlers
         std::map<std::string, InputState*>::const_iterator it = statesByName_.find(name);
-        if (it != statesByName_.end())
-        {
-            // exists
-            if (activeStates_.find(it->second->getPriority()) == activeStates_.end())
-            {
-                // not active
-                if (stateDestroyRequests_.find(it->second) == stateDestroyRequests_.end())
+        if (it != statesByName_.end() && activeStates_.find(it->second->getPriority()) == activeStates_.end())
+        {
+            // exists and not active
+            if (it->second->getPriority() == 0)
+            {
+                // Get smallest possible priority between 1 and maxStateStackSize_s
+                for (std::map<int, InputState*>::reverse_iterator rit = activeStates_.rbegin();
+                    rit != activeStates_.rend(); ++rit)
                 {
-                    // not scheduled for destruction
-                    // prevents a state from being added multiple times
-                    stateEnterRequests_.insert(it->second);
-                    return true;
+                    if (rit->first < InputStatePriority::HighPriority)
+                    {
+                        it->second->setPriority(rit->first + 1);
+                        break;
+                    }
                 }
-            }
-            else if (this->stateLeaveRequests_.find(it->second) != this->stateLeaveRequests_.end())
-            {
-                // State already scheduled for leaving --> cancel
-                this->stateLeaveRequests_.erase(this->stateLeaveRequests_.find(it->second));
-            }
+                // In case no normal handler was on the stack
+                if (it->second->getPriority() == 0)
+                    it->second->setPriority(1);
+            }
+            activeStates_[it->second->getPriority()] = it->second;
+            updateActiveStates();
+            it->second->entered();
+
+            return true;
         }
         return false;
@@ -654,18 +602,16 @@
         // get pointer from the map with all stored handlers
         std::map<std::string, InputState*>::const_iterator it = statesByName_.find(name);
-        if (it != statesByName_.end())
-        {
-            // exists
-            if (activeStates_.find(it->second->getPriority()) != activeStates_.end())
-            {
-                // active
-                stateLeaveRequests_.insert(it->second);
-                return true;
-            }
-            else if (this->stateEnterRequests_.find(it->second) != this->stateEnterRequests_.end())
-            {
-                // State already scheduled for entering --> cancel
-                this->stateEnterRequests_.erase(this->stateEnterRequests_.find(it->second));
-            }
+        if (it != statesByName_.end() && activeStates_.find(it->second->getPriority()) != activeStates_.end())
+        {
+            // exists and active
+
+            it->second->left();
+
+            activeStates_.erase(it->second->getPriority());
+            if (it->second->getPriority() < InputStatePriority::HighPriority)
+                it->second->setPriority(0);
+            updateActiveStates();
+
+            return true;
         }
         return false;
@@ -682,17 +628,6 @@
         if (it != statesByName_.end())
         {
-            if (activeStates_.find(it->second->getPriority()) != activeStates_.end())
-            {
-                // The state is still active. We have to postpone
-                stateLeaveRequests_.insert(it->second);
-                stateDestroyRequests_.insert(it->second);
-            }
-            else if (this->internalState_ & Ticking)
-            {
-                // cannot remove state while ticking
-                stateDestroyRequests_.insert(it->second);
-            }
-            else
-                destroyStateInternal(it->second);
+            this->leaveState(name);
+            destroyStateInternal(it->second);
 
             return true;
@@ -704,11 +639,5 @@
     void InputManager::destroyStateInternal(InputState* state)
     {
-        assert(state && !(this->internalState_ & Ticking));
-        std::map<int, InputState*>::iterator it = this->activeStates_.find(state->getPriority());
-        if (it != this->activeStates_.end())
-        {
-            this->activeStates_.erase(it);
-            updateActiveStates();
-        }
+        assert(state && this->activeStates_.find(state->getPriority()) == this->activeStates_.end());
         statesByName_.erase(state->getName());
         state->destroy();
Index: code/branches/gamestates2/src/libraries/core/input/InputManager.h
===================================================================
--- code/branches/gamestates2/src/libraries/core/input/InputManager.h	(revision 6595)
+++ code/branches/gamestates2/src/libraries/core/input/InputManager.h	(revision 6662)
@@ -36,9 +36,9 @@
 #include <string>
 #include <vector>
+#include <boost/function.hpp>
 
 #include "util/Singleton.h"
 #include "util/TriBool.h"
 #include "core/WindowEventListener.h"
-#include "InputState.h"
 
 // tolua_begin
@@ -76,7 +76,5 @@
             Nothing       = 0x00,
             Bad           = 0x02,
-            Ticking       = 0x04,
-            Calibrating   = 0x08,
-            ReloadRequest = 0x10,
+            Calibrating   = 0x04,
         };
 
@@ -170,5 +168,14 @@
         //! Returns a pointer to the OIS InputManager. Only you if you know what you're doing!
         OIS::InputManager* getOISInputManager() { return this->oisInputManager_; }
+        //! Returns the position of the cursor as std::pair of ints
         std::pair<int, int> getMousePosition() const;
+        //! Tells whether the mouse is used exclusively to the game
+        bool isMouseExclusive() const { return this->exclusiveMouse_; } // tolua_export
+
+        //-------------------------------
+        // Function call caching
+        //-------------------------------
+        void pushCall(const boost::function<void ()>& function)
+            { this->callBuffer_.push_back(function); }
 
         static InputManager& getInstance() { return Singleton<InputManager>::getInstance(); } // tolua_export
@@ -208,7 +215,5 @@
         std::vector<InputState*>            activeStatesTicked_;   //!< Like activeStates_, but only contains the ones that currently receive events
 
-        std::set<InputState*>               stateEnterRequests_;   //!< Requests to enter a new state
-        std::set<InputState*>               stateLeaveRequests_;   //!< Requests to leave a running state
-        std::set<InputState*>               stateDestroyRequests_; //!< Requests to destroy a state
+        std::vector<boost::function<void ()> > callBuffer_;        //!< Caches all calls from InputStates to be executed afterwards (see preUpdate)
 
         static InputManager*                singletonPtr_s;        //!< Pointer reference to the singleton
Index: code/branches/gamestates2/src/libraries/core/input/InputPrereqs.h
===================================================================
--- code/branches/gamestates2/src/libraries/core/input/InputPrereqs.h	(revision 6595)
+++ code/branches/gamestates2/src/libraries/core/input/InputPrereqs.h	(revision 6662)
@@ -42,4 +42,5 @@
 #include <ois/OISMouse.h>
 #include <ois/OISJoyStick.h>
+#include "util/OrxEnum.h"
 
 namespace orxonox
@@ -448,4 +449,18 @@
         };
     }
+
+    //! Enumeration wrapper for input state priorities
+    struct InputStatePriority : OrxEnum<InputStatePriority>
+    {
+        OrxEnumConstructors(InputStatePriority);
+
+        static const int Empty        = -1;
+        static const int Dynamic      = 0;
+
+        static const int HighPriority = 1000;
+        static const int Console      = HighPriority + 0;
+        static const int Calibrator   = HighPriority + 1;
+        static const int Detector     = HighPriority + 2;
+    };
 }
 
Index: code/branches/gamestates2/src/libraries/core/input/InputState.h
===================================================================
--- code/branches/gamestates2/src/libraries/core/input/InputState.h	(revision 6595)
+++ code/branches/gamestates2/src/libraries/core/input/InputState.h	(revision 6662)
@@ -35,27 +35,17 @@
 #include <string>
 #include <vector>
-
-#include "util/OrxEnum.h"
+#include <boost/function.hpp>
+#include <boost/bind.hpp>
+
 #include "util/TriBool.h"
 #include "InputHandler.h"
+#include "InputManager.h"
 #include "JoyStickQuantityListener.h"
+
+#define INPUT_STATE_PUSH_CALL(deviceIndex, functionName, ...) \
+    InputManager::getInstance().pushCall(boost::function<void ()>(boost::bind(&InputHandler::functionName, handlers_[deviceIndex], __VA_ARGS__)))
 
 namespace orxonox
 {
-    //! Enumeration wrapper for input state priorities
-    struct InputStatePriority : OrxEnum<InputStatePriority>
-    {
-        OrxEnumConstructors(InputStatePriority);
-
-        static const int Empty        = -1;
-        static const int Dynamic      = 0;
-
-        static const int HighPriority = 1000;
-        static const int Console      = HighPriority + 0;
-        static const int Calibrator   = HighPriority + 1;
-        static const int Detector     = HighPriority + 2;
-    };
-
-
     /**
     @brief
@@ -144,6 +134,6 @@
 
         //! Generic function that distributes all 9 button events
-        template <typename EventType, class Traits>
-        void buttonEvent(unsigned int device, const typename Traits::ButtonTypeParam button);
+        template <typename EventType, class ButtonTypeParam>
+        void buttonEvent(unsigned int device, ButtonTypeParam button);
 
         //! Event handler
@@ -190,5 +180,5 @@
         for (unsigned int i = 0; i < handlers_.size(); ++i)
             if (handlers_[i] != NULL)
-                handlers_[i]->allDevicesUpdated(dt);
+                INPUT_STATE_PUSH_CALL(i, allDevicesUpdated, dt);
     }
 
@@ -199,25 +189,29 @@
         case InputDeviceEnumerator::Keyboard:
             if (handlers_[keyboardIndex_s] != NULL)
-                handlers_[keyboardIndex_s]->keyboardUpdated(dt);
+                INPUT_STATE_PUSH_CALL(keyboardIndex_s, keyboardUpdated, dt);
             break;
 
         case InputDeviceEnumerator::Mouse:
             if (handlers_[mouseIndex_s] != NULL)
-                handlers_[mouseIndex_s]->mouseUpdated(dt);
+                INPUT_STATE_PUSH_CALL(mouseIndex_s, mouseUpdated, dt);
             break;
 
         default: // joy sticks
             if (handlers_[device] != NULL)
-                handlers_[device]->joyStickUpdated(device - firstJoyStickIndex_s, dt);
+                INPUT_STATE_PUSH_CALL(device, joyStickUpdated, device - firstJoyStickIndex_s, dt);
             break;
         }
     }
 
-    template <typename EventType, class Traits>
-    FORCEINLINE void InputState::buttonEvent(unsigned int device, const typename Traits::ButtonTypeParam button)
+    template <typename EventType, class ButtonTypeParam>
+    FORCEINLINE void InputState::buttonEvent(unsigned int device, typename ButtonTypeParam button)
     {
         assert(device < handlers_.size());
         if (handlers_[device] != NULL)
-            handlers_[device]->buttonEvent(device, button, EventType());
+        {
+            // We have to store the function pointer to tell the compiler about its actual type because of overloading
+            void (InputHandler::*function)(unsigned int, ButtonTypeParam, EventType) = &InputHandler::buttonEvent<ButtonTypeParam>;
+            InputManager::getInstance().pushCall(boost::function<void ()>(boost::bind(function, handlers_[device], device, button, EventType())));
+        }
     }
 
@@ -225,5 +219,5 @@
     {
         if (handlers_[mouseIndex_s] != NULL)
-            handlers_[mouseIndex_s]->mouseMoved(abs, rel, clippingSize);
+            INPUT_STATE_PUSH_CALL(mouseIndex_s, mouseMoved, abs, rel, clippingSize);
     }
 
@@ -231,5 +225,5 @@
     {
         if (handlers_[mouseIndex_s] != NULL)
-            handlers_[mouseIndex_s]->mouseScrolled(abs, rel);
+            INPUT_STATE_PUSH_CALL(mouseIndex_s, mouseScrolled, abs, rel);
     }
 
@@ -238,5 +232,5 @@
         assert(device < handlers_.size());
         if (handlers_[device] != NULL)
-            handlers_[device]->axisMoved(device - firstJoyStickIndex_s, axis, value);
+            INPUT_STATE_PUSH_CALL(device, axisMoved, device - firstJoyStickIndex_s, axis, value);
     }
 }
Index: code/branches/gamestates2/src/libraries/util/Singleton.h
===================================================================
--- code/branches/gamestates2/src/libraries/util/Singleton.h	(revision 6595)
+++ code/branches/gamestates2/src/libraries/util/Singleton.h	(revision 6662)
@@ -49,5 +49,5 @@
     public:
         //! Returns a reference to the singleton instance
-        static T& getInstance()
+        FORCEINLINE static T& getInstance()
         {
             assert(T::singletonPtr_s != NULL);
@@ -56,5 +56,5 @@
 
         //! Tells whether the singleton has been created
-        static bool exists()
+        FORCEINLINE static bool exists()
         {
             return (T::singletonPtr_s != NULL);
@@ -62,11 +62,11 @@
 
         //! Update method called by ClassSingletonManager (if used)
-        void preUpdateSingleton(const Clock& time) { static_cast<T*>(T::singletonPtr_s)->preUpdate(time); }
+        FORCEINLINE void preUpdateSingleton(const Clock& time) { static_cast<T*>(T::singletonPtr_s)->preUpdate(time); }
         //! Empty update method for the static polymorphism
-        void preUpdate(const Clock& time) { }
+        FORCEINLINE void preUpdate(const Clock& time) { }
         //! Update method called by ClassSingletonManager (if used)
-        void postUpdateSingleton(const Clock& time) { static_cast<T*>(T::singletonPtr_s)->postUpdate(time); }
+        FORCEINLINE void postUpdateSingleton(const Clock& time) { static_cast<T*>(T::singletonPtr_s)->postUpdate(time); }
         //! Empty update method for the static polymorphism
-        void postUpdate(const Clock& time) { }
+        FORCEINLINE void postUpdate(const Clock& time) { }
 
     protected:
