Index: code/branches/gui/src/core/CMakeLists.txt
===================================================================
--- code/branches/gui/src/core/CMakeLists.txt	(revision 1636)
+++ code/branches/gui/src/core/CMakeLists.txt	(revision 1638)
@@ -4,4 +4,5 @@
   Core.cc
   Error.cc
+  Exception.cc
   Language.cc
   OrxonoxClass.cc
@@ -41,4 +42,5 @@
   input/Button.cc
   input/CalibratorCallback.cc
+  input/ExtendedInputState.cc
   input/HalfAxis.cc
   input/InputBuffer.cc
@@ -47,4 +49,5 @@
   input/KeyBinder.cc
   input/KeyDetector.cc
+  input/SimpleInputState.cc
 
   tolua/tolua_bind.cc
Index: code/branches/gui/src/core/ClassTreeMask.h
===================================================================
--- code/branches/gui/src/core/ClassTreeMask.h	(revision 1636)
+++ code/branches/gui/src/core/ClassTreeMask.h	(revision 1638)
@@ -60,5 +60,5 @@
     step back, and so on.
 
-    Example: A and B are childs of BaseObject, A1 and A2 are childs of A, B1 and B2 are childs of B.
+    Example: A and B are children of BaseObject, A1 and A2 are children of A, B1 and B2 are children of B.
     The ClassTreeMaskIterator would move trough the tree in the following order:
     BaseObject, A, A1, A2, B, B1, B2.
Index: code/branches/gui/src/core/CommandExecutor.h
===================================================================
--- code/branches/gui/src/core/CommandExecutor.h	(revision 1636)
+++ code/branches/gui/src/core/CommandExecutor.h	(revision 1638)
@@ -36,10 +36,13 @@
 #include "CommandEvaluation.h"
 
-namespace orxonox
-{
+namespace orxonox // tolua_export
+{ // tolua_export
     class _CoreExport CommandExecutor
+    /*
+    class CommandExecutor { // tolua_export
+    */
     {
         public:
-            static bool execute(const std::string& command, bool useTcl = true);
+            static bool execute(const std::string& command, bool useTcl = true); // tolua_export
             static std::string complete(const std::string& command);
             static std::string hint(const std::string& command);
@@ -98,6 +101,6 @@
             std::map<std::string, ConsoleCommand*> consoleCommandShortcuts_;
             std::map<std::string, ConsoleCommand*> consoleCommandShortcuts_LC_;
-    };
-}
+    }; // tolua_export
+} // tolua_export
 
 #endif /* _CommandExecutor_H__ */
Index: code/branches/gui/src/core/Core.cc
===================================================================
--- code/branches/gui/src/core/Core.cc	(revision 1636)
+++ code/branches/gui/src/core/Core.cc	(revision 1638)
@@ -23,5 +23,5 @@
  *      Fabian 'x3n' Landau
  *   Co-authors:
- *      ...
+ *      Reto Grieder
  *
  */
Index: code/branches/gui/src/core/Core.h
===================================================================
--- code/branches/gui/src/core/Core.h	(revision 1636)
+++ code/branches/gui/src/core/Core.h	(revision 1638)
@@ -23,5 +23,5 @@
  *      Fabian 'x3n' Landau
  *   Co-authors:
- *      ...
+ *      Reto Grieder
  *
  */
@@ -29,5 +29,5 @@
 /**
     @file Core.h
-    @brief Definition of the Core class.
+    @brief Declaration of the Core class.
 
     The Core class is a singleton, only used to configure some variables
Index: code/branches/gui/src/core/CoreIncludes.h
===================================================================
--- code/branches/gui/src/core/CoreIncludes.h	(revision 1636)
+++ code/branches/gui/src/core/CoreIncludes.h	(revision 1638)
@@ -105,5 +105,5 @@
     @param StringOrInt The name or the network ID of the class
 */
-#define ID(StringOrInt) \
+#define GetIdentifier(StringOrInt) \
     orxonox::Factory::getIdentifier(StringOrInt)
 
Index: code/branches/gui/src/core/CorePrereqs.h
===================================================================
--- code/branches/gui/src/core/CorePrereqs.h	(revision 1636)
+++ code/branches/gui/src/core/CorePrereqs.h	(revision 1638)
@@ -158,12 +158,13 @@
 
   // input
-  //class GUIInputHandler;
   class BaseCommand;
   class BufferedParamCommand;
   class Button;
   class CalibratorCallback;
+  class ExtendedInputState;
   class HalfAxis;
   class InputBuffer;
   class InputManager;
+  class InputState;
   class JoyStickHandler;
   class MouseHandler;
@@ -173,4 +174,5 @@
   class ParamCommand;
   class SimpleCommand;
+  class SimpleInputState;
 }
 
Index: code/branches/gui/src/core/Error.cc
===================================================================
--- code/branches/gui/src/core/Error.cc	(revision 1636)
+++ code/branches/gui/src/core/Error.cc	(revision 1638)
@@ -37,23 +37,23 @@
 namespace orxonox
 {
-	Error::Error(std::string errorMsg, int errorCode)
-	{
-		COUT(1) << "############################ "<< std::endl
-							<< "#         Error "<<errorCode<< "          #"<< std::endl
-							<< "############################ "<< std::endl
-							<< "An error occured in Orxonox: "<< std::endl;
+    Error::Error(std::string errorMsg, int errorCode)
+    {
+        COUT(1) << "############################ "<< std::endl
+                            << "#         Error "<<errorCode<< "          #"<< std::endl
+                            << "############################ "<< std::endl
+                            << "An error occured in Orxonox: "<< std::endl;
 
-		if (errorMsg=="")
-		{
-			switch (errorCode)
-			{
-				case 1:
-					errorMsg = "Some error!";
-					break;
-				default:
-					errorMsg = "Unknown error!";
-			}
-		}
-		COUT(1) << errorMsg << std::endl<< std::endl;
-	}
+        if (errorMsg=="")
+        {
+            switch (errorCode)
+            {
+                case 1:
+                    errorMsg = "Some error!";
+                    break;
+                default:
+                    errorMsg = "Unknown error!";
+            }
+        }
+        COUT(1) << errorMsg << std::endl<< std::endl;
+    }
 }
Index: code/branches/gui/src/core/Error.h
===================================================================
--- code/branches/gui/src/core/Error.h	(revision 1636)
+++ code/branches/gui/src/core/Error.h	(revision 1638)
@@ -29,5 +29,5 @@
 /**
     @file Error.h
-    @brief Definition of the Error class.
+    @brief Declaration of the Error class.
 */
 
@@ -41,11 +41,11 @@
 namespace orxonox
 {
-	class _CoreExport Error
-	{
-	public:
-		Error(std::string errorMsg = "", int errorCode = 0);
-	private:
+    class _CoreExport Error
+    {
+    public:
+        Error(std::string errorMsg = "", int errorCode = 0);
+    private:
 
-	};
+    };
 }
 
Index: code/branches/gui/src/core/Exception.cc
===================================================================
--- code/branches/gui/src/core/Exception.cc	(revision 1638)
+++ code/branches/gui/src/core/Exception.cc	(revision 1638)
@@ -0,0 +1,80 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief
+    Implementation of the Exception class.
+*/
+
+#include "Exception.h"
+
+namespace orxonox
+{
+    Exception::Exception(const std::string& description, int lineNumber,
+                         const char* fileName, const char* functionName)
+        : description_(description)
+        , lineNumber_(lineNumber)
+        , functionName_(functionName)
+        , fileName_(fileName)
+    { }
+
+    Exception::Exception(const std::string& description)
+        : description_(description)
+        , lineNumber_(0)
+        , functionName_("")
+        , fileName_("")
+    { }
+
+    std::string Exception::getFullDescription() const
+    {
+        std::ostringstream fullDesc;
+
+        fullDesc << this->getTypeName() << "_EXCEPTION";
+
+        if (this->fileName_ != "")
+        {
+            fullDesc << " in " << this->fileName_;
+            if (this->lineNumber_)
+                fullDesc << "(" << this->lineNumber_ << ")";
+        }
+
+        if (this->functionName_ != "")
+            fullDesc << " in function '" << this->functionName_ << "'";
+
+        fullDesc << ": ";
+        if (this->description_ != "")
+            fullDesc << this->description_;
+        else
+            fullDesc << "No description available.";
+
+        return fullDesc.str();
+    }
+
+
+}
Index: code/branches/gui/src/core/Exception.h
===================================================================
--- code/branches/gui/src/core/Exception.h	(revision 1638)
+++ code/branches/gui/src/core/Exception.h	(revision 1638)
@@ -0,0 +1,133 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief
+    Declaration of the Exception class.
+*/
+
+#ifndef _Exception_H__
+#define _Exception_H__
+
+#include "CorePrereqs.h"
+
+#include <string>
+#include <exception>
+#include "core/Debug.h"
+
+namespace orxonox
+{
+    class _CoreExport Exception : public std::exception
+    {
+    public:
+        enum ExceptionType
+        {
+            General,
+            FileNotFound,
+            PluginsNotFound,
+            NotImplemented
+        };
+
+        Exception(const std::string& description, int lineNumber,
+                  const char* fileName, const char* functionName);
+        Exception(const std::string& description);
+
+        /// Needed for  compatibility with std::exception (from Ogre::Exception)
+        virtual ~Exception() throw() { }
+
+        virtual std::string        getFullDescription() const;
+        virtual ExceptionType      getType()            const = 0;
+        virtual std::string        getTypeName()        const = 0;
+        virtual const std::string& getDescription()     const { return this->description_; }
+        virtual const int          getLineNumber()      const { return this->lineNumber_; }
+        virtual const std::string& getFunctionName()    const { return this->functionName_; }
+
+        /// Override std::exception::what (from Ogre::Exception)
+        const char* what() const throw() { return getFullDescription().c_str(); }
+
+    protected:
+        std::string description_;
+        int lineNumber_;
+        std::string functionName_;
+        std::string fileName_;
+    };
+
+
+    template <Exception::ExceptionType Type>
+    class SpecificException : public Exception
+    {
+    public:
+        SpecificException(const std::string& description, int lineNumber,
+                  const char* fileName, const char* functionName)
+                  : Exception(description, lineNumber, fileName, functionName)
+        {
+            // let the catcher decide whether to display the message or not
+            //COUT(1) << this->getFullDescription() << std::endl;
+        }
+
+        SpecificException(const std::string& description)
+            : Exception(description)
+        {
+            // let the catcher decide whether to display the message or not
+            //COUT(1) << this->getFullDescription() << std::endl;
+        }
+
+        ~SpecificException() { }
+
+        ExceptionType getType() const { return Type; }
+        std::string getTypeName() const
+        {
+            // note: break is not necessary due to the return. Keep in mind!
+            switch (Type)
+            {
+            case Exception::General:
+                return "General";
+            case Exception::FileNotFound:
+                return "FileNotFound";
+            case Exception::PluginsNotFound:
+                return "PluginsNotFound";
+            case Exception::NotImplemented:
+                return "NotImplemented";
+            default:
+                return "";
+            }
+        }
+    };
+
+    typedef SpecificException<Exception::General> GeneralException;
+    typedef SpecificException<Exception::FileNotFound> FileNotFoundException;
+    typedef SpecificException<Exception::PluginsNotFound> PluginsNotFoundException;
+    typedef SpecificException<Exception::NotImplemented> NotImplementedException;
+
+#define ThrowException(type, description) \
+    throw SpecificException<Exception::type>(description, __LINE__, __FILE__, __FUNCTIONNAME__)
+
+}
+
+#endif /* _Exception_H__ */
Index: code/branches/gui/src/core/Identifier.h
===================================================================
--- code/branches/gui/src/core/Identifier.h	(revision 1636)
+++ code/branches/gui/src/core/Identifier.h	(revision 1638)
@@ -76,5 +76,5 @@
          - the name
          - a list with all objects
-         - parents and childs
+         - parents and children
          - the factory (if available)
          - the networkID that can be synchronised with the server
Index: code/branches/gui/src/core/OrxonoxClass.h
===================================================================
--- code/branches/gui/src/core/OrxonoxClass.h	(revision 1636)
+++ code/branches/gui/src/core/OrxonoxClass.h	(revision 1638)
@@ -29,5 +29,5 @@
 /**
     @file OrxonoxClass.h
-    @brief Definition of the OrxonoxClass Class.
+    @brief Declaration of the OrxonoxClass Class.
 
     All objects and interfaces of the game-logic (not the engine) are derived from OrxonoxClass.
Index: code/branches/gui/src/core/Script.cc
===================================================================
--- code/branches/gui/src/core/Script.cc	(revision 1636)
+++ code/branches/gui/src/core/Script.cc	(revision 1638)
@@ -60,5 +60,5 @@
     luaopen_debug(luaState_);
 #endif
-    tolua_core_open(luaState_);
+    tolua_Core_open(luaState_);
     output_ = "";
   }
Index: code/branches/gui/src/core/Shell.cc
===================================================================
--- code/branches/gui/src/core/Shell.cc	(revision 1636)
+++ code/branches/gui/src/core/Shell.cc	(revision 1638)
@@ -34,4 +34,6 @@
 #include "ConsoleCommand.h"
 #include "input/InputInterfaces.h"
+#include "input/SimpleInputState.h"
+#include "input/InputManager.h"
 
 #define SHELL_UPDATE_LISTENERS(function) \
@@ -57,10 +59,21 @@
         this->clearLines();
 
-        this->inputBuffer_ = 0;
-        this->setInputBuffer(new InputBuffer());
+        this->inputBuffer_ = new InputBuffer();
+        this->configureInputBuffer();
+        InputManager::createSimpleInputState("console", 40)->setKeyHandler(this->inputBuffer_);
 
         this->outputBuffer_.registerListener(this);
 
         this->setConfigValues();
+    }
+
+    Shell::~Shell()
+    {
+        SimpleInputState * inputState = dynamic_cast<SimpleInputState*>(InputManager::getState("console"));
+        if (inputState)
+        {
+            inputState->removeAndDestroyAllHandlers();
+            InputManager::destroyState("console");
+        }
     }
 
@@ -97,14 +110,6 @@
     }
 
-    void Shell::setInputBuffer(InputBuffer* buffer)
-    {
-        if (this->inputBuffer_)
-        {
-            this->inputBuffer_->unregisterListener(this);
-            // TODO: may be very dangerous. InputManager already deletes InputBuffer instance!!!
-            delete this->inputBuffer_;
-        }
-
-        this->inputBuffer_ = buffer;
+    void Shell::configureInputBuffer()
+    {
         this->inputBuffer_->registerListener(this, &Shell::inputChanged, true);
         this->inputBuffer_->registerListener(this, &Shell::execute, '\r', false);
Index: code/branches/gui/src/core/Shell.h
===================================================================
--- code/branches/gui/src/core/Shell.h	(revision 1636)
+++ code/branches/gui/src/core/Shell.h	(revision 1638)
@@ -71,5 +71,4 @@
             void unregisterListener(ShellListener* listener);
 
-            void setInputBuffer(InputBuffer* buffer);
             inline InputBuffer& getInputBuffer()
                 { return (*this->inputBuffer_); }
@@ -105,5 +104,7 @@
             Shell();
             Shell(const Shell& other);
-            virtual ~Shell() {}
+            virtual ~Shell();
+
+            void configureInputBuffer();
 
             void addToHistory(const std::string& command);
Index: code/branches/gui/src/core/SignalHandler.h
===================================================================
--- code/branches/gui/src/core/SignalHandler.h	(revision 1636)
+++ code/branches/gui/src/core/SignalHandler.h	(revision 1638)
@@ -29,5 +29,5 @@
 /**
     @file SignalHandler.h
-    @brief Definition of the SignalHandler class.
+    @brief Declaration of the SignalHandler class.
 */
 
Index: code/branches/gui/src/core/XMLPort.h
===================================================================
--- code/branches/gui/src/core/XMLPort.h	(revision 1636)
+++ code/branches/gui/src/core/XMLPort.h	(revision 1638)
@@ -288,5 +288,5 @@
                             for (ticpp::Iterator<ticpp::Element> child = xmlsubelement->FirstChildElement(false); child != child.end(); child++)
                             {
-                                Identifier* identifier = ID(child->Value());
+                                Identifier* identifier = GetIdentifier(child->Value());
                                 if (identifier)
                                 {
Index: code/branches/gui/src/core/input/Button.cc
===================================================================
--- code/branches/gui/src/core/input/Button.cc	(revision 1636)
+++ code/branches/gui/src/core/input/Button.cc	(revision 1638)
@@ -28,7 +28,8 @@
 
 /**
- @file
- @brief Implementation of the different input handlers.
- */
+@file
+@brief
+    Implementation of the different input handlers.
+*/
 
 #include "Button.h"
@@ -44,172 +45,187 @@
 namespace orxonox
 {
-  void Button::clear()
-  {
-    for (unsigned int j = 0; j < 3; j++)
-    {
-      if (nCommands_[j])
-      {
-        // delete all commands and the command pointer array
-        for (unsigned int i = 0; i < nCommands_[j]; i++)
-          delete commands_[j][i];
-        delete[] commands_[j];
-        commands_[j] = 0;
-        nCommands_[j] = 0;
-      }
-      else
-      {
-        commands_[j] = 0;
-      }
-    }
-  }
-
-  void Button::parse(std::vector<BufferedParamCommand*>& paramCommandBuffer)
-  {
-    if (isEmpty(bindingString_))
-    {
-      clear();
-      return;
-    }
-
-    // use std::vector for a temporary dynamic array
-    std::vector<BaseCommand*> commands[3];
-
-
-    // separate the commands
-    SubString commandStrings(bindingString_, "|", SubString::WhiteSpaces, false,
-        '\\', false, '"', false, '(', ')', false, '\0');
-
-    for (unsigned int iCommand = 0; iCommand < commandStrings.size(); iCommand++)
-    {
-      if (commandStrings[iCommand] != "")
-      {
-        SubString tokens(commandStrings[iCommand], " ", SubString::WhiteSpaces, false,
+    void Button::clear()
+    {
+        for (unsigned int j = 0; j < 3; j++)
+        {
+            if (nCommands_[j])
+            {
+                // delete all commands and the command pointer array
+                for (unsigned int i = 0; i < nCommands_[j]; i++)
+                    delete commands_[j][i];
+                delete[] commands_[j];
+                commands_[j] = 0;
+                nCommands_[j] = 0;
+            }
+            else
+            {
+                commands_[j] = 0;
+            }
+        }
+    }
+
+    void Button::parse(std::vector<BufferedParamCommand*>& paramCommandBuffer)
+    {
+        if (isEmpty(bindingString_))
+        {
+            clear();
+            return;
+        }
+
+        // use std::vector for a temporary dynamic array
+        std::vector<BaseCommand*> commands[3];
+
+
+        // separate the commands
+        SubString commandStrings(bindingString_, "|", SubString::WhiteSpaces, false,
             '\\', false, '"', false, '(', ')', false, '\0');
 
-        unsigned int iToken = 0;
-
-        // for real axes, we can feed a ButtonThreshold argument as entire command
-        if (getLowercase(tokens[0]) == "buttonthreshold")
-        {
-          if (tokens.size() == 1)
-            continue;
-          // may fail, but doesn't matter
-          convertValue(&buttonThreshold_, tokens[1]);
-          continue;
-        }
-
-        // first argument can be OnPress, OnHold OnRelease or nothing
-        KeybindMode::Enum mode = KeybindMode::None;
-        if (getLowercase(tokens[iToken]) == "onpress")
-          mode = KeybindMode::OnPress,   iToken++;
-        if (getLowercase(tokens[iToken]) == "onrelease")
-          mode = KeybindMode::OnRelease, iToken++;
-        if (getLowercase(tokens[iToken]) == "onhold")
-          mode = KeybindMode::OnHold,    iToken++;
-
-        if (iToken == tokens.size())
-          continue;
-
-        // second argument can be the amplitude for the case it as an axis command
-        // default amplitude is 1.0f
-        float paramModifier = 1.0f;
-        if (getLowercase(tokens[iToken]) == "scale")
-        {
-          iToken++;
-          if (iToken == tokens.size() || !convertValue(&paramModifier, tokens[iToken]))
-          {
-            COUT(2) << "Error while parsing key binding " << name_
-                << ". Numeric expression expected afer 'AxisAmp', switching to default value" << std::endl;
-            if (iToken == tokens.size())
-              continue;
-          }
-          iToken++;
-        }
-
-        // no more arguments expected except for the actual command
-        if (iToken == tokens.size())
-          continue;
-
-        std::string commandStr;
-        while (iToken != tokens.size())
-          commandStr += tokens[iToken++] + " ";
-
-        // evaluate the command
-        CommandEvaluation eval = CommandExecutor::evaluate(commandStr);
-        if (!eval.isValid())
-          continue;
-
-        // check for param command
-        int paramIndex = eval.getConsoleCommand()->getAxisParamIndex();
-        if (paramIndex >= 0)
-        {
-          // parameter supported command
-          ParamCommand* cmd = new ParamCommand();
-          cmd->paramModifier_ = paramModifier;
-          cmd->bRelative_ = eval.getConsoleCommand()->getIsAxisRelative();
-
-          // add command to the buffer if not yet existing
-          for (unsigned int iParamCmd = 0; iParamCmd < paramCommandBuffer.size(); iParamCmd++)
-          {
-            if (getLowercase(paramCommandBuffer[iParamCmd]->evaluation_.getOriginalCommand())
-                == getLowercase(commandStr))
-            {
-              // already in list
-              cmd->paramCommand_ = paramCommandBuffer[iParamCmd];
-              break;
-            }
-          }
-          if (cmd->paramCommand_ == 0)
-          {
-            cmd->paramCommand_ = new BufferedParamCommand();
-            paramCommandBuffer.push_back(cmd->paramCommand_);
-            cmd->paramCommand_->evaluation_ = eval;
-            cmd->paramCommand_->paramIndex_ = paramIndex;
-          }
-
-
-          // we don't know whether this is an actual axis or just a button
-          if (mode == KeybindMode::None)
-          {
-            if (!addParamCommand(cmd))
-            {
-              mode = eval.getConsoleCommand()->getKeybindMode();
-              commands[mode].push_back(cmd);
-            }
-          }
+        for (unsigned int iCommand = 0; iCommand < commandStrings.size(); iCommand++)
+        {
+            if (commandStrings[iCommand] != "")
+            {
+                SubString tokens(commandStrings[iCommand], " ", SubString::WhiteSpaces, false,
+                    '\\', false, '"', false, '(', ')', false, '\0');
+
+                KeybindMode::Enum mode = KeybindMode::None;
+                float paramModifier = 1.0f;
+                std::string commandStr = "";
+
+                for (unsigned int iToken = 0; iToken < tokens.size(); ++iToken)
+                {
+                    std::string token = getLowercase(tokens[iToken]);
+
+                    if (token == "onpress")
+                        mode = KeybindMode::OnPress;
+                    else if (token == "onrelease")
+                        mode = KeybindMode::OnRelease;
+                    else if (token == "onhold")
+                        mode = KeybindMode::OnHold;
+                    else if (token == "buttonthreshold")
+                    {
+                        // for real axes, we can feed a ButtonThreshold argument
+                        ++iToken;
+                        if (iToken == tokens.size())
+                            continue;
+                        // may fail, but doesn't matter (default value already set)
+                        if (!convertValue(&buttonThreshold_, tokens[iToken + 1]))
+                            parseError("Could not parse 'ButtonThreshold' argument. \
+                                Switching to default value.", true);
+                    }
+                    else if (token == "scale")
+                    {
+                        ++iToken;
+                        if (iToken == tokens.size() || !convertValue(&paramModifier, tokens[iToken]))
+                            parseError("Could not parse 'scale' argument. Switching to default value.", true);
+                    }
+                    else
+                    {
+                        // no input related argument
+                        // we interpret everything from here as a command string
+                        while (iToken != tokens.size())
+                            commandStr += tokens[iToken++] + " ";
+                    }
+                }
+
+                if (commandStr == "")
+                {
+                    parseError("No command string given.", false);
+                    continue;
+                }
+
+                // evaluate the command
+                CommandEvaluation eval = CommandExecutor::evaluate(commandStr);
+                if (!eval.isValid())
+                {
+                    parseError("Command evaluation failed.", true);
+                    continue;
+                }
+
+                // check for param command
+                int paramIndex = eval.getConsoleCommand()->getAxisParamIndex();
+                if (paramIndex >= 0)
+                {
+                    // parameter supported command
+                    ParamCommand* cmd = new ParamCommand();
+                    cmd->paramModifier_ = paramModifier;
+                    cmd->bRelative_ = eval.getConsoleCommand()->getIsAxisRelative();
+
+                    // add command to the buffer if not yet existing
+                    for (unsigned int iParamCmd = 0; iParamCmd < paramCommandBuffer.size(); iParamCmd++)
+                    {
+                        if (getLowercase(paramCommandBuffer[iParamCmd]->evaluation_.getOriginalCommand())
+                            == getLowercase(commandStr))
+                        {
+                            // already in list
+                            cmd->paramCommand_ = paramCommandBuffer[iParamCmd];
+                            break;
+                        }
+                    }
+                    if (cmd->paramCommand_ == 0)
+                    {
+                        cmd->paramCommand_ = new BufferedParamCommand();
+                        paramCommandBuffer.push_back(cmd->paramCommand_);
+                        cmd->paramCommand_->evaluation_ = eval;
+                        cmd->paramCommand_->paramIndex_ = paramIndex;
+                    }
+
+
+                    // we don't know whether this is an actual axis or just a button
+                    if (mode == KeybindMode::None)
+                    {
+                        if (!addParamCommand(cmd))
+                        {
+                            mode = eval.getConsoleCommand()->getKeybindMode();
+                            commands[mode].push_back(cmd);
+                        }
+                    }
+                }
+                else
+                {
+                    SimpleCommand* cmd = new SimpleCommand();
+                    cmd->evaluation_ = eval;
+
+                    if (mode == KeybindMode::None)
+                        mode = eval.getConsoleCommand()->getKeybindMode();
+
+                    commands[mode].push_back(cmd);
+                }
+            }
+        }
+
+        for (unsigned int j = 0; j < 3; j++)
+        {
+            nCommands_[j] = commands[j].size();
+            if (nCommands_[j])
+            {
+                commands_[j] = new BaseCommand*[nCommands_[j]];
+                for (unsigned int i = 0; i < commands[j].size(); i++)
+                    commands_[j][i] = commands[j][i];
+            }
+            else
+                commands_[j] = 0;
+        }
+    }
+
+    bool Button::execute(KeybindMode::Enum mode, float abs, float rel)
+    {
+        // execute all the parsed commands in the string
+        for (unsigned int iCommand = 0; iCommand < nCommands_[mode]; iCommand++)
+            commands_[mode][iCommand]->execute(abs, rel);
+        return true;
+    }
+
+    inline void Button::parseError(std::string message, bool serious)
+    {
+        if (serious)
+        {
+            COUT(2) << "Error while parsing binding for button/axis" << this->name_ << ". "
+                << message << std::endl;
         }
         else
         {
-          SimpleCommand* cmd = new SimpleCommand();
-          cmd->evaluation_ = eval;
-
-          if (mode == KeybindMode::None)
-            mode = eval.getConsoleCommand()->getKeybindMode();
-
-          commands[mode].push_back(cmd);
-        }
-      }
-    }
-
-    for (unsigned int j = 0; j < 3; j++)
-    {
-      nCommands_[j] = commands[j].size();
-      if (nCommands_[j])
-      {
-        commands_[j] = new BaseCommand*[nCommands_[j]];
-        for (unsigned int i = 0; i < commands[j].size(); i++)
-          commands_[j][i] = commands[j][i];
-      }
-      else
-        commands_[j] = 0;
-    }
-  }
-
-  bool Button::execute(KeybindMode::Enum mode, float abs, float rel)
-  {
-    // execute all the parsed commands in the string
-    for (unsigned int iCommand = 0; iCommand < nCommands_[mode]; iCommand++)
-      commands_[mode][iCommand]->execute(abs, rel);
-    return true;
-  }
+            COUT(3) << "Warning while parsing binding for button/axis" << this->name_ << ". "
+                << message << std::endl;
+        }
+    }
 }
Index: code/branches/gui/src/core/input/Button.h
===================================================================
--- code/branches/gui/src/core/input/Button.h	(revision 1636)
+++ code/branches/gui/src/core/input/Button.h	(revision 1638)
@@ -28,7 +28,8 @@
 
 /**
- @file
- @brief Different definitions of input processing.
- */
+@file
+@brief
+    Different definitions of input processing.
+*/
 
 #ifndef _Button_H__
@@ -42,26 +43,29 @@
 namespace orxonox
 {
-  class _CoreExport Button
-  {
-  public:
-    Button() { nCommands_[0]=0; nCommands_[1]=0; nCommands_[2]=0; clear(); }
-    virtual ~Button() { clear(); }
-    virtual void clear();
-    virtual bool addParamCommand(ParamCommand* command) { return false; }
-    void parse(std::vector<BufferedParamCommand*>& paramCommandBuffer);
-    bool execute(KeybindMode::Enum mode, float abs = 1.0f, float rel = 1.0f);
+    class _CoreExport Button
+    {
+    public:
+        Button() { nCommands_[0]=0; nCommands_[1]=0; nCommands_[2]=0; clear(); }
+        virtual ~Button() { clear(); }
+        virtual void clear();
+        virtual bool addParamCommand(ParamCommand* command) { return false; }
+        void parse(std::vector<BufferedParamCommand*>& paramCommandBuffer);
+        bool execute(KeybindMode::Enum mode, float abs = 1.0f, float rel = 1.0f);
 
-    //! The configured string value
-    std::string bindingString_;
-    //! Name of the trigger as strings
-    std::string name_;
-    //! Basic commands for OnPress, OnHold and OnRelease
-    BaseCommand** commands_[3];
-    //! Number of basic commands
-    unsigned int nCommands_[3];
-    //! Says how much it takes for an analog axis to trigger a button
-    //! Note: This variable is here to have only one parse() function.
-    float buttonThreshold_;
-  };
+        //! The configured string value
+        std::string bindingString_;
+        //! Name of the trigger as strings
+        std::string name_;
+        //! Basic commands for OnPress, OnHold and OnRelease
+        BaseCommand** commands_[3];
+        //! Number of basic commands
+        unsigned int nCommands_[3];
+        //! Says how much it takes for an analog axis to trigger a button
+        //! Note: This variable is here to have only one parse() function.
+        float buttonThreshold_;
+
+    private:
+        void parseError(std::string message, bool serious);
+    };
 }
 
Index: code/branches/gui/src/core/input/CalibratorCallback.cc
===================================================================
--- code/branches/gui/src/core/input/CalibratorCallback.cc	(revision 1636)
+++ code/branches/gui/src/core/input/CalibratorCallback.cc	(revision 1638)
@@ -28,7 +28,8 @@
 
 /**
- @file
- @brief Implementation of the different input handlers.
- */
+@file
+@brief
+    Implementation of the different input handlers.
+*/
 
 #include "CalibratorCallback.h"
@@ -37,10 +38,10 @@
 namespace orxonox
 {
-  void CalibratorCallback::keyPressed(const orxonox::KeyEvent &evt)
-  {
-    if (evt.key == KeyCode::Return)
+    void CalibratorCallback::keyPressed(const orxonox::KeyEvent &evt)
     {
-      InputManager::setInputState(InputManager::IS_NOCALIBRATE);
+        if (evt.key == KeyCode::Return)
+        {
+            //InputManager::setInputState(InputManager::IS_NOCALIBRATE);
+        }
     }
-  }
 }
Index: code/branches/gui/src/core/input/CalibratorCallback.h
===================================================================
--- code/branches/gui/src/core/input/CalibratorCallback.h	(revision 1636)
+++ code/branches/gui/src/core/input/CalibratorCallback.h	(revision 1638)
@@ -28,7 +28,8 @@
 
 /**
- @file
- @brief Different definitions of input processing.
- */
+@file
+@brief
+    Different definitions of input processing.
+*/
 
 #ifndef _CalibratorCallback_H__
@@ -36,22 +37,21 @@
 
 #include "core/CorePrereqs.h"
-
 #include "InputInterfaces.h"
 
 namespace orxonox
 {
-  class _CoreExport CalibratorCallback : public KeyHandler
-  {
-  public:
-    CalibratorCallback() {}
-    ~CalibratorCallback() {}
+    class _CoreExport CalibratorCallback : public KeyHandler
+    {
+    public:
+        CalibratorCallback()  { }
+        ~CalibratorCallback() { }
 
-  private:
-    void keyPressed (const KeyEvent& evt);
-    void keyReleased(const KeyEvent& evt) {}
-    void keyHeld    (const KeyEvent& evt) {}
+    private:
+        void keyPressed (const KeyEvent& evt);
+        void keyReleased(const KeyEvent& evt) { }
+        void keyHeld    (const KeyEvent& evt) { }
 
-    void tickInput(float dt, const HandlerState &state) { }
-  };
+        void tickInput(float dt) { }
+    };
 }
 
Index: code/branches/gui/src/core/input/ExtendedInputState.cc
===================================================================
--- code/branches/gui/src/core/input/ExtendedInputState.cc	(revision 1638)
+++ code/branches/gui/src/core/input/ExtendedInputState.cc	(revision 1638)
@@ -0,0 +1,472 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief
+    Implementation of the ExtendedInputState class.
+*/
+
+#include "ExtendedInputState.h"
+
+#include <assert.h>
+#include "core/Debug.h"
+
+namespace orxonox
+{
+    using namespace InputDevice;
+
+    void ExtendedInputState::numberOfJoySticksChanged(unsigned int n)
+    {
+        unsigned int oldSize = joyStickHandlers_.size();
+        joyStickHandlers_.resize(n);
+
+        if (oldSize > n)
+        {
+            // we have to add all the handlers in joyStickHandlersAll_ to the joyStickHandlers_[>n]
+            for (unsigned int j = 0; j < joyStickHandlersAll_.size(); ++j)
+            {
+                for (unsigned int i = oldSize; i < n; ++i)
+                {
+                    joyStickHandlers_[i].push_back(joyStickHandlersAll_[j]);
+                }
+            }
+        }
+        update();
+    }
+
+    void ExtendedInputState::keyPressed(const KeyEvent& evt)
+    {
+        for (unsigned int i = 0; i < keyHandlers_.size(); i++)
+            keyHandlers_[i]->keyPressed(evt);
+    }
+
+    void ExtendedInputState::keyReleased(const KeyEvent& evt)
+    {
+        for (unsigned int i = 0; i < keyHandlers_.size(); i++)
+            keyHandlers_[i]->keyReleased(evt);
+    }
+
+    void ExtendedInputState::keyHeld(const KeyEvent& evt)
+    {
+        for (unsigned int i = 0; i < keyHandlers_.size(); i++)
+            keyHandlers_[i]->keyHeld(evt);
+    }
+
+
+    void ExtendedInputState::mouseMoved(IntVector2 abs, IntVector2 rel, IntVector2 clippingSize)
+    {
+        for (unsigned int i = 0; i < mouseHandlers_.size(); i++)
+            mouseHandlers_[i]->mouseMoved(abs, rel, clippingSize);
+    }
+
+    void ExtendedInputState::mouseScrolled(int abs, int rel)
+    {
+        for (unsigned int i = 0; i < mouseHandlers_.size(); i++)
+            mouseHandlers_[i]->mouseScrolled(abs, rel);
+    }
+
+    void ExtendedInputState::mouseButtonPressed(MouseButton::Enum id)
+    {
+        for (unsigned int i = 0; i < mouseHandlers_.size(); i++)
+            mouseHandlers_[i]->mouseButtonPressed(id);
+    }
+
+    void ExtendedInputState::mouseButtonReleased(MouseButton::Enum id)
+    {
+        for (unsigned int i = 0; i < mouseHandlers_.size(); i++)
+            mouseHandlers_[i]->mouseButtonReleased(id);
+    }
+
+    void ExtendedInputState::mouseButtonHeld(MouseButton::Enum id)
+    {
+        for (unsigned int i = 0; i < mouseHandlers_.size(); i++)
+            mouseHandlers_[i]->mouseButtonHeld(id);
+    }
+
+
+    void ExtendedInputState::joyStickAxisMoved(unsigned int joyStickID, unsigned int axis, float value)
+    {
+        assert(joyStickID < joyStickHandlers_.size());
+        for (unsigned int i = 0; i < joyStickHandlers_[joyStickID].size(); i++)
+            joyStickHandlers_[joyStickID][i]->joyStickAxisMoved(joyStickID, axis, value);
+    }
+
+    void ExtendedInputState::joyStickButtonPressed(unsigned int joyStickID, unsigned int button)
+    {
+        assert(joyStickID < joyStickHandlers_.size());
+        for (unsigned int i = 0; i < joyStickHandlers_[joyStickID].size(); i++)
+            joyStickHandlers_[joyStickID][i]->joyStickButtonPressed(joyStickID, button);
+    }
+
+    void ExtendedInputState::joyStickButtonReleased(unsigned int joyStickID, unsigned int button)
+    {
+        assert(joyStickID < joyStickHandlers_.size());
+        for (unsigned int i = 0; i < joyStickHandlers_[joyStickID].size(); i++)
+            joyStickHandlers_[joyStickID][i]->joyStickButtonReleased(joyStickID, button);
+    }
+
+    void ExtendedInputState::joyStickButtonHeld(unsigned int joyStickID, unsigned int button)
+    {
+        assert(joyStickID < joyStickHandlers_.size());
+        for (unsigned int i = 0; i < joyStickHandlers_[joyStickID].size(); i++)
+            joyStickHandlers_[joyStickID][i]->joyStickButtonHeld(joyStickID, button);
+    }
+
+
+    /**
+    @brief
+        Adds a key handler.
+    @param handler
+        Pointer to the handler object.
+    @return
+        True if added, false if handler already existed.
+    */
+    bool ExtendedInputState::addKeyHandler(KeyHandler* handler)
+    {
+        if (!handler)
+            return false;
+
+        // see whether the handler already is in the list
+        for (std::vector<KeyHandler*>::iterator it = keyHandlers_.begin(); it != keyHandlers_.end(); it++)
+        {
+            if ((*it) == handler)
+            {
+                return false;
+            }
+        }
+        keyHandlers_.push_back(handler);
+        update();
+        return true;
+    }
+
+    /**
+    @brief
+        Removes a Key handler from the state.
+    @param handler
+        Pointer to the handler.
+    @return
+        True if removal was successful, false if handler was not found.
+    */
+    bool ExtendedInputState::removeKeyHandler(KeyHandler* handler)
+    {
+        if (!handler)
+            return false;
+
+        for (std::vector<KeyHandler*>::iterator it = keyHandlers_.begin(); it != keyHandlers_.end(); it++)
+        {
+            if ((*it) == handler)
+            {
+                keyHandlers_.erase(it);
+                update();
+                return true;
+            }
+        }
+        return false;
+    }
+
+
+    /**
+    @brief
+        Adds a mouse handler.
+    @param handler
+        Pointer to the handler object.
+    @return
+        True if added, false if handler already existed.
+    */
+    bool ExtendedInputState::addMouseHandler(MouseHandler* handler)
+    {
+        if (!handler)
+            return false;
+
+        // see whether the handler already is in the list
+        for (std::vector<MouseHandler*>::iterator it = mouseHandlers_.begin(); it != mouseHandlers_.end(); it++)
+        {
+            if ((*it) == handler)
+            {
+                return false;
+            }
+        }
+        mouseHandlers_.push_back(handler);
+        update();
+        return true;
+    }
+
+    /**
+    @brief
+        Removes a mouse handler from the state.
+    @param handler
+        Pointer to the handler.
+    @return
+        True if removal was successful, false if handler was not found.
+    */
+    bool ExtendedInputState::removeMouseHandler(MouseHandler* handler)
+    {
+        if (!handler)
+            return false;
+
+        for (std::vector<MouseHandler*>::iterator it = mouseHandlers_.begin(); it != mouseHandlers_.end(); it++)
+        {
+            if ((*it) == handler)
+            {
+                mouseHandlers_.erase(it);
+                update();
+                return true;
+            }
+        }
+        return false;
+    }
+
+
+    /**
+    @brief
+        Adds a joy stick handler.
+    @param handler
+        Pointer to the handler object.
+    @param joyStickID
+        ID of the joy stick
+    @return
+        True if added, false if handler already existed.
+    */
+    bool ExtendedInputState::addJoyStickHandler(JoyStickHandler* handler, unsigned int joyStickID)
+    {
+        if (!handler || joyStickID >= joyStickHandlers_.size())
+            return false;
+
+        // see whether the handler already is in the list
+        for (std::vector<JoyStickHandler*>::iterator it = joyStickHandlers_[joyStickID].begin();
+            it != joyStickHandlers_[joyStickID].end(); it++)
+        {
+            if ((*it) == handler)
+            {
+                return false;
+            }
+        }
+        joyStickHandlers_[joyStickID].push_back(handler);
+        update();
+        return true;
+    }
+
+    /**
+    @brief
+        Removes a joy stick handler from the state.
+    @param handler
+        Pointer to the handler.
+    @param joyStickID
+        ID of the joy stick
+    @return
+        True if removal was successful, false if handler was not found.
+    */
+    bool ExtendedInputState::removeJoyStickHandler(JoyStickHandler* handler, unsigned int joyStickID)
+    {
+        if (!handler || joyStickID >= joyStickHandlers_.size())
+            return false;
+
+        // remove it from the list of all-joystick handlers if present
+        for (std::vector<JoyStickHandler*>::iterator it = joyStickHandlersAll_.begin();
+            it != joyStickHandlersAll_.end(); it++)
+        {
+            if ((*it) == handler)
+            {
+                joyStickHandlersAll_.erase(it);
+            }
+        }
+
+        // remove handler from the list of seperate lists of handlers
+        for (std::vector<JoyStickHandler*>::iterator it = joyStickHandlers_[joyStickID].begin();
+            it != joyStickHandlers_[joyStickID].end(); it++)
+        {
+            if ((*it) == handler)
+            {
+                joyStickHandlers_[joyStickID].erase(it);
+                update();
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+    @brief
+        Adds a joy stick handler.
+    @param handler
+        Pointer to the handler object.
+    @return
+        True if added, false if handler already existed.
+    */
+    bool ExtendedInputState::addJoyStickHandler(JoyStickHandler* handler)
+    {
+        if (!handler)
+            return false;
+
+        // see whether the handler already is in the big list
+        for (std::vector<JoyStickHandler*>::iterator it = joyStickHandlersAll_.begin();
+            it != joyStickHandlersAll_.end(); it++)
+        {
+            if ((*it) == handler)
+            {
+                return false;
+            }
+        }
+        joyStickHandlersAll_.push_back(handler);
+        update();
+
+        // now, we have to add it to all the separate lists
+        for (unsigned int iJoyStick = 0; iJoyStick < joyStickHandlers_.size(); ++iJoyStick)
+            addJoyStickHandler(handler, iJoyStick);
+        return true;
+    }
+
+    /**
+    @brief
+        Removes a joy stick handler from the state.
+    @param handler
+        Pointer to the handler.
+    @return
+        True if removal was successful, false if handler was not found.
+    */
+    bool ExtendedInputState::removeJoyStickHandler(JoyStickHandler* handler)
+    {
+        if (!handler)
+            return false;
+
+        bool success = false;
+        // remove from all lists in a loop (also removes it from the big list)
+        for (unsigned int iJoyStick = 0; iJoyStick < joyStickHandlers_.size(); ++iJoyStick)
+            success |= removeJoyStickHandler(handler, iJoyStick);
+
+        return success;
+    }
+
+    void ExtendedInputState::removeAndDestroyAllHandlers()
+    {
+        for (std::vector<InputTickable*>::iterator it = allHandlers_.begin();
+            it != allHandlers_.end(); ++it)
+            delete *it;
+
+        allHandlers_.clear();
+        keyHandlers_.clear();
+        mouseHandlers_.clear();
+        joyStickHandlersAll_.clear();
+        for (unsigned int iJoyStick = 0; iJoyStick < joyStickHandlers_.size(); ++iJoyStick)
+            joyStickHandlers_[iJoyStick].clear();
+        update();
+    }
+
+    /**
+    @brief
+        Adds a handler of any kind. dynamic_cast determines to which list it is added.
+    @param handler
+        Pointer to the handler object.
+    @return
+        True if added, false if handler already existed.
+    */
+    bool ExtendedInputState::addHandler(InputTickable* handler)
+    {
+        bool success = false;
+
+        success |= addKeyHandler(dynamic_cast<KeyHandler*>(handler));
+        success |= addMouseHandler(dynamic_cast<MouseHandler*>(handler));
+        success |= addJoyStickHandler(dynamic_cast<JoyStickHandler*>(handler));
+
+        return success;
+    }
+
+    /**
+    @brief
+        Removes a handler from all lists.
+    @param handler
+        Pointer to the handler.
+    @return
+        True if removal was successful, false if handler was not found.
+    */
+    bool ExtendedInputState::removeHandler(InputTickable* handler)
+    {
+        bool success = false;
+
+        success |= removeKeyHandler(dynamic_cast<KeyHandler*>(handler));
+        success |= removeMouseHandler(dynamic_cast<MouseHandler*>(handler));
+        success |= removeJoyStickHandler(dynamic_cast<JoyStickHandler*>(handler));
+
+        return success;
+    }
+
+    void ExtendedInputState::tickInput(float dt)
+    {
+        for (unsigned int i = 0; i < allHandlers_.size(); ++i)
+        {
+            allHandlers_[i]->tickInput(dt);
+        }
+    }
+
+    void ExtendedInputState::tickInput(float dt, unsigned int device)
+    {
+        switch (device)
+        {
+        case Keyboard:
+            for (unsigned int i = 0; i < keyHandlers_.size(); ++i)
+                keyHandlers_[i]->tickKey(dt);
+            break;
+
+        case Mouse:
+            for (unsigned int i = 0; i < mouseHandlers_.size(); ++i)
+                mouseHandlers_[i]->tickMouse(dt);
+            break;
+
+        default: // joy sticks
+            for (unsigned int i = 0; i < joyStickHandlers_[device - 2].size(); ++i)
+                joyStickHandlers_[device - 2][i]->tickJoyStick(dt, device - 2);
+            break;
+        }
+    }
+
+    void ExtendedInputState::update()
+    {
+        // we can use a set to have a list of unique pointers (an object can implement all 3 handlers)
+        std::set<InputTickable*> tempSet;
+        for (unsigned int iHandler = 0; iHandler < keyHandlers_.size(); iHandler++)
+            tempSet.insert(keyHandlers_[iHandler]);
+        for (unsigned int iHandler = 0; iHandler < mouseHandlers_.size(); iHandler++)
+            tempSet.insert(mouseHandlers_[iHandler]);
+        for (unsigned int iJoyStick = 0; iJoyStick < joyStickHandlers_.size(); iJoyStick++)
+            for (unsigned int iHandler = 0; iHandler < joyStickHandlers_[iJoyStick].size(); iHandler++)
+                tempSet.insert(joyStickHandlers_[iJoyStick][iHandler]);
+
+        // copy the content of the map back to the actual vector
+        allHandlers_.clear();
+        for (std::set<InputTickable*>::const_iterator itHandler = tempSet.begin();
+            itHandler != tempSet.end(); itHandler++)
+            allHandlers_.push_back(*itHandler);
+
+        // update the deviceEnabled options
+        setInputDeviceEnabled(Keyboard, (keyHandlers_.size() != 0));
+        setInputDeviceEnabled(Mouse, (mouseHandlers_.size() != 0));
+        for (unsigned int i = 0; i < joyStickHandlers_.size(); ++i)
+            setInputDeviceEnabled(2 + i, (joyStickHandlers_[i].size() != 0));
+    }
+}
Index: code/branches/gui/src/core/input/ExtendedInputState.h
===================================================================
--- code/branches/gui/src/core/input/ExtendedInputState.h	(revision 1638)
+++ code/branches/gui/src/core/input/ExtendedInputState.h	(revision 1638)
@@ -0,0 +1,100 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief 
+*/
+
+#ifndef _ExtendedInputState_H__
+#define _ExtendedInputState_H__
+
+#include "core/CorePrereqs.h"
+
+#include <vector>
+
+#include "InputInterfaces.h"
+#include "InputState.h"
+
+namespace orxonox
+{
+
+    class _CoreExport ExtendedInputState : public InputState
+    {
+    public:
+        ExtendedInputState() { }
+        ~ExtendedInputState() { }
+
+        bool addKeyHandler        (KeyHandler* handler);
+        bool removeKeyHandler     (KeyHandler* handler);
+
+        bool addMouseHandler      (MouseHandler* handler);
+        bool removeMouseHandler   (MouseHandler* handler);
+
+        bool addJoyStickHandler   (JoyStickHandler* handler, unsigned int joyStickID);
+        bool removeJoyStickHandler(JoyStickHandler* handler, unsigned int joyStickID);
+        bool addJoyStickHandler   (JoyStickHandler* handler);
+        bool removeJoyStickHandler(JoyStickHandler* handler);
+
+        bool addHandler(InputTickable* handler);
+        bool removeHandler(InputTickable* handler);
+
+        void removeAndDestroyAllHandlers();
+
+    private:
+        void tickInput(float dt);
+        void tickInput(float dt, unsigned int device);
+
+        void keyPressed (const KeyEvent& evt);
+        void keyReleased(const KeyEvent& evt);
+        void keyHeld    (const KeyEvent& evt);
+
+        void mouseButtonPressed (MouseButton::Enum id);
+        void mouseButtonReleased(MouseButton::Enum id);
+        void mouseButtonHeld    (MouseButton::Enum id);
+        void mouseMoved         (IntVector2 abs, IntVector2 rel, IntVector2 clippingSize);
+        void mouseScrolled      (int abs, int rel);
+
+        void joyStickButtonPressed (unsigned int joyStickID, unsigned int button);
+        void joyStickButtonReleased(unsigned int joyStickID, unsigned int button);
+        void joyStickButtonHeld    (unsigned int joyStickID, unsigned int button);
+        void joyStickAxisMoved     (unsigned int joyStickID, unsigned int axis, float value);        void updateTickables();
+
+        void numberOfJoySticksChanged(unsigned int n);
+        void update();
+
+        std::vector<KeyHandler*>                    keyHandlers_;
+        std::vector<MouseHandler*>                  mouseHandlers_;
+        std::vector<std::vector<JoyStickHandler*> > joyStickHandlers_;
+        std::vector<JoyStickHandler*>               joyStickHandlersAll_;
+
+        std::vector<InputTickable*> allHandlers_;
+    };
+}
+
+#endif /* _ExtendedInputState_H__ */
Index: code/branches/gui/src/core/input/HalfAxis.cc
===================================================================
--- code/branches/gui/src/core/input/HalfAxis.cc	(revision 1636)
+++ code/branches/gui/src/core/input/HalfAxis.cc	(revision 1638)
@@ -28,7 +28,8 @@
 
 /**
- @file
- @brief Implementation of the different input handlers.
- */
+@file
+@brief
+    Implementation of the different input handlers.
+*/
 
 #include "HalfAxis.h"
@@ -38,40 +39,40 @@
 namespace orxonox
 {
-  void HalfAxis::clear()
-  {
-    Button::clear();
-    if (nParamCommands_)
+    void HalfAxis::clear()
     {
-      // delete all commands and the command pointer array
-      for (unsigned int i = 0; i < nParamCommands_; i++)
-        delete paramCommands_[i];
-      delete[] paramCommands_;
-      nParamCommands_ = 0;
+        Button::clear();
+        if (nParamCommands_)
+        {
+            // delete all commands and the command pointer array
+            for (unsigned int i = 0; i < nParamCommands_; i++)
+                delete paramCommands_[i];
+            delete[] paramCommands_;
+            nParamCommands_ = 0;
+        }
+        else
+        {
+            nParamCommands_ = 0; nParamCommands_ = 0;
+        }
     }
-    else
+
+    bool HalfAxis::addParamCommand(ParamCommand* command)
     {
-      nParamCommands_ = 0; nParamCommands_ = 0;
+        ParamCommand** cmds = paramCommands_;
+        paramCommands_ = new ParamCommand*[++nParamCommands_];
+        unsigned int i;
+        for (i = 0; i < nParamCommands_ - 1; i++)
+            paramCommands_[i] = cmds[i];
+        paramCommands_[i] = command;
+        if (nParamCommands_ > 1)
+            delete[] cmds;
+        return true;
     }
-  }
 
-  bool HalfAxis::addParamCommand(ParamCommand* command)
-  {
-    ParamCommand** cmds = paramCommands_;
-    paramCommands_ = new ParamCommand*[++nParamCommands_];
-    unsigned int i;
-    for (i = 0; i < nParamCommands_ - 1; i++)
-      paramCommands_[i] = cmds[i];
-    paramCommands_[i] = command;
-    if (nParamCommands_ > 1)
-      delete[] cmds;
-    return true;
-  }
-
-  bool HalfAxis::execute()
-  {
-    bool success = true;
-    for (unsigned int i = 0; i < nParamCommands_; i++)
-      success = success && paramCommands_[i]->execute(absVal_, relVal_);
-    return success;
-  }
+    bool HalfAxis::execute()
+    {
+        bool success = true;
+        for (unsigned int i = 0; i < nParamCommands_; i++)
+            success = success && paramCommands_[i]->execute(absVal_, relVal_);
+        return success;
+    }
 }
Index: code/branches/gui/src/core/input/HalfAxis.h
===================================================================
--- code/branches/gui/src/core/input/HalfAxis.h	(revision 1636)
+++ code/branches/gui/src/core/input/HalfAxis.h	(revision 1638)
@@ -28,7 +28,8 @@
 
 /**
- @file
- @brief Different definitions of input processing.
- */
+@file
+@brief
+    Different definitions of input processing.
+*/
 
 #ifndef _HalfAxis_H__
@@ -40,24 +41,30 @@
 namespace orxonox
 {
-  class _CoreExport HalfAxis : public Button
-  {
-  public:
-    HalfAxis() : relVal_(0.0f), absVal_(0.0f), paramCommands_(0), nParamCommands_(0),
-                 wasDown_(false), hasChanged_(false) { }
-    using Button::execute;
-    bool execute();
-    bool addParamCommand(ParamCommand* command);
-    void clear();
+    class _CoreExport HalfAxis : public Button
+    {
+    public:
+        HalfAxis()
+            : relVal_(0.0f)
+            , absVal_(0.0f)
+            , paramCommands_(0)
+            , nParamCommands_(0)
+            , wasDown_(false)
+            , hasChanged_(false)
+        { }
+        using Button::execute;
+        bool execute();
+        bool addParamCommand(ParamCommand* command);
+        void clear();
 
-    // axis related
-    float relVal_;
-    float absVal_;
-    ParamCommand** paramCommands_;
-    unsigned int nParamCommands_;
+        // axis related
+        float relVal_;
+        float absVal_;
+        ParamCommand** paramCommands_;
+        unsigned int nParamCommands_;
 
-    // button related
-    bool wasDown_;
-    bool hasChanged_;
-  };
+        // button related
+        bool wasDown_;
+        bool hasChanged_;
+    };
 }
 
Index: code/branches/gui/src/core/input/InputBuffer.cc
===================================================================
--- code/branches/gui/src/core/input/InputBuffer.cc	(revision 1636)
+++ code/branches/gui/src/core/input/InputBuffer.cc	(revision 1638)
@@ -220,5 +220,5 @@
         @param dt Delta time
     */
-    void InputBuffer::tickInput(float dt, const HandlerState& state)
+    void InputBuffer::tickInput(float dt)
     {
         timeSinceKeyPressed_ += dt;
Index: code/branches/gui/src/core/input/InputBuffer.h
===================================================================
--- code/branches/gui/src/core/input/InputBuffer.h	(revision 1636)
+++ code/branches/gui/src/core/input/InputBuffer.h	(revision 1638)
@@ -170,5 +170,6 @@
             void processKey (const KeyEvent &e);
 
-            void tickInput(float dt, const HandlerState& state);
+            void tickInput(float dt);
+            void tickInput(float dt, int device) { }
 
             std::string buffer_;
Index: code/branches/gui/src/core/input/InputCommands.cc
===================================================================
--- code/branches/gui/src/core/input/InputCommands.cc	(revision 1636)
+++ code/branches/gui/src/core/input/InputCommands.cc	(revision 1638)
@@ -28,7 +28,8 @@
 
 /**
- @file
- @brief Implementation of the different input handlers.
- */
+@file
+@brief
+    Implementation of the different input handlers.
+*/
 
 #include "InputCommands.h"
@@ -37,91 +38,97 @@
 namespace orxonox
 {
-  // ###############################
-  // ###  BufferedParamCommand   ###
-  // ###############################
+    // ###############################
+    // ###  BufferedParamCommand   ###
+    // ###############################
 
-  /**
-  * Executes a buffered command. This is used for commands with additional
-  * parameters.
-  * @return True if command execution was successful or value was zero.
-  */
-  bool BufferedParamCommand::execute()
-  {
-    if (nValuesAdded_)
+    /**
+    @brief
+        Executes a buffered command. This is used for commands with additional
+        parameters.
+    @return
+        True if command execution was successful or value was zero.
+    */
+    bool BufferedParamCommand::execute()
     {
-      BufferedParamCommand& cmd = *this;
-      cmd.evaluation_.setEvaluatedParameter(cmd.paramIndex_, cmd.value_);
-      // reset
-      cmd.nValuesAdded_ = 0;
-      cmd.value_ = 0;
-      return cmd.evaluation_.execute();
+        if (nValuesAdded_)
+        {
+            BufferedParamCommand& cmd = *this;
+            cmd.evaluation_.setEvaluatedParameter(cmd.paramIndex_, cmd.value_);
+            // reset
+            cmd.nValuesAdded_ = 0;
+            cmd.value_ = 0;
+            return cmd.evaluation_.execute();
+        }
+        else
+            return true;
     }
-    else
-      return true;
-  }
 
-  // ###############################
-  // #####    SimpleCommand    #####
-  // ###############################
+    // ###############################
+    // #####    SimpleCommand    #####
+    // ###############################
 
-  /**
-  * Executes a simple command with no additional paramters.
-  * @return True if command execution was successful, false otherwise.
-  */
-  bool SimpleCommand::execute(float abs, float rel)
-  {
-    return evaluation_.execute();
-  }
+    /**
+    @brief
+        Executes a simple command with no additional paramters.
+    @return 
+        True if command execution was successful, false otherwise.
+    */
+    bool SimpleCommand::execute(float abs, float rel)
+    {
+        return evaluation_.execute();
+    }
 
-  // ###############################
-  // #####    ParamCommand     #####
-  // ###############################
+    // ###############################
+    // #####    ParamCommand     #####
+    // ###############################
 
-  /**
-  * Executes a parameter command. The commmand string is not directly executed,
-  * but instead stored in a buffer list so that values can be combined.
-  * @return Always true.
-  */
-  bool ParamCommand::execute(float abs, float rel)
-  {
-    BufferedParamCommand& cmd = *paramCommand_;
-    // command has an additional parameter
-    if (bRelative_)
+    /**
+    @brief
+        Executes a parameter command. The commmand string is not directly executed,
+        but instead stored in a buffer list so that values can be combined.
+    @return
+        Always true.
+    */
+    bool ParamCommand::execute(float abs, float rel)
     {
-      if (rel != 0.0f)
-      {
-        // we have to calculate a relative movement.
-        // paramModifier_ says how much one keystroke is
-        cmd.value_ += paramModifier_ * rel;
-      }
+        BufferedParamCommand& cmd = *paramCommand_;
+        // command has an additional parameter
+        if (bRelative_)
+        {
+            if (rel != 0.0f)
+            {
+                // we have to calculate a relative movement.
+                // paramModifier_ says how much one keystroke is
+                cmd.value_ += paramModifier_ * rel;
+            }
+        }
+        else if (abs != 0.0f)
+        {
+            // Usually, joy sticks create 'noise' (they return values if they're in 0 position)
+            // and normally this is caught in tickInput(), but that threshold cannot be to high
+            // in order to preserve accuracy. Instead, we have to catch the problem here. An example:
+            // Someone only uses buttons with an active joystick. The joy stick value could then
+            // be 0.05 for instance and the the key value 1. Without handling the problem, the final
+            // value would be computed to (1+0.05)/2=0.5025 which is not what the user expects.
+            float absQ = abs * abs;
+            float valueQ = cmd.value_ * cmd.value_;
+            if (absQ > 50.0f * valueQ) // ease up comparison by using quadratics
+            {
+                cmd.value_ = abs * paramModifier_;
+                cmd.nValuesAdded_ = 1;
+            }
+            else if (absQ * 50.0f < valueQ)
+            {
+                // abs is too small, we just don't do anything
+            }
+            else
+            {
+                // we have to calculate the absolute position of the axis.
+                // Since there might be another axis that is affected, we have to wait and
+                // store the result in a temporary place
+                cmd.value_ = (cmd.value_ * cmd.nValuesAdded_ + paramModifier_ * abs) / ++cmd.nValuesAdded_;
+            }
+        }
+        return true;
     }
-    else if (abs != 0.0f)
-    {
-      // Usually, joy sticks create 'noise' (they return values if they're in 0 position)
-      // and normally this is caught in tickInput(), but that threshold cannot be to high
-      // in order to preserve accuracy. Instead, we have to catch the problem here. An example:
-      // Someone only uses buttons with an active joystick. The joy stick value could then
-      // be 0.05 for instance and the the key value 1. Without handling the problem, the final
-      // value would be computed to (1+0.05)/2=0.5025 which is not what the user expects.
-      float absQ = abs * abs;
-      float valueQ = cmd.value_ * cmd.value_;
-      if (absQ > 50.0f * valueQ) // ease up comparison by using quadratics
-      {
-        cmd.value_ = abs * paramModifier_;
-        cmd.nValuesAdded_ = 1;
-      }
-      else if (absQ * 50.0f < valueQ)
-      {
-        // abs is too small, we just don't do anything
-      }
-      else
-      {
-        // we have to calculate the absolute position of the axis.
-        // Since there might be another axis that is affected, we have to wait and
-        // store the result in a temporary place
-        cmd.value_ = (cmd.value_ * cmd.nValuesAdded_ + paramModifier_ * abs) / ++cmd.nValuesAdded_;
-      }
-    }
-    return true;
-  }
 }
Index: code/branches/gui/src/core/input/InputCommands.h
===================================================================
--- code/branches/gui/src/core/input/InputCommands.h	(revision 1636)
+++ code/branches/gui/src/core/input/InputCommands.h	(revision 1638)
@@ -28,7 +28,8 @@
 
 /**
- @file
- @brief Different definitions of input processing.
- */
+@file
+@brief
+    Different definitions of input processing.
+*/
 
 #ifndef _InputCommands_H__
@@ -40,41 +41,41 @@
 namespace orxonox
 {
-  class _CoreExport BufferedParamCommand
-  {
-  public:
-    BufferedParamCommand() : value_(0.0f), nValuesAdded_(0), paramIndex_(-1) { }
-    bool execute();
+    class _CoreExport BufferedParamCommand
+    {
+    public:
+        BufferedParamCommand() : value_(0.0f), nValuesAdded_(0), paramIndex_(-1) { }
+        bool execute();
 
-    float value_;
-    unsigned int nValuesAdded_;
-    int paramIndex_;
-    CommandEvaluation evaluation_;
-  };
+        float value_;
+        unsigned int nValuesAdded_;
+        int paramIndex_;
+        CommandEvaluation evaluation_;
+    };
 
-  class _CoreExport BaseCommand
-  {
-  public:
-    virtual ~BaseCommand() { }
-    virtual bool execute(float abs = 1.0f, float rel = 1.0f) = 0;
-  };
+    class _CoreExport BaseCommand
+    {
+    public:
+        virtual ~BaseCommand() { }
+        virtual bool execute(float abs = 1.0f, float rel = 1.0f) = 0;
+    };
 
-  class _CoreExport SimpleCommand : public BaseCommand
-  {
-  public:
-    bool execute(float abs = 1.0f, float rel = 1.0f);
+    class _CoreExport SimpleCommand : public BaseCommand
+    {
+    public:
+        bool execute(float abs = 1.0f, float rel = 1.0f);
 
-    CommandEvaluation evaluation_;
-  };
+        CommandEvaluation evaluation_;
+    };
 
-  class _CoreExport ParamCommand : public BaseCommand
-  {
-  public:
-    ParamCommand() : bRelative_(false), paramModifier_(1.0f), paramCommand_(0) { }
-    bool execute(float abs = 1.0f, float rel = 1.0f);
+    class _CoreExport ParamCommand : public BaseCommand
+    {
+    public:
+        ParamCommand() : bRelative_(false), paramModifier_(1.0f), paramCommand_(0) { }
+        bool execute(float abs = 1.0f, float rel = 1.0f);
 
-    bool bRelative_;
-    float paramModifier_;
-    BufferedParamCommand* paramCommand_;
-  };
+        bool bRelative_;
+        float paramModifier_;
+        BufferedParamCommand* paramCommand_;
+    };
 }
 
Index: code/branches/gui/src/core/input/InputInterfaces.h
===================================================================
--- code/branches/gui/src/core/input/InputInterfaces.h	(revision 1636)
+++ code/branches/gui/src/core/input/InputInterfaces.h	(revision 1638)
@@ -28,6 +28,7 @@
 
 /**
- @file
- @brief Declarations of various interface classes for the input management.
+@file
+@brief
+    Declarations of various interface classes for the input management.
 */
 
@@ -37,286 +38,329 @@
 #include "core/CorePrereqs.h"
 
-#include "src/ois/OISKeyboard.h"
-#include "src/ois/OISMouse.h"
-#include "src/ois/OISJoyStick.h"
+#include "ois/OISKeyboard.h"
+#include "ois/OISMouse.h"
+#include "ois/OISJoyStick.h"
 #include "util/Math.h"
 
 namespace orxonox
 {
-  namespace KeyCode
-  {
-    // note: KeyCode comments were directly taken from OISKeyboard.h
-    enum Enum
-    {
-      Unassigned    = OIS::KC_UNASSIGNED,
-      Escape        = OIS::KC_ESCAPE,
-      NumRow1       = OIS::KC_1,
-      NumRow2       = OIS::KC_2,
-      NumRow3       = OIS::KC_3,
-      NumRow4       = OIS::KC_4,
-      NumRow5       = OIS::KC_5,
-      NumRow6       = OIS::KC_6,
-      NumRow7       = OIS::KC_7,
-      NumRow8       = OIS::KC_8,
-      NumRow9       = OIS::KC_9,
-      NumRow0       = OIS::KC_0,
-      Minus         = OIS::KC_MINUS,           // - on main keyboard
-      Equals        = OIS::KC_EQUALS,
-      Back          = OIS::KC_BACK,            // backspace
-      Tab           = OIS::KC_TAB,
-      Q             = OIS::KC_Q,
-      W             = OIS::KC_W,
-      E             = OIS::KC_E,
-      R             = OIS::KC_R,
-      T             = OIS::KC_T,
-      Y             = OIS::KC_Y,
-      U             = OIS::KC_U,
-      I             = OIS::KC_I,
-      O             = OIS::KC_O,
-      P             = OIS::KC_P,
-      LeftBracket   = OIS::KC_LBRACKET,
-      RightBracket  = OIS::KC_RBRACKET,
-      Return        = OIS::KC_RETURN,          // Enter on main keyboard
-      LeftControl   = OIS::KC_LCONTROL,
-      A             = OIS::KC_A,
-      S             = OIS::KC_S,
-      D             = OIS::KC_D,
-      F             = OIS::KC_F,
-      G             = OIS::KC_G,
-      H             = OIS::KC_H,
-      J             = OIS::KC_J,
-      K             = OIS::KC_K,
-      L             = OIS::KC_L,
-      Semicolon     = OIS::KC_SEMICOLON,
-      Apostrophe    = OIS::KC_APOSTROPHE,
-      Grave         = OIS::KC_GRAVE,           // accent
-      LeftShift     = OIS::KC_LSHIFT,
-      Backslash     = OIS::KC_BACKSLASH,
-      Z             = OIS::KC_Z,
-      X             = OIS::KC_X,
-      C             = OIS::KC_C,
-      V             = OIS::KC_V,
-      B             = OIS::KC_B,
-      N             = OIS::KC_N,
-      M             = OIS::KC_M,
-      Comma         = OIS::KC_COMMA,
-      Period        = OIS::KC_PERIOD,          // . on main keyboard
-      Slash         = OIS::KC_SLASH,           // / on main keyboard
-      RightShift    = OIS::KC_RSHIFT,
-      Multiply      = OIS::KC_MULTIPLY,        // * on numeric keypad
-      LeftAlt       = OIS::KC_LMENU,           // left Alt
-      Space         = OIS::KC_SPACE,
-      CapsLock      = OIS::KC_CAPITAL,
-      F1            = OIS::KC_F1,
-      F2            = OIS::KC_F2,
-      F3            = OIS::KC_F3,
-      F4            = OIS::KC_F4,
-      F5            = OIS::KC_F5,
-      F6            = OIS::KC_F6,
-      F7            = OIS::KC_F7,
-      F8            = OIS::KC_F8,
-      F9            = OIS::KC_F9,
-      F10           = OIS::KC_F10,
-      Numlock       = OIS::KC_NUMLOCK,
-      Scrolllock    = OIS::KC_SCROLL,          // Scroll Lock
-      Numpad7       = OIS::KC_NUMPAD7,
-      Numpad8       = OIS::KC_NUMPAD8,
-      Numpad9       = OIS::KC_NUMPAD9,
-      NumpadSubtract= OIS::KC_SUBTRACT,        // - on numeric keypad
-      Numpad4       = OIS::KC_NUMPAD4,
-      Numpad5       = OIS::KC_NUMPAD5,
-      Numpad6       = OIS::KC_NUMPAD6,
-      NumpadAdd     = OIS::KC_ADD,             // + on numeric keypad
-      Numpad1       = OIS::KC_NUMPAD1,
-      Numpad2       = OIS::KC_NUMPAD2,
-      Numpad3       = OIS::KC_NUMPAD3,
-      Numpad0       = OIS::KC_NUMPAD0,
-      NumpadPeriod  = OIS::KC_DECIMAL,         // . on numeric keypad
-      LessThan      = OIS::KC_OEM_102,         // < > | on UK/Germany keyboards
-      F11           = OIS::KC_F11,
-      F12           = OIS::KC_F12,
-      F13           = OIS::KC_F13,             //                     (NEC PC98)
-      F14           = OIS::KC_F14,             //                     (NEC PC98)
-      F15           = OIS::KC_F15,             //                     (NEC PC98)
-      Kana          = OIS::KC_KANA,            // (Japanese keyboard)
-      ABNT_C1       = OIS::KC_ABNT_C1,         // / ? on Portugese (Brazilian) keyboards
-      Convert       = OIS::KC_CONVERT,         // (Japanese keyboard)
-      NoConvert     = OIS::KC_NOCONVERT,       // (Japanese keyboard)
-      Yen           = OIS::KC_YEN,             // (Japanese keyboard)
-      ABNT_C2       = OIS::KC_ABNT_C2,         // Numpad . on Portugese (Brazilian) keyboards
-      NumpadEquals  = OIS::KC_NUMPADEQUALS,    // = on numeric keypad (NEC PC98)
-      PreviousTrack = OIS::KC_PREVTRACK,       // Previous Track (KC_CIRCUMFLEX on Japanese keyboard)
-      AT            = OIS::KC_AT,              //                     (NEC PC98)
-      Colon         = OIS::KC_COLON,           //                     (NEC PC98)
-      Underline     = OIS::KC_UNDERLINE,       //                     (NEC PC98)
-      Kanji         = OIS::KC_KANJI,           // (Japanese keyboard)
-      Stop          = OIS::KC_STOP,            //                     (NEC PC98)
-      AX            = OIS::KC_AX,              //                     (Japan AX)
-      Unlabeled     = OIS::KC_UNLABELED,       //                        (J3100)
-      NextTrack     = OIS::KC_NEXTTRACK,       // Next Track
-      NumpadEnter   = OIS::KC_NUMPADENTER,     // Enter on numeric keypad
-      RightControl  = OIS::KC_RCONTROL,
-      Mute          = OIS::KC_MUTE,            // Mute
-      Calculator    = OIS::KC_CALCULATOR,      // Calculator
-      PlayPause     = OIS::KC_PLAYPAUSE,       // Play / Pause
-      MediaStop     = OIS::KC_MEDIASTOP,       // Media Stop
-      VolumeDown    = OIS::KC_VOLUMEDOWN,      // Volume -
-      VolumeUp      = OIS::KC_VOLUMEUP,        // Volume +
-      WebHome       = OIS::KC_WEBHOME,         // Web home
-      NumpadComma   = OIS::KC_NUMPADCOMMA,     // , on numeric keypad (NEC PC98)
-      Divide        = OIS::KC_DIVIDE,          // / on numeric keypad
-      SYSRQ         = OIS::KC_SYSRQ,
-      RightAlt      = OIS::KC_RMENU,           // right Alt
-      Pause         = OIS::KC_PAUSE,           // Pause
-      Home          = OIS::KC_HOME,            // Home on arrow keypad
-      Up            = OIS::KC_UP,              // UpArrow on arrow keypad
-      PageUp        = OIS::KC_PGUP,            // PgUp on arrow keypad
-      Left          = OIS::KC_LEFT,            // LeftArrow on arrow keypad
-      Right         = OIS::KC_RIGHT,           // RightArrow on arrow keypad
-      End           = OIS::KC_END,             // End on arrow keypad
-      Down          = OIS::KC_DOWN,            // DownArrow on arrow keypad
-      PageDown      = OIS::KC_PGDOWN,          // PgDn on arrow keypad
-      Insert        = OIS::KC_INSERT,          // Insert on arrow keypad
-      Delete        = OIS::KC_DELETE,          // Delete on arrow keypad
-      LeftWindows   = OIS::KC_LWIN,            // Left Windows key
-      RightWindows  = OIS::KC_RWIN,            // Right Windows key
-      Apps          = OIS::KC_APPS,            // AppMenu key
-      Power         = OIS::KC_POWER,           // System Power
-      Sleep         = OIS::KC_SLEEP,           // System Sleep
-      Wake          = OIS::KC_WAKE,            // System Wake
-      WebSearch     = OIS::KC_WEBSEARCH,       // Web Search
-      WebFavorites  = OIS::KC_WEBFAVORITES,    // Web Favorites
-      WebRefresh    = OIS::KC_WEBREFRESH,      // Web Refresh
-      WebStop       = OIS::KC_WEBSTOP,         // Web Stop
-      WebForward    = OIS::KC_WEBFORWARD,      // Web Forward
-      WebBack       = OIS::KC_WEBBACK,         // Web Back
-      MyComputer    = OIS::KC_MYCOMPUTER,      // My Computer
-      Mail          = OIS::KC_MAIL,            // Mail
-      MediaSelect   = OIS::KC_MEDIASELECT      // Media Select
-    };
-  }
-
-  namespace MouseButton
-  {
-    enum Enum
-    {
-      Left    = OIS::MB_Left,
-      Right   = OIS::MB_Right,
-      Middle  = OIS::MB_Middle,
-      Button3 = OIS::MB_Button3,
-      Button4 = OIS::MB_Button4,
-      Button5 = OIS::MB_Button5,
-      Button6 = OIS::MB_Button6,
-      Button7 = OIS::MB_Button7
-    };
-  }
-
-  namespace KeyboardModifier
-  {
-    enum Enum
-    {
-      Shift = 0x0000001,
-      Ctrl  = 0x0000010,
-      Alt   = 0x0000100
-    };
-  }
-
-  struct _CoreExport Key
-  {
-    Key(const OIS::KeyEvent& evt) : key((KeyCode::Enum)evt.key), text(evt.text) { }
-    KeyCode::Enum key;
-    unsigned int text;
-  };
-
-  class _CoreExport KeyEvent
-  {
-  public:
-    KeyEvent(KeyCode::Enum key, unsigned int text) : key(key), text(text) { }
-    KeyEvent(const OIS::KeyEvent& evt, unsigned int mod) : key((KeyCode::Enum)evt.key), text(evt.text), modifiers(mod) { }
-    KeyEvent(const Key& key, unsigned int mod) : key(key.key), text(key.text), modifiers(mod) { }
-    bool isModifierDown(KeyboardModifier::Enum modifier) const { return (KeyboardModifier::Enum)modifier&modifiers; }
-
-    const KeyCode::Enum key;
-    unsigned int text;
-    unsigned int modifiers;
-  };
-
-  //typedef OIS::MouseState MouseState;
-
-  /*class _CoreExport JoyStickState
-  {
-  public:
-    JoyStickState(const OIS::JoyStickState& state, int ID) : OIS::JoyStickState(state), mJoyStickID(ID) { }
-    JoyStickState() { clear(); }
-    int mJoyStickID;
-		JoyStickState() { clear(); }
-
-		std::vector<bool> mButtons;
-		int axes[16];
-		std::vector<Vector3> mVectors;
-  };*/
-
-  /**
-  * Helper struct to determine which handlers of an object (can implement
-  * multiple handlers) are active.
-  */
-  struct HandlerState
-  {
-    HandlerState() : key(false), mouse(false), joyStick(false) { }
-    bool key;
-    bool mouse;
-    bool joyStick;
-  };
-
-  class _CoreExport InputTickable
-  {
-  public:
-    virtual ~InputTickable() { }
-    virtual void tickInput(float dt, const HandlerState& state) = 0;
-  };
-
-  /**
-    @brief Interface class used for key input listeners.
-  */
-  class _CoreExport KeyHandler : virtual public InputTickable
-  {
-  public:
-    virtual ~KeyHandler() { }
-    virtual void keyPressed (const KeyEvent& evt) = 0;
-    virtual void keyReleased(const KeyEvent& evt) = 0;
-    virtual void keyHeld    (const KeyEvent& evt) = 0;
-    //virtual void tickKey    (float dt) { }
-  };
-
-  /**
-    @brief Interface class used for mouse input listeners.
-  */
-  class _CoreExport MouseHandler : virtual public InputTickable
-  {
-  public:
-    virtual ~MouseHandler() { }
-    virtual void mouseButtonPressed (MouseButton::Enum id) = 0;
-    virtual void mouseButtonReleased(MouseButton::Enum id) = 0;
-    virtual void mouseButtonHeld    (MouseButton::Enum id) = 0;
-    virtual void mouseMoved         (IntVector2 abs, IntVector2 rel, IntVector2 clippingSize) = 0;
-    virtual void mouseScrolled      (int abs, int rel)     = 0;
-    //virtual void tickMouse          (float dt) { }
-  };
-
-
-  /**
-    @brief Interface class used for joy stick input listeners.
-  */
-  class _CoreExport JoyStickHandler : virtual public InputTickable
-  {
-  public:
-    virtual ~JoyStickHandler() { }
-    virtual void joyStickButtonPressed (int joyStickID, int button) = 0;
-    virtual void joyStickButtonReleased(int joyStickID, int button) = 0;
-    virtual void joyStickButtonHeld    (int joyStickID, int button) = 0;
-    virtual void joyStickAxisMoved     (int joyStickID, int axis, float value) = 0;
-    //virtual bool joyStickVector3Moved  (int joyStickID, int index /*, fill list*/) {return true;}
-    //virtual void tickJoyStick          (float dt) { }
-  };
+    namespace KeyCode
+    {
+        // note: KeyCode comments were directly copied from OISKeyboard.h
+        enum Enum
+        {
+            Unassigned    = OIS::KC_UNASSIGNED,
+            Escape        = OIS::KC_ESCAPE,
+            NumRow1       = OIS::KC_1,
+            NumRow2       = OIS::KC_2,
+            NumRow3       = OIS::KC_3,
+            NumRow4       = OIS::KC_4,
+            NumRow5       = OIS::KC_5,
+            NumRow6       = OIS::KC_6,
+            NumRow7       = OIS::KC_7,
+            NumRow8       = OIS::KC_8,
+            NumRow9       = OIS::KC_9,
+            NumRow0       = OIS::KC_0,
+            Minus         = OIS::KC_MINUS,           // - on main keyboard
+            Equals        = OIS::KC_EQUALS,
+            Back          = OIS::KC_BACK,            // backspace
+            Tab           = OIS::KC_TAB,
+            Q             = OIS::KC_Q,
+            W             = OIS::KC_W,
+            E             = OIS::KC_E,
+            R             = OIS::KC_R,
+            T             = OIS::KC_T,
+            Y             = OIS::KC_Y,
+            U             = OIS::KC_U,
+            I             = OIS::KC_I,
+            O             = OIS::KC_O,
+            P             = OIS::KC_P,
+            LeftBracket   = OIS::KC_LBRACKET,
+            RightBracket  = OIS::KC_RBRACKET,
+            Return        = OIS::KC_RETURN,          // Enter on main keyboard
+            LeftControl   = OIS::KC_LCONTROL,
+            A             = OIS::KC_A,
+            S             = OIS::KC_S,
+            D             = OIS::KC_D,
+            F             = OIS::KC_F,
+            G             = OIS::KC_G,
+            H             = OIS::KC_H,
+            J             = OIS::KC_J,
+            K             = OIS::KC_K,
+            L             = OIS::KC_L,
+            Semicolon     = OIS::KC_SEMICOLON,
+            Apostrophe    = OIS::KC_APOSTROPHE,
+            Grave         = OIS::KC_GRAVE,           // accent
+            LeftShift     = OIS::KC_LSHIFT,
+            Backslash     = OIS::KC_BACKSLASH,
+            Z             = OIS::KC_Z,
+            X             = OIS::KC_X,
+            C             = OIS::KC_C,
+            V             = OIS::KC_V,
+            B             = OIS::KC_B,
+            N             = OIS::KC_N,
+            M             = OIS::KC_M,
+            Comma         = OIS::KC_COMMA,
+            Period        = OIS::KC_PERIOD,          // . on main keyboard
+            Slash         = OIS::KC_SLASH,           // / on main keyboard
+            RightShift    = OIS::KC_RSHIFT,
+            Multiply      = OIS::KC_MULTIPLY,        // * on numeric keypad
+            LeftAlt       = OIS::KC_LMENU,           // left Alt
+            Space         = OIS::KC_SPACE,
+            CapsLock      = OIS::KC_CAPITAL,
+            F1            = OIS::KC_F1,
+            F2            = OIS::KC_F2,
+            F3            = OIS::KC_F3,
+            F4            = OIS::KC_F4,
+            F5            = OIS::KC_F5,
+            F6            = OIS::KC_F6,
+            F7            = OIS::KC_F7,
+            F8            = OIS::KC_F8,
+            F9            = OIS::KC_F9,
+            F10           = OIS::KC_F10,
+            Numlock       = OIS::KC_NUMLOCK,
+            Scrolllock    = OIS::KC_SCROLL,          // Scroll Lock
+            Numpad7       = OIS::KC_NUMPAD7,
+            Numpad8       = OIS::KC_NUMPAD8,
+            Numpad9       = OIS::KC_NUMPAD9,
+            NumpadSubtract= OIS::KC_SUBTRACT,        // - on numeric keypad
+            Numpad4       = OIS::KC_NUMPAD4,
+            Numpad5       = OIS::KC_NUMPAD5,
+            Numpad6       = OIS::KC_NUMPAD6,
+            NumpadAdd     = OIS::KC_ADD,             // + on numeric keypad
+            Numpad1       = OIS::KC_NUMPAD1,
+            Numpad2       = OIS::KC_NUMPAD2,
+            Numpad3       = OIS::KC_NUMPAD3,
+            Numpad0       = OIS::KC_NUMPAD0,
+            NumpadPeriod  = OIS::KC_DECIMAL,         // . on numeric keypad
+            LessThan      = OIS::KC_OEM_102,         // < > | on UK/Germany keyboards
+            F11           = OIS::KC_F11,
+            F12           = OIS::KC_F12,
+            F13           = OIS::KC_F13,             //                     (NEC PC98)
+            F14           = OIS::KC_F14,             //                     (NEC PC98)
+            F15           = OIS::KC_F15,             //                     (NEC PC98)
+            Kana          = OIS::KC_KANA,            // (Japanese keyboard)
+            ABNT_C1       = OIS::KC_ABNT_C1,         // / ? on Portugese (Brazilian) keyboards
+            Convert       = OIS::KC_CONVERT,         // (Japanese keyboard)
+            NoConvert     = OIS::KC_NOCONVERT,       // (Japanese keyboard)
+            Yen           = OIS::KC_YEN,             // (Japanese keyboard)
+            ABNT_C2       = OIS::KC_ABNT_C2,         // Numpad . on Portugese (Brazilian) keyboards
+            NumpadEquals  = OIS::KC_NUMPADEQUALS,    // = on numeric keypad (NEC PC98)
+            PreviousTrack = OIS::KC_PREVTRACK,       // Previous Track (KC_CIRCUMFLEX on Japanese keyboard)
+            AT            = OIS::KC_AT,              //                     (NEC PC98)
+            Colon         = OIS::KC_COLON,           //                     (NEC PC98)
+            Underline     = OIS::KC_UNDERLINE,       //                     (NEC PC98)
+            Kanji         = OIS::KC_KANJI,           // (Japanese keyboard)
+            Stop          = OIS::KC_STOP,            //                     (NEC PC98)
+            AX            = OIS::KC_AX,              //                     (Japan AX)
+            Unlabeled     = OIS::KC_UNLABELED,       //                        (J3100)
+            NextTrack     = OIS::KC_NEXTTRACK,       // Next Track
+            NumpadEnter   = OIS::KC_NUMPADENTER,     // Enter on numeric keypad
+            RightControl  = OIS::KC_RCONTROL,
+            Mute          = OIS::KC_MUTE,            // Mute
+            Calculator    = OIS::KC_CALCULATOR,      // Calculator
+            PlayPause     = OIS::KC_PLAYPAUSE,       // Play / Pause
+            MediaStop     = OIS::KC_MEDIASTOP,       // Media Stop
+            VolumeDown    = OIS::KC_VOLUMEDOWN,      // Volume -
+            VolumeUp      = OIS::KC_VOLUMEUP,        // Volume +
+            WebHome       = OIS::KC_WEBHOME,         // Web home
+            NumpadComma   = OIS::KC_NUMPADCOMMA,     // , on numeric keypad (NEC PC98)
+            Divide        = OIS::KC_DIVIDE,          // / on numeric keypad
+            SYSRQ         = OIS::KC_SYSRQ,
+            RightAlt      = OIS::KC_RMENU,           // right Alt
+            Pause         = OIS::KC_PAUSE,           // Pause
+            Home          = OIS::KC_HOME,            // Home on arrow keypad
+            Up            = OIS::KC_UP,              // UpArrow on arrow keypad
+            PageUp        = OIS::KC_PGUP,            // PgUp on arrow keypad
+            Left          = OIS::KC_LEFT,            // LeftArrow on arrow keypad
+            Right         = OIS::KC_RIGHT,           // RightArrow on arrow keypad
+            End           = OIS::KC_END,             // End on arrow keypad
+            Down          = OIS::KC_DOWN,            // DownArrow on arrow keypad
+            PageDown      = OIS::KC_PGDOWN,          // PgDn on arrow keypad
+            Insert        = OIS::KC_INSERT,          // Insert on arrow keypad
+            Delete        = OIS::KC_DELETE,          // Delete on arrow keypad
+            LeftWindows   = OIS::KC_LWIN,            // Left Windows key
+            RightWindows  = OIS::KC_RWIN,            // Right Windows key
+            Apps          = OIS::KC_APPS,            // AppMenu key
+            Power         = OIS::KC_POWER,           // System Power
+            Sleep         = OIS::KC_SLEEP,           // System Sleep
+            Wake          = OIS::KC_WAKE,            // System Wake
+            WebSearch     = OIS::KC_WEBSEARCH,       // Web Search
+            WebFavorites  = OIS::KC_WEBFAVORITES,    // Web Favorites
+            WebRefresh    = OIS::KC_WEBREFRESH,      // Web Refresh
+            WebStop       = OIS::KC_WEBSTOP,         // Web Stop
+            WebForward    = OIS::KC_WEBFORWARD,      // Web Forward
+            WebBack       = OIS::KC_WEBBACK,         // Web Back
+            MyComputer    = OIS::KC_MYCOMPUTER,      // My Computer
+            Mail          = OIS::KC_MAIL,            // Mail
+            MediaSelect   = OIS::KC_MEDIASELECT      // Media Select
+        };
+    }
+
+    namespace MouseButton
+    {
+        enum Enum
+        {
+            Left    = OIS::MB_Left,
+            Right   = OIS::MB_Right,
+            Middle  = OIS::MB_Middle,
+            Button3 = OIS::MB_Button3,
+            Button4 = OIS::MB_Button4,
+            Button5 = OIS::MB_Button5,
+            Button6 = OIS::MB_Button6,
+            Button7 = OIS::MB_Button7
+        };
+    }
+
+    namespace KeyboardModifier
+    {
+        enum Enum
+        {
+            Shift = 0x0000001,
+            Ctrl  = 0x0000010,
+            Alt   = 0x0000100
+        };
+    }
+    
+    namespace InputDevice
+    {
+        enum Enum
+        {
+            Keyboard,
+            Mouse,
+            JoyStick0,
+            JoyStick1,
+            JoyStick2,
+            JoyStick3,
+            // note: No problem if there are more joy sticks. This enum is just for convenience.
+        };
+    }
+
+    struct _CoreExport Key
+    {
+        Key(const OIS::KeyEvent& evt) : key((KeyCode::Enum)evt.key), text(evt.text) { }
+        KeyCode::Enum key;
+        unsigned int text;
+    };
+
+    class _CoreExport KeyEvent
+    {
+    public:
+        KeyEvent(KeyCode::Enum key, unsigned int text) : key(key), text(text) { }
+        KeyEvent(const OIS::KeyEvent& evt, unsigned int mod)
+            : key((KeyCode::Enum)evt.key), text(evt.text), modifiers(mod) { }
+        KeyEvent(const Key& key, unsigned int mod) : key(key.key), text(key.text), modifiers(mod) { }
+        bool isModifierDown(KeyboardModifier::Enum modifier) const
+            { return (KeyboardModifier::Enum)modifier&modifiers; }
+
+        const KeyCode::Enum key;
+        unsigned int text;
+        unsigned int modifiers;
+    };
+
+    //typedef OIS::MouseState MouseState;
+
+    /*class _CoreExport JoyStickState
+    {
+    public:
+        JoyStickState(const OIS::JoyStickState& state, int ID) : OIS::JoyStickState(state), mJoyStickID(ID) { }
+        JoyStickState() { clear(); }
+        int mJoyStickID;
+        JoyStickState() { clear(); }
+
+        std::vector<bool> mButtons;
+        int axes[16];
+        std::vector<Vector3> mVectors;
+    };*/
+
+    /**
+    @brief
+        Helper struct to determine which handlers of an object (can implement
+        multiple handlers) are active.
+    */
+    //struct HandlerState
+    //{
+    //    HandlerState() : keyboard(false), mouse(false) { }
+    //    bool keyboard;
+    //    bool mouse;
+    //    std::vector<bool> joySticks;
+    //};
+
+    class _CoreExport InputTickable
+    {
+    public:
+        virtual ~InputTickable() { }
+        virtual void tickInput(float dt) = 0;
+        //virtual void tickInput(float dt, unsigned int device) = 0;
+    };
+
+    /**
+    @brief
+        Interface class used for key input listeners.
+    */
+    class _CoreExport KeyHandler : virtual public InputTickable
+    {
+    public:
+        virtual ~KeyHandler() { }
+        virtual void keyPressed (const KeyEvent& evt) = 0;
+        virtual void keyReleased(const KeyEvent& evt) = 0;
+        virtual void keyHeld    (const KeyEvent& evt) = 0;
+        virtual void tickKey    (float dt) { }
+    };
+
+    /**
+    @brief
+        Interface class used for mouse input listeners.
+    */
+    class _CoreExport MouseHandler : virtual public InputTickable
+    {
+    public:
+        virtual ~MouseHandler() { }
+        virtual void mouseButtonPressed (MouseButton::Enum id) = 0;
+        virtual void mouseButtonReleased(MouseButton::Enum id) = 0;
+        virtual void mouseButtonHeld    (MouseButton::Enum id) = 0;
+        virtual void mouseMoved         (IntVector2 abs, IntVector2 rel, IntVector2 clippingSize) = 0;
+        virtual void mouseScrolled      (int abs, int rel)     = 0;
+        virtual void tickMouse          (float dt) { }
+    };
+
+
+    /**
+    @brief
+        Interface class used for joy stick input listeners.
+    */
+    class _CoreExport JoyStickHandler : virtual public InputTickable
+    {
+    public:
+        virtual ~JoyStickHandler() { }
+        virtual void joyStickButtonPressed (unsigned int joyStickID, unsigned int button) = 0;
+        virtual void joyStickButtonReleased(unsigned int joyStickID, unsigned int button) = 0;
+        virtual void joyStickButtonHeld    (unsigned int joyStickID, unsigned int button) = 0;
+        virtual void joyStickAxisMoved     (unsigned int joyStickID, unsigned int axis, float value) = 0;
+        //virtual bool joyStickVector3Moved  (unsigned int joyStickID, unsigned int index /*, fill list*/) {return true;}
+        virtual void tickJoyStick          (float dt, unsigned int device) { }
+    };
+
+    class _CoreExport EmptyHandler : public KeyHandler, public MouseHandler, public JoyStickHandler
+    {
+    private:
+        void tickInput(float dt) { }
+        void tickInput(float dt, unsigned int device) { }
+
+        void keyPressed (const KeyEvent& evt) { }
+        void keyReleased(const KeyEvent& evt) { }
+        void keyHeld    (const KeyEvent& evt) { }
+
+        void mouseButtonPressed (MouseButton::Enum id) { }
+        void mouseButtonReleased(MouseButton::Enum id) { }
+        void mouseButtonHeld    (MouseButton::Enum id) { }
+        void mouseMoved         (IntVector2 abs, IntVector2 rel, IntVector2 clippingSize) { }
+        void mouseScrolled      (int abs, int rel) { }
+
+        void joyStickButtonPressed (unsigned int joyStickID, unsigned int button) { }
+        void joyStickButtonReleased(unsigned int joyStickID, unsigned int button) { }
+        void joyStickButtonHeld    (unsigned int joyStickID, unsigned int button) { }
+        void joyStickAxisMoved     (unsigned int joyStickID, unsigned int axis, float value) { }
+    };
 
 }
Index: code/branches/gui/src/core/input/InputManager.cc
===================================================================
--- code/branches/gui/src/core/input/InputManager.cc	(revision 1636)
+++ code/branches/gui/src/core/input/InputManager.cc	(revision 1638)
@@ -28,12 +28,17 @@
 
 /**
-  @file
-  @brief Implementation of the InputManager that captures all the input from OIS
-         and redirects it to handlers.
+@file
+@brief
+    Implementation of the InputManager that captures all the input from OIS
+    and redirects it to handlers.
  */
 
 #include "InputManager.h"
 
-#include <limits.h>
+#include <climits>
+#include <cassert>
+
+#include "ois/OISException.h"
+#include "ois/OISInputManager.h"
 
 #include "core/CoreIncludes.h"
@@ -42,5 +47,4 @@
 #include "core/CommandExecutor.h"
 #include "core/ConsoleCommand.h"
-#include "core/Shell.h"               // hack!
 
 #include "InputBuffer.h"
@@ -48,1510 +52,1192 @@
 #include "KeyDetector.h"
 #include "CalibratorCallback.h"
-
-#include "src/ois/OISException.h"
-#include "src/ois/OISInputManager.h"
+#include "InputState.h"
+#include "SimpleInputState.h"
+#include "ExtendedInputState.h"
 
 namespace orxonox
 {
-  SetConsoleCommandShortcut(InputManager, keyBind);
-  SetConsoleCommandShortcut(InputManager, storeKeyStroke);
-  SetConsoleCommandShortcut(InputManager, calibrate);
-
-  // ###############################
-  // ###    Internal Methods     ###
-  // ###############################
-  // ###############################
-
-  /**
-    @brief Constructor only sets member fields to initial zero values
-           and registers the class in the class hierarchy.
-  */
-  InputManager::InputManager() :
-      inputSystem_(0), keyboard_(0), mouse_(0),
-      joySticksSize_(0),
-      keyBinder_(0), keyDetector_(0), buffer_(0), calibratorCallback_(0),
-      state_(IS_UNINIT), stateRequest_(IS_UNINIT), savedState_(IS_UNINIT),
-      keyboardModifiers_(0)
-  {
-    RegisterRootObject(InputManager);
-  }
-
-  /**
-    @brief The one instance of the InputManager is stored in this function.
-    @return A reference to the only instance of the InputManager
-  */
-  InputManager& InputManager::_getSingleton()
-  {
-    static InputManager theOnlyInstance;
-    return theOnlyInstance;
-  }
-
-  /**
-    @brief Destructor only called at the end of the program, after main.
-  */
-  InputManager::~InputManager()
-  {
-    _destroy();
-  }
-
-  /**
-    @brief Creates the OIS::InputMananger, the keyboard, the mouse and
-           the joysticks and assigns the key bindings.
-    @param windowHnd The window handle of the render window
-    @param windowWidth The width of the render window
-    @param windowHeight The height of the render window
-  */
-  bool InputManager::_initialise(const size_t windowHnd, int windowWidth, int windowHeight,
+    SetConsoleCommandShortcut(InputManager, keyBind);
+    SetConsoleCommandShortcut(InputManager, storeKeyStroke);
+    SetConsoleCommandShortcut(InputManager, calibrate);
+
+    using namespace InputDevice;
+
+    // ###############################
+    // ###    Internal Methods     ###
+    // ###############################
+    // ###############################
+
+    /**
+    @brief
+        Constructor only sets member fields to initial zero values
+        and registers the class in the class hierarchy.
+    */
+    InputManager::InputManager()
+        : inputSystem_(0)
+        , keyboard_(0)
+        , mouse_(0)
+        , joySticksSize_(0)
+        , devicesNum_(0)
+        , stateDetector_(0)
+        , stateCalibrator_(0)
+        , stateEmpty_(0)
+        , keyboardModifiers_(0)
+        , bCalibrating_(false)
+    {
+        RegisterRootObject(InputManager);
+    }
+
+    /**
+    @brief
+        The one instance of the InputManager is stored in this function.
+    @return
+        A reference to the only instance of the InputManager
+    */
+    InputManager& InputManager::_getInstance()
+    {
+        static InputManager theOnlyInstance;
+        return theOnlyInstance;
+    }
+
+    /**
+    @brief
+        Destructor only called at the end of the program, after main.
+    */
+    InputManager::~InputManager()
+    {
+        _destroy();
+    }
+
+
+    // ############################################################
+    // #####                  Initialisation                  #####
+    // ##########                                        ##########
+    // ############################################################
+
+    /**
+    @brief
+        Creates the OIS::InputMananger, the keyboard, the mouse and
+        the joysticks and assigns the key bindings.
+    @param windowHnd
+        The window handle of the render window
+    @param windowWidth
+        The width of the render window
+    @param windowHeight
+        The height of the render window
+    */
+    bool InputManager::_initialise(const size_t windowHnd, int windowWidth, int windowHeight,
+                                   bool createKeyboard, bool createMouse, bool createJoySticks)
+    {
+        if (inputSystem_ == 0)
+        {
+            CCOUT(3) << "Initialising Input System..." << std::endl;
+            CCOUT(ORX_DEBUG) << "Initialising OIS components..." << std::endl;
+
+            OIS::ParamList paramList;
+            std::ostringstream windowHndStr;
+
+            // Fill parameter list
+            windowHndStr << (unsigned int)windowHnd;
+            paramList.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
+            //paramList.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_NONEXCLUSIVE")));
+            //paramList.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_FOREGROUND")));
+//#if defined OIS_LINUX_PLATFORM
+            //paramList.insert(std::make_pair(std::string("XAutoRepeatOn"), std::string("true")));
+//#endif
+
+            try
+            {
+                inputSystem_ = OIS::InputManager::createInputSystem(paramList);
+                CCOUT(ORX_DEBUG) << "Created OIS input system" << std::endl;
+            }
+            catch (OIS::Exception ex)
+            {
+                CCOUT(ORX_ERROR) << "Error: Failed creating an OIS input system."
+                    << "OIS message: \"" << ex.eText << "\"" << std::endl;
+                inputSystem_ = 0;
+                return false;
+            }
+
+            if (createKeyboard)
+                _initialiseKeyboard();
+
+            if (createMouse)
+                _initialiseMouse();
+
+            if (createJoySticks)
+                _initialiseJoySticks();
+
+            // set all the std::vector list sizes now that the devices have been created
+            _redimensionLists();
+
+            // Set mouse/joystick region
+            if (mouse_)
+            {
+                setWindowExtents(windowWidth, windowHeight);
+            }
+
+            CCOUT(ORX_DEBUG) << "Initialising OIS components done." << std::endl;
+
+            // InputManager holds the input buffer --> create one and add it.
+            //buffer_ = new InputBuffer();
+            //addKeyHandler(buffer_, "buffer");
+            //Shell::getInstance().setInputBuffer(buffer_);
+
+            setConfigValues();
+
+            stateEmpty_ = createSimpleInputState("empty", -1);
+            stateEmpty_->setHandler(new EmptyHandler());
+            activeStates_[stateEmpty_->getPriority()] = stateEmpty_;
+
+            stateDetector_ = createSimpleInputState("detector", 101);
+            KeyDetector* temp = new KeyDetector();
+            temp->loadBindings("storeKeyStroke");
+            stateDetector_->setHandler(temp);
+
+            stateCalibrator_ = createSimpleInputState("calibrator", 100);
+            stateCalibrator_->setHandler(new EmptyHandler());
+            InputBuffer* buffer = new InputBuffer();
+            buffer->registerListener(this, &InputManager::_completeCalibration, '\r', true);
+            stateCalibrator_->setKeyHandler(buffer);
+
+            _updateActiveStates();
+
+            CCOUT(ORX_DEBUG) << "Initialising complete." << std::endl;
+        }
+        else
+        {
+            CCOUT(ORX_WARNING) << "Warning: OIS compoments already initialised, skipping" << std::endl;
+        }
+        return true;
+    }
+
+    /**
+    @brief
+        Creates a keyboard and sets the event handler.
+    @return
+        False if keyboard stays uninitialised, true otherwise.
+    */
+    bool InputManager::_initialiseKeyboard()
+    {
+        if (keyboard_ != 0)
+        {
+            CCOUT(2) << "Warning: Keyboard already initialised, skipping." << std::endl;
+            return true;
+        }
+        try
+        {
+            if (inputSystem_->getNumberOfDevices(OIS::OISKeyboard) > 0)
+            {
+                keyboard_ = (OIS::Keyboard*)inputSystem_->createInputObject(OIS::OISKeyboard, true);
+                // register our listener in OIS.
+                keyboard_->setEventCallback(this);
+                // note: OIS will not detect keys that have already been down when the keyboard was created.
+                CCOUT(ORX_DEBUG) << "Created OIS keyboard" << std::endl;
+                return true;
+            }
+            else
+            {
+                CCOUT(ORX_WARNING) << "Warning: No keyboard found!" << std::endl;
+                return false;
+            }
+        }
+        catch (OIS::Exception ex)
+        {
+            CCOUT(ORX_WARNING) << "Warning: Failed to create an OIS keyboard\n"
+                << "OIS error message: \"" << ex.eText << "\"" << std::endl;
+            keyboard_ = 0;
+            return false;
+        }
+    }
+
+    /**
+    @brief
+        Creates a mouse and sets the event handler.
+    @return
+        False if mouse stays uninitialised, true otherwise.
+    */
+    bool InputManager::_initialiseMouse()
+    {
+        if (mouse_ != 0)
+        {
+            CCOUT(2) << "Warning: Mouse already initialised, skipping." << std::endl;
+            return true;
+        }
+        try
+        {
+            if (inputSystem_->getNumberOfDevices(OIS::OISMouse) > 0)
+            {
+                mouse_ = static_cast<OIS::Mouse*>(inputSystem_->createInputObject(OIS::OISMouse, true));
+                // register our listener in OIS.
+                mouse_->setEventCallback(this);
+                CCOUT(ORX_DEBUG) << "Created OIS mouse" << std::endl;
+                return true;
+            }
+            else
+            {
+                CCOUT(ORX_WARNING) << "Warning: No mouse found!" << std::endl;
+                return false;
+            }
+        }
+        catch (OIS::Exception ex)
+        {
+            CCOUT(ORX_WARNING) << "Warning: Failed to create an OIS mouse\n"
+                << "OIS error message: \"" << ex.eText << "\"" << std::endl;
+            mouse_ = 0;
+            return false;
+        }
+    }
+
+    /**
+    @brief
+        Creates all joy sticks and sets the event handler.
+    @return
+        False joy stick stay uninitialised, true otherwise.
+    */
+    bool InputManager::_initialiseJoySticks()
+    {
+        if (joySticksSize_ > 0)
+        {
+            CCOUT(2) << "Warning: Joy sticks already initialised, skipping." << std::endl;
+            return true;
+        }
+        bool success = false;
+        if (inputSystem_->getNumberOfDevices(OIS::OISJoyStick) > 0)
+        {
+            for (int i = 0; i < inputSystem_->getNumberOfDevices(OIS::OISJoyStick); i++)
+            {
+                try
+                {
+                    OIS::JoyStick* stig = static_cast<OIS::JoyStick*>
+                        (inputSystem_->createInputObject(OIS::OISJoyStick, true));
+                    CCOUT(ORX_DEBUG) << "Created OIS joy stick with ID " << stig->getID() << std::endl;
+                    joySticks_.push_back(stig);
+                    // register our listener in OIS.
+                    stig->setEventCallback(this);
+                    success = true;
+                }
+                catch (OIS::Exception ex)
+                {
+                    CCOUT(ORX_WARNING) << "Warning: Failed to create OIS joy number" << i << "\n"
+                        << "OIS error message: \"" << ex.eText << "\"" << std::endl;
+                }
+            }
+        }
+        else
+        {
+            CCOUT(ORX_WARNING) << "Warning: Joy stick support requested, but no joy stick was found" << std::endl;
+            return false;
+        }
+        return success;
+    }
+
+    void InputManager::_redimensionLists()
+    {
+        joySticksSize_ = joySticks_.size();
+        devicesNum_ = 2 + joySticksSize_;
+        joyStickButtonsDown_ .resize(joySticksSize_);
+        povStates_           .resize(joySticksSize_);
+        sliderStates_        .resize(joySticksSize_);
+        joySticksCalibration_.resize(joySticksSize_);
+
+        for (unsigned int iJoyStick = 0; iJoyStick < joySticksSize_; iJoyStick++)
+        {
+            // reset the calibration with default values
+            for (unsigned int i = 0; i < 24; i++)
+            {
+                joySticksCalibration_[iJoyStick].negativeCoeff[i] = 1.0f/32767.0f;
+                joySticksCalibration_[iJoyStick].positiveCoeff[i] = 1.0f/32768.0f;
+                joySticksCalibration_[iJoyStick].zeroStates[i] = 0;
+            }
+        }
+
+        // state management
+        activeStatesTop_.resize(devicesNum_);
+
+        // inform all registered states
+        for (std::map<int, InputState*>::const_iterator it = inputStatesByPriority_.begin();
+            it != inputStatesByPriority_.end(); ++it)
+            (*it).second->setNumOfJoySticks(joySticksSize_);
+    }
+
+    /**
+    @brief
+        Sets the configurable values. Use keybindings.ini as file..
+    */
+    void InputManager::setConfigValues()
+    {
+        if (joySticksSize_)
+        {
+            std::vector<MultiTypeMath> coeffPos;
+            std::vector<MultiTypeMath> coeffNeg;
+            std::vector<MultiTypeMath> zero;
+            coeffPos.resize(24);
+            coeffNeg.resize(24);
+            zero.resize(24);
+            for (unsigned int i = 0; i < 24; i++)
+            {
+                coeffPos[i] =  1.0f/32767.0f;
+                coeffNeg[i] =  1.0f/32768.0f;
+                zero[i]     =  0;
+            }
+
+            ConfigValueContainer* cont = getIdentifier()->getConfigValueContainer("CoeffPos");
+            if (!cont)
+            {
+                cont = new ConfigValueContainer(CFT_Keybindings, getIdentifier(), "CoeffPos", coeffPos);
+                getIdentifier()->addConfigValueContainer("CoeffPos", cont);
+            }
+            cont->getValue(&coeffPos);
+
+            cont = getIdentifier()->getConfigValueContainer("CoeffNeg");
+            if (!cont)
+            {
+                cont = new ConfigValueContainer(CFT_Keybindings, getIdentifier(), "CoeffNeg", coeffNeg);
+                getIdentifier()->addConfigValueContainer("CoeffNeg", cont);
+            }
+            cont->getValue(&coeffNeg);
+
+            cont = getIdentifier()->getConfigValueContainer("Zero");
+            if (!cont)
+            {
+                cont = new ConfigValueContainer(CFT_Keybindings, getIdentifier(), "Zero", zero);
+                getIdentifier()->addConfigValueContainer("Zero", cont);
+            }
+            cont->getValue(&zero);
+
+            // copy values to our own variables
+            for (unsigned int i = 0; i < 24; i++)
+            {
+                joySticksCalibration_[0].positiveCoeff[i] = coeffPos[i];
+                joySticksCalibration_[0].negativeCoeff[i] = coeffNeg[i];
+                joySticksCalibration_[0].zeroStates[i]    = zero[i];
+            }
+        }
+    }
+
+
+    // ############################################################
+    // #####                    Destruction                   #####
+    // ##########                                        ##########
+    // ############################################################
+
+    /**
+    @brief
+        Destroys all the created input devices and sets the InputManager to construction state.
+    */
+    void InputManager::_destroy()
+    {
+        if (inputSystem_)
+        {
+            CCOUT(ORX_DEBUG) << "Destroying ..." << std::endl;
+
+            // kick all active states 'nicely'
+            for (std::map<int, InputState*>::reverse_iterator rit = activeStates_.rbegin();
+                rit != activeStates_.rend(); ++rit)
+                (*rit).second->onLeave();
+            activeStates_.clear();
+
+            // destroy our own states
+            stateEmpty_->removeAndDestroyAllHandlers();
+            stateCalibrator_->removeAndDestroyAllHandlers();
+            stateDetector_->removeAndDestroyAllHandlers();
+            _destroyState(stateEmpty_);
+            _destroyState(stateCalibrator_);
+            _destroyState(stateDetector_);
+            stateEmpty_ = 0;
+            stateCalibrator_ = 0;
+            stateDetector_ = 0;
+
+            // we don't remove the other states yet because the singleton might still exist.
+            // So people can still removeAndDestroy their states
+            //inputStatesByName_.clear();
+            //inputStatesByPriority_.clear();
+
+            // destroy the devices
+            _destroyKeyboard();
+            _destroyMouse();
+            _destroyJoySticks();
+
+            _redimensionLists();
+
+            OIS::InputManager::destroyInputSystem(inputSystem_);
+            inputSystem_ = 0;
+
+            CCOUT(ORX_DEBUG) << "Destroying done." << std::endl;
+        }
+    }
+
+    /**
+    @brief
+        Destroys the keyboard and sets it to 0.
+    */
+    void InputManager::_destroyKeyboard()
+    {
+        if (keyboard_)
+            inputSystem_->destroyInputObject(keyboard_);
+        keyboard_ = 0;
+        keysDown_.clear();
+        CCOUT(ORX_DEBUG) << "Keyboard destroyed." << std::endl;
+    }
+
+    /**
+    @brief
+        Destroys the mouse and sets it to 0.
+    */
+    void InputManager::_destroyMouse()
+    {
+        if (mouse_)
+            inputSystem_->destroyInputObject(mouse_);
+        mouse_ = 0;
+        mouseButtonsDown_.clear();
+        CCOUT(ORX_DEBUG) << "Mouse destroyed." << std::endl;
+    }
+
+    /**
+    @brief
+        Destroys all the joy sticks and resizes the lists to 0.
+    */
+    void InputManager::_destroyJoySticks()
+    {
+        if (joySticksSize_ > 0)
+        {
+            // note: inputSystem_ can never be 0, or else the code is mistaken
+            for (unsigned int i = 0; i < joySticksSize_; i++)
+                if (joySticks_[i] != 0)
+                    inputSystem_->destroyInputObject(joySticks_[i]);
+
+            joySticks_.clear();
+        }
+        CCOUT(ORX_DEBUG) << "Joy sticks destroyed." << std::endl;
+    }
+
+    void InputManager::_destroyState(InputState* state)
+    {
+        assert(state);
+        inputStatesByPriority_.erase(state->getPriority());
+        inputStatesByName_.erase(state->getName());
+        delete state;
+    }
+
+
+    // ############################################################
+    // #####                  Runtime Methods                 #####
+    // ##########                                        ##########
+    // ############################################################
+
+    /**
+    @brief
+        Updates the InputManager. Tick is called by the Core class.
+    @param dt
+        Delta time
+    */
+    void InputManager::_tick(float dt)
+    {
+        if (inputSystem_ == 0)
+            return;
+
+        // check for states to leave (don't use unsigned int!)
+        for (int i = stateLeaveRequests_.size() - 1; i >= 0; --i)
+        {
+            stateLeaveRequests_[i]->onLeave();
+            // just to be sure that the state actually is registered
+            assert(inputStatesByName_.find(stateLeaveRequests_[i]->getName()) != inputStatesByName_.end());
+            
+            activeStates_.erase(stateLeaveRequests_[i]->getPriority());
+            _updateActiveStates();
+            stateLeaveRequests_.pop_back();
+        }
+
+
+        // check for states to enter (don't use unsigned int!)
+        for (int i = stateEnterRequests_.size() - 1; i >= 0; --i)
+        {
+            // just to be sure that the state actually is registered
+            assert(inputStatesByName_.find(stateEnterRequests_[i]->getName()) != inputStatesByName_.end());
+            
+            activeStates_[stateEnterRequests_[i]->getPriority()] = stateEnterRequests_[i];
+            _updateActiveStates();
+            stateEnterRequests_[i]->onEnter();
+            stateEnterRequests_.pop_back();
+        }
+
+        // Capture all the input. This calls the event handlers in InputManager.
+        if (keyboard_)
+            keyboard_->capture();
+        if (mouse_)
+            mouse_->capture();
+        for (unsigned  int i = 0; i < joySticksSize_; i++)
+            joySticks_[i]->capture();
+
+        if (!bCalibrating_)
+        {
+            // call all the handlers for the held key events
+            for (unsigned int iKey = 0; iKey < keysDown_.size(); iKey++)
+                activeStatesTop_[Keyboard]->keyHeld(KeyEvent(keysDown_[iKey], keyboardModifiers_));
+
+            // call all the handlers for the held mouse button events
+            for (unsigned int iButton = 0; iButton < mouseButtonsDown_.size(); iButton++)
+                activeStatesTop_[Mouse]->mouseButtonHeld(mouseButtonsDown_[iButton]);
+
+            // call all the handlers for the held joy stick button events
+            for (unsigned int iJoyStick  = 0; iJoyStick < joySticksSize_; iJoyStick++)
+                for (unsigned int iButton   = 0; iButton   < joyStickButtonsDown_[iJoyStick].size(); iButton++)
+                    activeStatesTop_[JoyStick0 + iJoyStick]
+                        ->joyStickButtonHeld(iJoyStick, joyStickButtonsDown_[iJoyStick][iButton]);
+
+            // tick the handlers for each active handler
+            for (unsigned int i = 0; i < devicesNum_; ++i)
+                activeStatesTop_[i]->tickInput(dt, i);
+
+            // tick the handler with a general tick afterwards
+            for (unsigned int i = 0; i < activeStatesTicked_.size(); ++i)
+                activeStatesTicked_[i]->tickInput(dt);
+        }
+    }
+
+    void InputManager::_updateActiveStates()
+    {
+        for (std::map<int, InputState*>::const_iterator it = activeStates_.begin(); it != activeStates_.end(); ++it)
+            for (unsigned int i = 0; i < devicesNum_; ++i)
+                if ((*it).second->isInputDeviceEnabled(i))
+                    activeStatesTop_[i] = (*it).second;
+
+        // update tickables (every state will only appear once)
+        // Using a std::set to avoid duplicates
+        std::set<InputState*> tempSet;
+        for (unsigned int i = 0; i < devicesNum_; ++i)
+            tempSet.insert(activeStatesTop_[i]);
+
+        // copy the content of the set back to the actual vector
+        activeStatesTicked_.clear();
+        for (std::set<InputState*>::const_iterator it = tempSet.begin();it != tempSet.end(); ++it)
+            activeStatesTicked_.push_back(*it);
+    }
+
+    void InputManager::_completeCalibration()
+    {
+        for (unsigned int i = 0; i < 24; i++)
+        {
+            // positive coefficient
+            if (marginalsMax_[i] == INT_MIN)
+                marginalsMax_[i] =  32767;
+            // coefficients
+            if (marginalsMax_[i] - joySticksCalibration_[0].zeroStates[i])
+            {
+                joySticksCalibration_[0].positiveCoeff[i]
+                    = 1.0f/(marginalsMax_[i] - joySticksCalibration_[0].zeroStates[i]);
+            }
+            else
+                joySticksCalibration_[0].positiveCoeff[i] =  1.0f;
+
+            // config value
+            ConfigValueContainer* cont = getIdentifier()->getConfigValueContainer("CoeffPos");
+            assert(cont);
+            cont->set(i, joySticksCalibration_[0].positiveCoeff[i]);
+
+            // negative coefficient
+            if (marginalsMin_[i] == INT_MAX)
+                marginalsMin_[i] = -32768;
+            // coefficients
+            if (marginalsMin_[i] - joySticksCalibration_[0].zeroStates[i])
+            {
+                joySticksCalibration_[0].negativeCoeff[i] = -1.0f
+                    / (marginalsMin_[i] - joySticksCalibration_[0].zeroStates[i]);
+            }
+            else
+                joySticksCalibration_[0].negativeCoeff[i] =  1.0f;
+            // config value
+            cont = getIdentifier()->getConfigValueContainer("CoeffNeg");
+            assert(cont);
+            cont->set(i, joySticksCalibration_[0].negativeCoeff[i]);
+
+            // zero states
+            if (i < 8)
+            {
+                if (!(i & 1))
+                    joySticksCalibration_[0].zeroStates[i] = joySticks_[0]->getJoyStickState().mSliders[i/2].abX;
+                else
+                    joySticksCalibration_[0].zeroStates[i] = joySticks_[0]->getJoyStickState().mSliders[i/2].abY;
+            }
+            else
+            {
+                if (i - 8 < joySticks_[0]->getJoyStickState().mAxes.size())
+                    joySticksCalibration_[0].zeroStates[i] = joySticks_[0]->getJoyStickState().mAxes[i - 8].abs;
+                else
+                    joySticksCalibration_[0].zeroStates[i] = 0;
+            }
+            // config value
+            cont = getIdentifier()->getConfigValueContainer("Zero");
+            assert(cont);
+            cont->set(i, joySticksCalibration_[0].zeroStates[i]);
+        }
+
+        // restore old input state
+        requestLeaveState("calibrator");
+    }
+
+
+    // ############################################################
+    // #####                    OIS events                    #####
+    // ##########                                        ##########
+    // ############################################################
+
+    // ###### Key Events ######
+
+    /**
+    @brief
+        Event handler for the keyPressed Event.
+    @param e
+        Event information
+    */
+    bool InputManager::keyPressed(const OIS::KeyEvent &e)
+    {
+        // check whether the key already is in the list (can happen when focus was lost)
+        unsigned int iKey = 0;
+        while (iKey < keysDown_.size() && keysDown_[iKey].key != (KeyCode::Enum)e.key)
+            iKey++;
+        if (iKey == keysDown_.size())
+            keysDown_.push_back(Key(e));
+
+        // update modifiers
+        if(e.key == OIS::KC_RMENU    || e.key == OIS::KC_LMENU)
+            keyboardModifiers_ |= KeyboardModifier::Alt;   // alt key
+        if(e.key == OIS::KC_RCONTROL || e.key == OIS::KC_LCONTROL)
+            keyboardModifiers_ |= KeyboardModifier::Ctrl;  // ctrl key
+        if(e.key == OIS::KC_RSHIFT   || e.key == OIS::KC_LSHIFT)
+            keyboardModifiers_ |= KeyboardModifier::Shift; // shift key
+
+        activeStatesTop_[Keyboard]->keyPressed(KeyEvent(e, keyboardModifiers_));
+
+        return true;
+    }
+
+    /**
+    @brief
+        Event handler for the keyReleased Event.
+    @param e
+        Event information
+    */
+    bool InputManager::keyReleased(const OIS::KeyEvent &e)
+    {
+        // remove the key from the keysDown_ list
+        for (unsigned int iKey = 0; iKey < keysDown_.size(); iKey++)
+        {
+            if (keysDown_[iKey].key == (KeyCode::Enum)e.key)
+            {
+                keysDown_.erase(keysDown_.begin() + iKey);
+                break;
+            }
+        }
+
+        // update modifiers
+        if(e.key == OIS::KC_RMENU    || e.key == OIS::KC_LMENU)
+            keyboardModifiers_ &= ~KeyboardModifier::Alt;   // alt key
+        if(e.key == OIS::KC_RCONTROL || e.key == OIS::KC_LCONTROL)
+            keyboardModifiers_ &= ~KeyboardModifier::Ctrl;  // ctrl key
+        if(e.key == OIS::KC_RSHIFT   || e.key == OIS::KC_LSHIFT)
+            keyboardModifiers_ &= ~KeyboardModifier::Shift; // shift key
+
+        activeStatesTop_[Keyboard]->keyReleased(KeyEvent(e, keyboardModifiers_));
+
+        return true;
+    }
+
+
+    // ###### Mouse Events ######
+
+    /**
+    @brief
+        Event handler for the mouseMoved Event.
+    @param e
+        Event information
+    */
+    bool InputManager::mouseMoved(const OIS::MouseEvent &e)
+    {
+        // check for actual moved event
+        if (e.state.X.rel != 0 || e.state.Y.rel != 0)
+        {
+            activeStatesTop_[Mouse]->mouseMoved(IntVector2(e.state.X.abs, e.state.Y.abs),
+                    IntVector2(e.state.X.rel, e.state.Y.rel), IntVector2(e.state.width, e.state.height));
+        }
+
+        // check for mouse scrolled event
+        if (e.state.Z.rel != 0)
+        {
+            activeStatesTop_[Mouse]->mouseScrolled(e.state.Z.abs, e.state.Z.rel);
+        }
+
+        return true;
+    }
+
+    /**
+    @brief
+        Event handler for the mousePressed Event.
+    @param e
+        Event information
+    @param id
+        The ID of the mouse button
+    */
+    bool InputManager::mousePressed(const OIS::MouseEvent &e, OIS::MouseButtonID id)
+    {
+        // check whether the button already is in the list (can happen when focus was lost)
+        unsigned int iButton = 0;
+        while (iButton < mouseButtonsDown_.size() && mouseButtonsDown_[iButton] != (MouseButton::Enum)id)
+            iButton++;
+        if (iButton == mouseButtonsDown_.size())
+            mouseButtonsDown_.push_back((MouseButton::Enum)id);
+
+        activeStatesTop_[Mouse]->mouseButtonPressed((MouseButton::Enum)id);
+
+        return true;
+    }
+
+    /**
+    @brief
+        Event handler for the mouseReleased Event.
+    @param e
+        Event information
+    @param id
+        The ID of the mouse button
+    */
+    bool InputManager::mouseReleased(const OIS::MouseEvent &e, OIS::MouseButtonID id)
+    {
+        // remove the button from the keysDown_ list
+        for (unsigned int iButton = 0; iButton < mouseButtonsDown_.size(); iButton++)
+        {
+            if (mouseButtonsDown_[iButton] == (MouseButton::Enum)id)
+            {
+                mouseButtonsDown_.erase(mouseButtonsDown_.begin() + iButton);
+                break;
+            }
+        }
+
+        activeStatesTop_[Mouse]->mouseButtonReleased((MouseButton::Enum)id);
+
+        return true;
+    }
+
+
+    // ###### Joy Stick Events ######
+
+    inline unsigned int InputManager::_getJoystick(const OIS::JoyStickEvent& arg)
+    {
+        // use the device to identify which one called the method
+        OIS::JoyStick* joyStick = (OIS::JoyStick*)arg.device;
+        unsigned int iJoyStick = 0;
+        while (joySticks_[iJoyStick] != joyStick)
+            iJoyStick++;
+        // assert: Unknown joystick fired an event.
+        assert(iJoyStick != joySticksSize_);
+        return iJoyStick;
+    }
+
+    bool InputManager::buttonPressed(const OIS::JoyStickEvent &arg, int button)
+    {
+        unsigned int iJoyStick = _getJoystick(arg);
+
+        // check whether the button already is in the list (can happen when focus was lost)
+        std::vector<int>& buttonsDown = joyStickButtonsDown_[iJoyStick];
+        unsigned int iButton = 0;
+        while (iButton < buttonsDown.size() && buttonsDown[iButton] != button)
+            iButton++;
+        if (iButton == buttonsDown.size())
+            buttonsDown.push_back(button);
+
+        activeStatesTop_[2 + iJoyStick]->joyStickButtonPressed(iJoyStick, button);
+
+        return true;
+    }
+
+    bool InputManager::buttonReleased(const OIS::JoyStickEvent &arg, int button)
+    {
+        unsigned int iJoyStick = _getJoystick(arg);
+
+        // remove the button from the joyStickButtonsDown_ list
+        std::vector<int>& buttonsDown = joyStickButtonsDown_[iJoyStick];
+        for (unsigned int iButton = 0; iButton < buttonsDown.size(); iButton++)
+        {
+            if (buttonsDown[iButton] == button)
+            {
+                buttonsDown.erase(buttonsDown.begin() + iButton);
+                break;
+            }
+        }
+
+        activeStatesTop_[2 + iJoyStick]->joyStickButtonReleased(iJoyStick, button);
+
+        return true;
+    }
+
+    void InputManager::_fireAxis(unsigned int iJoyStick, int axis, int value)
+    {
+        if (bCalibrating_)
+        {
+            if (value > marginalsMax_[axis])
+                marginalsMax_[axis] = value;
+            if (value < marginalsMin_[axis])
+                marginalsMin_[axis] = value;
+        }
+        else
+        {
+            float fValue = value - joySticksCalibration_[iJoyStick].zeroStates[axis];
+            if (fValue > 0.0f)
+                fValue *= joySticksCalibration_[iJoyStick].positiveCoeff[axis];
+            else
+                fValue *= joySticksCalibration_[iJoyStick].negativeCoeff[axis];
+
+            activeStatesTop_[2 + iJoyStick]->joyStickAxisMoved(iJoyStick, axis, fValue);
+        }
+    }
+
+    bool InputManager::axisMoved(const OIS::JoyStickEvent &arg, int axis)
+    {
+        unsigned int iJoyStick = _getJoystick(arg);
+
+        // keep in mind that the first 8 axes are reserved for the sliders
+        _fireAxis(iJoyStick, axis + 8, arg.state.mAxes[axis].abs);
+
+        return true;
+    }
+
+    bool InputManager::sliderMoved(const OIS::JoyStickEvent &arg, int id)
+    {
+        unsigned int iJoyStick = _getJoystick(arg);
+
+        if (sliderStates_[iJoyStick].sliderStates[id].x != arg.state.mSliders[id].abX)
+            _fireAxis(iJoyStick, id * 2, arg.state.mSliders[id].abX);
+        else if (sliderStates_[iJoyStick].sliderStates[id].y != arg.state.mSliders[id].abY)
+            _fireAxis(iJoyStick, id * 2 + 1, arg.state.mSliders[id].abY);
+
+        return true;
+    }
+
+    bool InputManager::povMoved(const OIS::JoyStickEvent &arg, int id)
+    {
+        unsigned int iJoyStick = _getJoystick(arg);
+
+        // translate the POV into 8 simple buttons
+        int lastState = povStates_[iJoyStick][id];
+        if (lastState & OIS::Pov::North)
+            buttonReleased(arg, 32 + id * 4 + 0);
+        if (lastState & OIS::Pov::South)
+            buttonReleased(arg, 32 + id * 4 + 1);
+        if (lastState & OIS::Pov::East)
+            buttonReleased(arg, 32 + id * 4 + 2);
+        if (lastState & OIS::Pov::West)
+            buttonReleased(arg, 32 + id * 4 + 3);
+
+        povStates_[iJoyStick].povStates[id] = arg.state.mPOV[id].direction;
+
+        int currentState = povStates_[iJoyStick][id];
+        if (currentState & OIS::Pov::North)
+            buttonPressed(arg, 32 + id * 4 + 0);
+        if (currentState & OIS::Pov::South)
+            buttonPressed(arg, 32 + id * 4 + 1);
+        if (currentState & OIS::Pov::East)
+            buttonPressed(arg, 32 + id * 4 + 2);
+        if (currentState & OIS::Pov::West)
+            buttonPressed(arg, 32 + id * 4 + 3);
+
+        return true;
+    }
+
+
+    // ############################################################
+    // #####            Static Interface Methods              #####
+    // ##########                                        ##########
+    // ############################################################
+
+    std::string InputManager::bindingCommmandString_s = "";
+
+    bool InputManager::initialise(const size_t windowHnd, int windowWidth, int windowHeight,
         bool createKeyboard, bool createMouse, bool createJoySticks)
-  {
-    if (state_ == IS_UNINIT)
-    {
-      CCOUT(3) << "Initialising Input System..." << std::endl;
-      CCOUT(ORX_DEBUG) << "Initialising OIS components..." << std::endl;
-
-      OIS::ParamList paramList;
-      std::ostringstream windowHndStr;
-
-      // Fill parameter list
-      windowHndStr << (unsigned int)windowHnd;
-      paramList.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
-      //paramList.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_NONEXCLUSIVE")));
-      //paramList.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_FOREGROUND")));
-//#if defined OIS_LINUX_PLATFORM
-//      paramList.insert(std::make_pair(std::string("XAutoRepeatOn"), std::string("true")));
-//#endif
-
-      try
-      {
-        inputSystem_ = OIS::InputManager::createInputSystem(paramList);
-        CCOUT(ORX_DEBUG) << "Created OIS input system" << std::endl;
-      }
-      catch (OIS::Exception ex)
-      {
-        CCOUT(ORX_ERROR) << "Error: Failed creating an OIS input system."
-            << "OIS message: \"" << ex.eText << "\"" << std::endl;
-        inputSystem_ = 0;
+    {
+        return _getInstance()._initialise(windowHnd, windowWidth, windowHeight,
+            createKeyboard, createMouse, createJoySticks);
+    }
+
+    bool InputManager::initialiseKeyboard()
+    {
+        return _getInstance()._initialiseKeyboard();
+    }
+
+    bool InputManager::initialiseMouse()
+    {
+        return _getInstance()._initialiseMouse();
+    }
+
+    bool InputManager::initialiseJoySticks()
+    {
+        return _getInstance()._initialiseJoySticks();
+    }
+
+    int InputManager::numberOfKeyboards()
+    {
+        if (_getInstance().keyboard_ != 0)
+            return 1;
+        else
+            return 0;
+    }
+
+    int InputManager::numberOfMice()
+    {
+        if (_getInstance().mouse_ != 0)
+            return 1;
+        else
+            return 0;
+    }
+
+    int InputManager::numberOfJoySticks()
+    {
+        return _getInstance().joySticksSize_;
+    }
+
+    /*bool InputManager::isKeyDown(KeyCode::Enum key)
+    {
+    if (_getInstance().keyboard_)
+        return _getInstance().keyboard_->isKeyDown((OIS::KeyCode)key);
+    else
         return false;
-      }
-
-      if (createKeyboard)
-        _initialiseKeyboard();
-
-      if (createMouse)
-        _initialiseMouse();
-
-      if (createJoySticks)
-        _initialiseJoySticks();
-
-      // Set mouse/joystick region
-      if (mouse_)
-      {
-        setWindowExtents(windowWidth, windowHeight);
-      }
-
-      state_ = IS_NONE;
-      CCOUT(ORX_DEBUG) << "Initialising OIS components done." << std::endl;
-
-      // InputManager holds the input buffer --> create one and add it.
-      buffer_ = new InputBuffer();
-      addKeyHandler(buffer_, "buffer");
-      Shell::getInstance().setInputBuffer(buffer_);
-
-      keyBinder_ = new KeyBinder();
-      keyBinder_->loadBindings();
-      addKeyHandler(keyBinder_, "keybinder");
-      addMouseHandler(keyBinder_, "keybinder");
-      addJoyStickHandler(keyBinder_, "keybinder");
-
-      keyDetector_ = new KeyDetector();
-      keyDetector_->loadBindings();
-      addKeyHandler(keyDetector_, "keydetector");
-      addMouseHandler(keyDetector_, "keydetector");
-      addJoyStickHandler(keyDetector_, "keydetector");
-
-      calibratorCallback_ = new CalibratorCallback();
-      addKeyHandler(calibratorCallback_, "calibratorcallback");
-
-      setConfigValues();
-
-      CCOUT(ORX_DEBUG) << "Initialising complete." << std::endl;
-    }
+    }*/
+
+    /*bool InputManager::isModifierDown(KeyboardModifier::Enum modifier)
+    {
+    if (_getInstance().keyboard_)
+        return isModifierDown(modifier);
     else
-    {
-      CCOUT(ORX_WARNING) << "Warning: OIS compoments already initialised, skipping" << std::endl;
-    }
-    return true;
-  }
-
-  /**
-    @brief Creates a keyboard and sets the event handler.
-    @return False if keyboard stays uninitialised, true otherwise.
-  */
-  bool InputManager::_initialiseKeyboard()
-  {
-    if (keyboard_ != 0)
-    {
-      CCOUT(2) << "Warning: Keyboard already initialised, skipping." << std::endl;
-      return true;
-    }
-    try
-    {
-      if (inputSystem_->getNumberOfDevices(OIS::OISKeyboard) > 0)
-      {
-        keyboard_ = (OIS::Keyboard*)inputSystem_->createInputObject(OIS::OISKeyboard, true);
-        // register our listener in OIS.
-        keyboard_->setEventCallback(this);
-        // note: OIS will not detect keys that have already been down when the keyboard was created.
-        CCOUT(ORX_DEBUG) << "Created OIS keyboard" << std::endl;
-        return true;
-      }
-      else
-      {
-        CCOUT(ORX_WARNING) << "Warning: No keyboard found!" << std::endl;
         return false;
-      }
-    }
-    catch (OIS::Exception ex)
-    {
-      // TODO: Test this output regarding formatting
-      CCOUT(ORX_WARNING) << "Warning: Failed to create an OIS keyboard\n"
-          << "OIS error message: \"" << ex.eText << "\"" << std::endl;
-      keyboard_ = 0;
-      return false;
-    }
-  }
-
-  /**
-    @brief Creates a mouse and sets the event handler.
-    @return False if mouse stays uninitialised, true otherwise.
-  */
-  bool InputManager::_initialiseMouse()
-  {
-    if (mouse_ != 0)
-    {
-      CCOUT(2) << "Warning: Mouse already initialised, skipping." << std::endl;
-      return true;
-    }
-    try
-    {
-      if (inputSystem_->getNumberOfDevices(OIS::OISMouse) > 0)
-      {
-        mouse_ = static_cast<OIS::Mouse*>(inputSystem_->createInputObject(OIS::OISMouse, true));
-        // register our listener in OIS.
-        mouse_->setEventCallback(this);
-        CCOUT(ORX_DEBUG) << "Created OIS mouse" << std::endl;
-        return true;
-      }
-      else
-      {
-        CCOUT(ORX_WARNING) << "Warning: No mouse found!" << std::endl;
+    }*/
+
+    /*const MouseState InputManager::getMouseState()
+    {
+    if (_getInstance().mouse_)
+        return _getInstance().mouse_->getMouseState();
+    else
+        return MouseState();
+    }*/
+
+    /*const JoyStickState InputManager::getJoyStickState(unsigned int ID)
+    {
+    if (ID < _getInstance().joySticksSize_)
+        return JoyStickState(_getInstance().joySticks_[ID]->getJoyStickState(), ID);
+    else
+        return JoyStickState();
+    }*/
+
+    void InputManager::destroy()
+    {
+        _getInstance()._destroy();
+    }
+
+    void InputManager::destroyKeyboard()
+    {
+        return _getInstance()._destroyKeyboard();
+    }
+
+    void InputManager::destroyMouse()
+    {
+        return _getInstance()._destroyMouse();
+    }
+
+    void InputManager::destroyJoySticks()
+    {
+        return _getInstance()._destroyJoySticks();
+    }
+
+
+    /**
+    @brief
+        Adjusts the mouse window metrics.
+        This method has to be called every time the size of the window changes.
+    @param width
+        The new width of the render window
+    @param^height
+        The new height of the render window
+    */
+    void InputManager::setWindowExtents(const int width, const int height)
+    {
+        if (_getInstance().mouse_)
+        {
+            // Set mouse region (if window resizes, we should alter this to reflect as well)
+            const OIS::MouseState &mouseState = _getInstance().mouse_->getMouseState();
+            mouseState.width  = width;
+            mouseState.height = height;
+        }
+    }
+
+    void InputManager::storeKeyStroke(const std::string& name)
+    {
+        requestLeaveState("detector");
+        COUT(0) << "Binding string \"" << bindingCommmandString_s << "\" on key '" << name << "'" << std::endl;
+        CommandExecutor::execute("config KeyBinder " + name + " " + bindingCommmandString_s, false);
+    }
+
+    void InputManager::keyBind(const std::string& command)
+    {
+        bindingCommmandString_s = command;
+        requestEnterState("detector");
+        COUT(0) << "Press any button/key or move a mouse/joystick axis" << std::endl;
+    }
+
+    void InputManager::calibrate()
+    {
+        requestEnterState("calibrator");
+    }
+
+    void InputManager::tick(float dt)
+    {
+        _getInstance()._tick(dt);
+    }
+
+    // ###### InputStates ######
+
+    /**
+    @brief
+        Adds a new key handler.
+    @param handler
+        Pointer to the handler object.
+    @param name
+        Unique name of the handler.
+    @return
+        True if added, false if name already existed.
+    */
+    bool InputManager::_configureInputState(InputState* state, const std::string& name, int priority)
+    {
+        if (name == "")
+            return false;
+        if (_getInstance().inputStatesByName_.find(name) == _getInstance().inputStatesByName_.end())
+        {
+            if (_getInstance().inputStatesByPriority_.find(priority)
+                == _getInstance().inputStatesByPriority_.end())
+            {
+                _getInstance().inputStatesByName_[name] = state;
+                _getInstance().inputStatesByPriority_[priority] = state;
+                state->setNumOfJoySticks(numberOfJoySticks());
+                state->setName(name);
+                state->setPriority(priority);
+                return true;
+            }
+            else
+            {
+                COUT(2) << "Warning: Could not add an InputState with the same priority '"
+                    << priority << "'." << std::endl;
+                return false;
+            }
+        }
+        else
+        {
+            COUT(2) << "Warning: Could not add an InputState with the same name '" << name << "'." << std::endl;
+            return false;
+        }
+    }
+
+    SimpleInputState* InputManager::createSimpleInputState(const std::string &name, int priority)
+    {
+        SimpleInputState* state = new SimpleInputState();
+        if (_getInstance()._configureInputState(state, name, priority))
+            return state;
+        else
+        {
+            delete state;
+            return 0;
+        }
+    }
+
+    ExtendedInputState* InputManager::createExtendedInputState(const std::string &name, int priority)
+    {
+        ExtendedInputState* state = new ExtendedInputState();
+        if (_getInstance()._configureInputState(state, name, priority))
+            return state;
+        else
+        {
+            delete state;
+            return 0;
+        }
+    }
+
+    /**
+    @brief
+        Removes a Key handler from the list.
+    @param name
+        Unique name of the handler.
+    @return
+        True if removal was successful, false if name was not found.
+    */
+    bool InputManager::destroyState(const std::string& name)
+    {
+        if (name == "empty" || name == "calibrator" || name == "detector")
+        {
+            COUT(2) << "InputManager: Removing the '" << name << "' state is not allowed!" << std::endl;
+            return false;
+        }
+        std::map<std::string, InputState*>::iterator it = _getInstance().inputStatesByName_.find(name);
+        if (it != _getInstance().inputStatesByName_.end())
+        {
+            _getInstance()._destroyState((*it).second);
+            return true;
+        }
         return false;
-      }
-    }
-    catch (OIS::Exception ex)
-    {
-      CCOUT(ORX_WARNING) << "Warning: Failed to create an OIS mouse\n"
-          << "OIS error message: \"" << ex.eText << "\"" << std::endl;
-      mouse_ = 0;
-      return false;
-    }
-  }
-
-  /**
-    @brief Creates all joy sticks and sets the event handler.
-    @return False joy stick stay uninitialised, true otherwise.
-  */
-  bool InputManager::_initialiseJoySticks()
-  {
-    if (joySticksSize_ > 0)
-    {
-      CCOUT(2) << "Warning: Joy sticks already initialised, skipping." << std::endl;
-      return true;
-    }
-    bool success = false;
-    if (inputSystem_->getNumberOfDevices(OIS::OISJoyStick) > 0)
-    {
-      for (int i = 0; i < inputSystem_->getNumberOfDevices(OIS::OISJoyStick); i++)
-      {
-        try
-        {
-          OIS::JoyStick* stig = static_cast<OIS::JoyStick*>(inputSystem_->createInputObject(OIS::OISJoyStick, true));
-          joySticks_.push_back(stig);
-          // register our listener in OIS.
-          stig->setEventCallback(this);
-          CCOUT(ORX_DEBUG) << "Created OIS joy stick with ID " << stig->getID() << std::endl;
-          success = true;
-        }
-        catch (OIS::Exception ex)
-        {
-          CCOUT(ORX_WARNING) << "Warning: Failed to create OIS joy number" << i << "\n"
-              << "OIS error message: \"" << ex.eText << "\"" << std::endl;
-        }
-      }
-    }
-    else
-    {
-      CCOUT(ORX_WARNING) << "Warning: Joy stick support requested, but no joy stick was found" << std::endl;
-      return false;
-    }
-    joySticksSize_ = joySticks_.size();
-    activeJoyStickHandlers_.resize(joySticksSize_);
-    joyStickButtonsDown_.resize(joySticksSize_);
-    povStates_.resize(joySticksSize_);
-    sliderStates_.resize(joySticksSize_);
-    joySticksCalibration_.resize(joySticksSize_);
-    for (unsigned int iJoyStick = 0; iJoyStick < joySticksSize_; iJoyStick++)
-    {
-      // reset the calibration with default values
-      for (unsigned int i = 0; i < 24; i++)
-      {
-        joySticksCalibration_[iJoyStick].negativeCoeff[i] = 1.0f/32767.0f;
-        joySticksCalibration_[iJoyStick].positiveCoeff[i] = 1.0f/32768.0f;
-        joySticksCalibration_[iJoyStick].zeroStates[i] = 0;
-      }
-    }
-    return success;
-  }
-
-  /**
-    @brief Sets the configurable values. Use keybindings.ini as file..
-  */
-  void InputManager::setConfigValues()
-  {
-    if (joySticksSize_)
-    {
-      std::vector<MultiTypeMath> coeffPos;
-      std::vector<MultiTypeMath> coeffNeg;
-      std::vector<MultiTypeMath> zero;
-      coeffPos.resize(24);
-      coeffNeg.resize(24);
-      zero.resize(24);
-      for (unsigned int i = 0; i < 24; i++)
-      {
-        coeffPos[i] =  1.0f/32767.0f;
-        coeffNeg[i] =  1.0f/32768.0f;
-        zero[i]     =  0;
-      }
-
-      ConfigValueContainer* cont = getIdentifier()->getConfigValueContainer("CoeffPos");
-      if (!cont)
-      {
-          cont = new ConfigValueContainer(CFT_Keybindings, getIdentifier(), "CoeffPos", coeffPos);
-          getIdentifier()->addConfigValueContainer("CoeffPos", cont);
-      }
-      cont->getValue(&coeffPos);
-
-      cont = getIdentifier()->getConfigValueContainer("CoeffNeg");
-      if (!cont)
-      {
-          cont = new ConfigValueContainer(CFT_Keybindings, getIdentifier(), "CoeffNeg", coeffNeg);
-          getIdentifier()->addConfigValueContainer("CoeffNeg", cont);
-      }
-      cont->getValue(&coeffNeg);
-
-      cont = getIdentifier()->getConfigValueContainer("Zero");
-      if (!cont)
-      {
-          cont = new ConfigValueContainer(CFT_Keybindings, getIdentifier(), "Zero", zero);
-          getIdentifier()->addConfigValueContainer("Zero", cont);
-      }
-      cont->getValue(&zero);
-
-      // copy values to our own variables
-      for (unsigned int i = 0; i < 24; i++)
-      {
-        joySticksCalibration_[0].positiveCoeff[i] = coeffPos[i];
-        joySticksCalibration_[0].negativeCoeff[i] = coeffNeg[i];
-        joySticksCalibration_[0].zeroStates[i]    = zero[i];
-      }
-    }
-  }
-
-  /**
-    @brief Destroys all the created input devices and sets the InputManager to construction state.
-  */
-  void InputManager::_destroy()
-  {
-    if (state_ != IS_UNINIT)
-    {
-      CCOUT(ORX_DEBUG) << "Destroying ..." << std::endl;
-
-      if (buffer_)
-        delete buffer_;
-
-      if (keyBinder_)
-        delete keyBinder_;
-
-      if (keyDetector_)
-        delete keyDetector_;
-
-      if (calibratorCallback_)
-        delete calibratorCallback_;
-
-      keyHandlers_.clear();
-      mouseHandlers_.clear();
-      joyStickHandlers_.clear();
-
-      _destroyKeyboard();
-      _destroyMouse();
-      _destroyJoySticks();
-
-      activeHandlers_.clear();
-
-      // inputSystem_ can never be 0, or else the code is mistaken
-      OIS::InputManager::destroyInputSystem(inputSystem_);
-      inputSystem_ = 0;
-
-      state_ = IS_UNINIT;
-      CCOUT(ORX_DEBUG) << "Destroying done." << std::endl;
-    }
-  }
-
-  /**
-    @brief Destroys the keyboard and sets it to 0.
-  */
-  void InputManager::_destroyKeyboard()
-  {
-    if (keyboard_)
-      // inputSystem_ can never be 0, or else the code is mistaken
-      inputSystem_->destroyInputObject(keyboard_);
-    keyboard_ = 0;
-    activeKeyHandlers_.clear();
-    keysDown_.clear();
-    CCOUT(ORX_DEBUG) << "Keyboard destroyed." << std::endl;
-  }
-
-  /**
-    @brief Destroys the mouse and sets it to 0.
-  */
-  void InputManager::_destroyMouse()
-  {
-    if (mouse_)
-      // inputSystem_ can never be 0, or else the code is mistaken
-      inputSystem_->destroyInputObject(mouse_);
-    mouse_ = 0;
-    activeMouseHandlers_.clear();
-    mouseButtonsDown_.clear();
-    CCOUT(ORX_DEBUG) << "Mouse destroyed." << std::endl;
-  }
-
-  /**
-    @brief Destroys all the joy sticks and resizes the lists to 0.
-  */
-  void InputManager::_destroyJoySticks()
-  {
-    if (joySticksSize_ > 0)
-    {
-      // note: inputSystem_ can never be 0, or else the code is mistaken
-      for (unsigned int i = 0; i < joySticksSize_; i++)
-        if (joySticks_[i] != 0)
-          inputSystem_->destroyInputObject(joySticks_[i]);
-
-      joySticks_.clear();
-      joySticksSize_ = 0;
-      activeJoyStickHandlers_.clear();
-      joyStickButtonsDown_.clear();
-      povStates_.clear();
-      sliderStates_.clear();
-      joySticksCalibration_.clear();
-    }
-    CCOUT(ORX_DEBUG) << "Joy sticks destroyed." << std::endl;
-  }
-
-  void InputManager::_saveState()
-  {
-    savedHandlers_.activeHandlers_ = activeHandlers_;
-    savedHandlers_.activeJoyStickHandlers_ = activeJoyStickHandlers_;
-    savedHandlers_.activeKeyHandlers_ = activeKeyHandlers_;
-    savedHandlers_.activeMouseHandlers_ = activeMouseHandlers_;
-  }
-
-  void InputManager::_restoreState()
-  {
-    activeHandlers_ = savedHandlers_.activeHandlers_;
-    activeJoyStickHandlers_ = savedHandlers_.activeJoyStickHandlers_;
-    activeKeyHandlers_ = savedHandlers_.activeKeyHandlers_;
-    activeMouseHandlers_ = savedHandlers_.activeMouseHandlers_;
-  }
-
-  void InputManager::_updateTickables()
-  {
-    // we can use a map to have a list of unique pointers (an object can implement all 3 handlers)
-    std::map<InputTickable*, HandlerState> tempSet;
-    for (unsigned int iHandler = 0; iHandler < activeKeyHandlers_.size(); iHandler++)
-      tempSet[activeKeyHandlers_[iHandler]].joyStick = true;
-    for (unsigned int iHandler = 0; iHandler < activeMouseHandlers_.size(); iHandler++)
-      tempSet[activeMouseHandlers_[iHandler]].mouse = true;
-    for (unsigned int iJoyStick  = 0; iJoyStick < joySticksSize_; iJoyStick++)
-      for (unsigned int iHandler = 0; iHandler  < activeJoyStickHandlers_[iJoyStick].size(); iHandler++)
-        tempSet[activeJoyStickHandlers_[iJoyStick][iHandler]].joyStick = true;
-
-    // copy the content of the map back to the actual vector
-    activeHandlers_.clear();
-    for (std::map<InputTickable*, HandlerState>::const_iterator itHandler = tempSet.begin();
-        itHandler != tempSet.end(); itHandler++)
-      activeHandlers_.push_back(std::pair<InputTickable*, HandlerState>((*itHandler).first, (*itHandler).second));
-  }
-
-
-  // #################################
-  // ### Private Interface Methods ###
-  // #################################
-  // #################################
-
-  /**
-    @brief Updates the InputManager. Tick is called by Orxonox.
-    @param dt Delta time
-  */
-  void InputManager::_tick(float dt)
-  {
-    if (state_ == IS_UNINIT)
-      return;
-
-    if (state_ != stateRequest_)
-    {
-      InputState sr = stateRequest_;
-      switch (sr)
-      {
-      case IS_NORMAL:
-        activeKeyHandlers_.clear();
-        activeMouseHandlers_.clear();
-        for (unsigned int i = 0; i < joySticksSize_; i++)
-          activeJoyStickHandlers_[i].clear();
-
-        // normal play mode
-        // note: we assume that the handlers exist since otherwise, something's wrong anyway.
-        enableKeyHandler("keybinder");
-        enableMouseHandler("keybinder");
-        enableJoyStickHandler("keybinder", 0);
-        stateRequest_ = IS_NORMAL;
-        state_ = IS_NORMAL;
-        break;
-
-      case IS_GUI:
-        state_ = IS_GUI;
-        break;
-
-      case IS_CONSOLE:
-        activeKeyHandlers_.clear();
-        activeMouseHandlers_.clear();
-        for (unsigned int i = 0; i < joySticksSize_; i++)
-          activeJoyStickHandlers_[i].clear();
-
-        enableMouseHandler("keybinder");
-        enableJoyStickHandler("keybinder", 0);
-        enableKeyHandler("buffer");
-        stateRequest_ = IS_CONSOLE;
-        state_ = IS_CONSOLE;
-        break;
-
-      case IS_DETECT:
-        savedState_ = state_;
-        _saveState();
-
-        activeKeyHandlers_.clear();
-        activeMouseHandlers_.clear();
-        for (unsigned int i = 0; i < joySticksSize_; i++)
-          activeJoyStickHandlers_[i].clear();
-
-        enableKeyHandler("keydetector");
-        enableMouseHandler("keydetector");
-        enableJoyStickHandler("keydetector", 0);
-
-        stateRequest_ = IS_DETECT;
-        state_ = IS_DETECT;
-        break;
-
-      case IS_NODETECT:
-        _restoreState();
-        keysDown_.clear();
-        mouseButtonsDown_.clear();
-        for (unsigned int i = 0; i < joySticksSize_; i++)
-          joyStickButtonsDown_[i].clear();
-        state_ = IS_NODETECT;
-        stateRequest_ = savedState_;
-        break;
-
-      case IS_CALIBRATE:
-        if (joySticksSize_)
-        {
-          savedState_ = _getSingleton().state_;
-          for (unsigned int i = 0; i < 24; i++)
-          {
-            marginalsMax_[i] = INT_MIN;
-            marginalsMin_[i] = INT_MAX;
-          }
-          COUT(0) << "Move all joy stick axes in all directions a few times. "
-            << "Then put all axes in zero state and hit enter." << std::endl;
-
-          savedState_ = state_;
-          _saveState();
-
-          activeKeyHandlers_.clear();
-          activeMouseHandlers_.clear();
-          for (unsigned int i = 0; i < joySticksSize_; i++)
-            activeJoyStickHandlers_[i].clear();
-
-          enableKeyHandler("calibratorcallback");
-          stateRequest_ = IS_CALIBRATE;
-          state_ = IS_CALIBRATE;
-        }
+    }
+
+    /**
+    @brief
+        Returns the pointer to a handler.
+    @param name
+        Unique name of the handler.
+    @return
+        Pointer to the instance, 0 if name was not found.
+    */
+    InputState* InputManager::getState(const std::string& name)
+    {
+        std::map<std::string, InputState*>::iterator it = _getInstance().inputStatesByName_.find(name);
+        if (it != _getInstance().inputStatesByName_.end())
+            return (*it).second;
         else
-        {
-          COUT(3) << "Connot calibrate, no joy stick found!" << std::endl;
-          stateRequest_ = state_;
-        }
-        break;
-
-      case IS_NOCALIBRATE:
-        _completeCalibration();
-        _restoreState();
-        keyBinder_->resetJoyStickAxes();
-        state_ = IS_NOCALIBRATE;
-        stateRequest_ = savedState_;
-        break;
-
-      case IS_NONE:
-        activeKeyHandlers_.clear();
-        activeMouseHandlers_.clear();
-        for (unsigned int i = 0; i < joySticksSize_; i++)
-          activeJoyStickHandlers_[i].clear();
-        state_ = IS_NONE;
-
-      default:
-        break;
-      }
-    }
-
-    // Capture all the input. This calls the event handlers in InputManager.
-    if (mouse_)
-      mouse_->capture();
-    if (keyboard_)
-      keyboard_->capture();
-    for (unsigned  int i = 0; i < joySticksSize_; i++)
-      joySticks_[i]->capture();
-
-    if (state_ != IS_CALIBRATE)
-    {
-      // call all the handlers for the held key events
-      for (unsigned int iKey = 0; iKey < keysDown_.size(); iKey++)
-        for (unsigned int iHandler = 0; iHandler < activeKeyHandlers_.size(); iHandler++)
-          activeKeyHandlers_[iHandler]->keyHeld(KeyEvent(keysDown_[iKey], keyboardModifiers_));
-
-      // call all the handlers for the held mouse button events
-      for (unsigned int iButton = 0; iButton < mouseButtonsDown_.size(); iButton++)
-        for (unsigned int iHandler = 0; iHandler < activeMouseHandlers_.size(); iHandler++)
-          activeMouseHandlers_[iHandler]->mouseButtonHeld(mouseButtonsDown_[iButton]);
-
-      // call all the handlers for the held joy stick button events
-      for (unsigned int iJoyStick  = 0; iJoyStick < joySticksSize_; iJoyStick++)
-        for (unsigned int iButton   = 0; iButton   < joyStickButtonsDown_[iJoyStick].size(); iButton++)
-          for (unsigned int iHandler = 0; iHandler  < activeJoyStickHandlers_[iJoyStick].size(); iHandler++)
-            activeJoyStickHandlers_[iJoyStick][iHandler]->joyStickButtonHeld(iJoyStick, joyStickButtonsDown_[iJoyStick][iButton]);
-    }
-
-    // call the ticks for the handlers (need to be treated specially)
-    for (unsigned int iHandler = 0; iHandler < activeHandlers_.size(); iHandler++)
-      activeHandlers_[iHandler].first->tickInput(dt, activeHandlers_[iHandler].second);
-  }
-
-  void InputManager::_completeCalibration()
-  {
-    for (unsigned int i = 0; i < 24; i++)
-    {
-      // positive coefficient
-      if (marginalsMax_[i] == INT_MIN)
-        marginalsMax_[i] =  32767;
-      // coefficients
-      if (marginalsMax_[i] - joySticksCalibration_[0].zeroStates[i])
-        joySticksCalibration_[0].positiveCoeff[i] =  1.0f/(marginalsMax_[i] - joySticksCalibration_[0].zeroStates[i]);
-      else
-        joySticksCalibration_[0].positiveCoeff[i] =  1.0f;
-
-      // config value
-      ConfigValueContainer* cont = getIdentifier()->getConfigValueContainer("CoeffPos");
-      assert(cont);
-      cont->set(i, joySticksCalibration_[0].positiveCoeff[i]);
-
-      // negative coefficient
-      if (marginalsMin_[i] == INT_MAX)
-        marginalsMin_[i] = -32768;
-      // coefficients
-      if (marginalsMin_[i] - joySticksCalibration_[0].zeroStates[i])
-        joySticksCalibration_[0].negativeCoeff[i] = -1.0f/(marginalsMin_[i] - joySticksCalibration_[0].zeroStates[i]);
-      else
-        joySticksCalibration_[0].negativeCoeff[i] =  1.0f;
-      // config value
-      cont = getIdentifier()->getConfigValueContainer("CoeffNeg");
-      assert(cont);
-      cont->set(i, joySticksCalibration_[0].negativeCoeff[i]);
-
-      // zero states
-      if (i < 8)
-      {
-        if (!(i & 1))
-          joySticksCalibration_[0].zeroStates[i] = joySticks_[0]->getJoyStickState().mSliders[i/2].abX;
-        else
-          joySticksCalibration_[0].zeroStates[i] = joySticks_[0]->getJoyStickState().mSliders[i/2].abY;
-      }
-      else
-      {
-        if (i - 8 < joySticks_[0]->getJoyStickState().mAxes.size())
-          joySticksCalibration_[0].zeroStates[i] = joySticks_[0]->getJoyStickState().mAxes[i - 8].abs;
-        else
-          joySticksCalibration_[0].zeroStates[i] = 0;
-      }
-      // config value
-      cont = getIdentifier()->getConfigValueContainer("Zero");
-      assert(cont);
-      cont->set(i, joySticksCalibration_[0].zeroStates[i]);
-    }
-  }
-
-  // ###### Key Events ######
-
-  /**
-    @brief Event handler for the keyPressed Event.
-    @param e Event information
-  */
-  bool InputManager::keyPressed(const OIS::KeyEvent &e)
-  {
-    // check whether the key already is in the list (can happen when focus was lost)
-    unsigned int iKey = 0;
-    while (iKey < keysDown_.size() && keysDown_[iKey].key != (KeyCode::Enum)e.key)
-      iKey++;
-    if (iKey == keysDown_.size())
-      keysDown_.push_back(Key(e));
-
-    // update modifiers
-    if(e.key == OIS::KC_RMENU    || e.key == OIS::KC_LMENU)
-      keyboardModifiers_ |= KeyboardModifier::Alt;   // alt key
-    if(e.key == OIS::KC_RCONTROL || e.key == OIS::KC_LCONTROL)
-      keyboardModifiers_ |= KeyboardModifier::Ctrl;  // ctrl key
-    if(e.key == OIS::KC_RSHIFT   || e.key == OIS::KC_LSHIFT)
-      keyboardModifiers_ |= KeyboardModifier::Shift; // shift key
-
-    for (unsigned int i = 0; i < activeKeyHandlers_.size(); i++)
-      activeKeyHandlers_[i]->keyPressed(KeyEvent(e, keyboardModifiers_));
-
-    return true;
-  }
-
-  /**
-    @brief Event handler for the keyReleased Event.
-    @param e Event information
-  */
-  bool InputManager::keyReleased(const OIS::KeyEvent &e)
-  {
-    // remove the key from the keysDown_ list
-    for (unsigned int iKey = 0; iKey < keysDown_.size(); iKey++)
-    {
-      if (keysDown_[iKey].key == (KeyCode::Enum)e.key)
-      {
-        keysDown_.erase(keysDown_.begin() + iKey);
-        break;
-      }
-    }
-
-    // update modifiers
-    if(e.key == OIS::KC_RMENU    || e.key == OIS::KC_LMENU)
-      keyboardModifiers_ &= ~KeyboardModifier::Alt;   // alt key
-    if(e.key == OIS::KC_RCONTROL || e.key == OIS::KC_LCONTROL)
-      keyboardModifiers_ &= ~KeyboardModifier::Ctrl;  // ctrl key
-    if(e.key == OIS::KC_RSHIFT   || e.key == OIS::KC_LSHIFT)
-      keyboardModifiers_ &= ~KeyboardModifier::Shift; // shift key
-
-    for (unsigned int i = 0; i < activeKeyHandlers_.size(); i++)
-      activeKeyHandlers_[i]->keyReleased(KeyEvent(e, keyboardModifiers_));
-
-    return true;
-  }
-
-
-  // ###### Mouse Events ######
-
-  /**
-    @brief Event handler for the mouseMoved Event.
-    @param e Event information
-  */
-  bool InputManager::mouseMoved(const OIS::MouseEvent &e)
-  {
-    // check for actual moved event
-    if (e.state.X.rel != 0 || e.state.Y.rel != 0)
-    {
-      for (unsigned int i = 0; i < activeMouseHandlers_.size(); i++)
-        activeMouseHandlers_[i]->mouseMoved(IntVector2(e.state.X.abs, e.state.Y.abs),
-            IntVector2(e.state.X.rel, e.state.Y.rel), IntVector2(e.state.width, e.state.height));
-    }
-
-    // check for mouse scrolled event
-    if (e.state.Z.rel != 0)
-    {
-      for (unsigned int i = 0; i < activeMouseHandlers_.size(); i++)
-        activeMouseHandlers_[i]->mouseScrolled(e.state.Z.abs, e.state.Z.rel);
-    }
-
-    return true;
-  }
-
-  /**
-    @brief Event handler for the mousePressed Event.
-    @param e Event information
-    @param id The ID of the mouse button
-  */
-  bool InputManager::mousePressed(const OIS::MouseEvent &e, OIS::MouseButtonID id)
-  {
-    // check whether the button already is in the list (can happen when focus was lost)
-    unsigned int iButton = 0;
-    while (iButton < mouseButtonsDown_.size() && mouseButtonsDown_[iButton] != (MouseButton::Enum)id)
-      iButton++;
-    if (iButton == mouseButtonsDown_.size())
-      mouseButtonsDown_.push_back((MouseButton::Enum)id);
-
-    for (unsigned int i = 0; i < activeMouseHandlers_.size(); i++)
-      activeMouseHandlers_[i]->mouseButtonPressed((MouseButton::Enum)id);
-
-    return true;
-  }
-
-  /**
-    @brief Event handler for the mouseReleased Event.
-    @param e Event information
-    @param id The ID of the mouse button
-  */
-  bool InputManager::mouseReleased(const OIS::MouseEvent &e, OIS::MouseButtonID id)
-  {
-    // remove the button from the keysDown_ list
-    for (unsigned int iButton = 0; iButton < mouseButtonsDown_.size(); iButton++)
-    {
-      if (mouseButtonsDown_[iButton] == (MouseButton::Enum)id)
-      {
-        mouseButtonsDown_.erase(mouseButtonsDown_.begin() + iButton);
-        break;
-      }
-    }
-
-    for (unsigned int i = 0; i < activeMouseHandlers_.size(); i++)
-      activeMouseHandlers_[i]->mouseButtonReleased((MouseButton::Enum)id);
-
-    return true;
-  }
-
-
-  // ###### Joy Stick Events ######
-
-  inline unsigned int InputManager::_getJoystick(const OIS::JoyStickEvent& arg)
-  {
-    // use the device to identify which one called the method
-    OIS::JoyStick* joyStick = (OIS::JoyStick*)arg.device;
-    unsigned int iJoyStick = 0;
-    while (joySticks_[iJoyStick] != joyStick)
-    {
-      iJoyStick++;
-      if (iJoyStick == joySticksSize_)
-      {
-        CCOUT(3) << "Unknown joystick fired an event. This means there is a bug somewhere! Aborting." << std::endl;
-        abort();
-      }
-    }
-    return iJoyStick;
-  }
-
-  bool InputManager::buttonPressed(const OIS::JoyStickEvent &arg, int button)
-  {
-    unsigned int iJoyStick = _getJoystick(arg);
-
-    // check whether the button already is in the list (can happen when focus was lost)
-    std::vector<int>& buttonsDown = joyStickButtonsDown_[iJoyStick];
-    unsigned int iButton = 0;
-    while (iButton < buttonsDown.size() && buttonsDown[iButton] != button)
-      iButton++;
-    if (iButton == buttonsDown.size())
-      buttonsDown.push_back(button);
-
-    for (unsigned int iHandler = 0; iHandler < activeJoyStickHandlers_[iJoyStick].size(); iHandler++)
-      activeJoyStickHandlers_[iJoyStick][iHandler]->joyStickButtonPressed(iJoyStick, button);
-
-    return true;
-  }
-
-  bool InputManager::buttonReleased(const OIS::JoyStickEvent &arg, int button)
-  {
-    unsigned int iJoyStick = _getJoystick(arg);
-
-    // remove the button from the joyStickButtonsDown_ list
-    std::vector<int>& buttonsDown = joyStickButtonsDown_[iJoyStick];
-    for (unsigned int iButton = 0; iButton < buttonsDown.size(); iButton++)
-    {
-      if (buttonsDown[iButton] == button)
-      {
-        buttonsDown.erase(buttonsDown.begin() + iButton);
-        break;
-      }
-    }
-
-    for (unsigned int iHandler = 0; iHandler < activeJoyStickHandlers_[iJoyStick].size(); iHandler++)
-      activeJoyStickHandlers_[iJoyStick][iHandler]->joyStickButtonReleased(iJoyStick, button);
-
-    return true;
-  }
-
-  void InputManager::_fireAxis(unsigned int iJoyStick, int axis, int value)
-  {
-    if (state_ == IS_CALIBRATE)
-    {
-      if (value > marginalsMax_[axis])
-        marginalsMax_[axis] = value;
-      if (value < marginalsMin_[axis])
-        marginalsMin_[axis] = value;
-    }
-    else
-    {
-      float fValue = value - joySticksCalibration_[iJoyStick].zeroStates[axis];
-      if (fValue > 0.0f)
-        fValue *= joySticksCalibration_[iJoyStick].positiveCoeff[axis];
-      else
-        fValue *= joySticksCalibration_[iJoyStick].negativeCoeff[axis];
-
-      for (unsigned int iHandler = 0; iHandler < activeJoyStickHandlers_[iJoyStick].size(); iHandler++)
-        activeJoyStickHandlers_[iJoyStick][iHandler]->joyStickAxisMoved(iJoyStick, axis, fValue);
-    }
-  }
-
-  bool InputManager::axisMoved(const OIS::JoyStickEvent &arg, int axis)
-  {
-    //if (arg.state.mAxes[axis].abs > 10000 || arg.state.mAxes[axis].abs < -10000)
-    //{ CCOUT(3) << "axis " << axis << " moved" << arg.state.mAxes[axis].abs << std::endl;}
-
-    unsigned int iJoyStick = _getJoystick(arg);
-
-    // keep in mind that the first 8 axes are reserved for the sliders
-    _fireAxis(iJoyStick, axis + 8, arg.state.mAxes[axis].abs);
-
-    return true;
-  }
-
-  bool InputManager::sliderMoved(const OIS::JoyStickEvent &arg, int id)
-  {
-    //if (arg.state.mSliders[id].abX > 10000 || arg.state.mSliders[id].abX < -10000)
-    //{CCOUT(3) << "slider " << id << " moved" << arg.state.mSliders[id].abX << std::endl;}
-    //CCOUT(3) << arg.state.mSliders[id].abX << "\t |" << arg.state.mSliders[id].abY << std::endl;
-
-    unsigned int iJoyStick = _getJoystick(arg);
-
-    if (sliderStates_[iJoyStick].sliderStates[id].x != arg.state.mSliders[id].abX)
-      _fireAxis(iJoyStick, id * 2, arg.state.mSliders[id].abX);
-    else if (sliderStates_[iJoyStick].sliderStates[id].y != arg.state.mSliders[id].abY)
-      _fireAxis(iJoyStick, id * 2 + 1, arg.state.mSliders[id].abY);
-
-    return true;
-  }
-
-  bool InputManager::povMoved(const OIS::JoyStickEvent &arg, int id)
-  {
-    unsigned int iJoyStick = _getJoystick(arg);
-
-    // translate the POV into 8 simple buttons
-    int lastState = povStates_[iJoyStick][id];
-    if (lastState & OIS::Pov::North)
-      buttonReleased(arg, 32 + id * 4 + 0);
-    if (lastState & OIS::Pov::South)
-      buttonReleased(arg, 32 + id * 4 + 1);
-    if (lastState & OIS::Pov::East)
-      buttonReleased(arg, 32 + id * 4 + 2);
-    if (lastState & OIS::Pov::West)
-      buttonReleased(arg, 32 + id * 4 + 3);
-
-    povStates_[iJoyStick].povStates[id] = arg.state.mPOV[id].direction;
-
-    int currentState = povStates_[iJoyStick][id];
-    if (currentState & OIS::Pov::North)
-      buttonPressed(arg, 32 + id * 4 + 0);
-    if (currentState & OIS::Pov::South)
-      buttonPressed(arg, 32 + id * 4 + 1);
-    if (currentState & OIS::Pov::East)
-      buttonPressed(arg, 32 + id * 4 + 2);
-    if (currentState & OIS::Pov::West)
-      buttonPressed(arg, 32 + id * 4 + 3);
-
-    return true;
-  }
-
-  /*bool InputManager::vector3Moved(const OIS::JoyStickEvent &arg, int id)
-  {
-    unsigned int iJoyStick = _getJoystick(arg);
-
-    for (unsigned int iHandler = 0; iHandler < activeJoyStickHandlers_[iJoyStick].size(); iHandler++)
-      activeJoyStickHandlers_[iJoyStick][iHandler]->joyStickVector3Moved(JoyStickState(arg.state, iJoyStick), id);
-
-    return true;
-  }*/
-
-
-  // ################################
-  // ### Static Interface Methods ###
-  // ################################
-  // ################################
-
-  std::string InputManager::bindingCommmandString_s = "";
-
-  bool InputManager::initialise(const size_t windowHnd, int windowWidth, int windowHeight,
-    bool createKeyboard, bool createMouse, bool createJoySticks)
-  {
-    return _getSingleton()._initialise(windowHnd, windowWidth, windowHeight,
-          createKeyboard, createMouse, createJoySticks);
-  }
-
-  bool InputManager::initialiseKeyboard()
-  {
-    return _getSingleton()._initialiseKeyboard();
-  }
-
-  bool InputManager::initialiseMouse()
-  {
-    return _getSingleton()._initialiseMouse();
-  }
-
-  bool InputManager::initialiseJoySticks()
-  {
-    return _getSingleton()._initialiseJoySticks();
-  }
-
-  int InputManager::numberOfKeyboards()
-  {
-    if (_getSingleton().keyboard_ != 0)
-      return 1;
-    else
-      return 0;
-  }
-
-  int InputManager::numberOfMice()
-  {
-    if (_getSingleton().mouse_ != 0)
-      return 1;
-    else
-      return 0;
-  }
-
-  int InputManager::numberOfJoySticks()
-  {
-    return _getSingleton().joySticksSize_;
-  }
-
-  /*bool InputManager::isKeyDown(KeyCode::Enum key)
-  {
-    if (_getSingleton().keyboard_)
-      return _getSingleton().keyboard_->isKeyDown((OIS::KeyCode)key);
-    else
-      return false;
-  }*/
-
-  /*bool InputManager::isModifierDown(KeyboardModifier::Enum modifier)
-  {
-    if (_getSingleton().keyboard_)
-      return isModifierDown(modifier);
-    else
-      return false;
-  }*/
-
-  /*const MouseState InputManager::getMouseState()
-  {
-    if (_getSingleton().mouse_)
-      return _getSingleton().mouse_->getMouseState();
-    else
-      return MouseState();
-  }*/
-
-  /*const JoyStickState InputManager::getJoyStickState(unsigned int ID)
-  {
-    if (ID < _getSingleton().joySticksSize_)
-      return JoyStickState(_getSingleton().joySticks_[ID]->getJoyStickState(), ID);
-    else
-      return JoyStickState();
-  }*/
-
-  void InputManager::destroy()
-  {
-    _getSingleton()._destroy();
-  }
-
-  void InputManager::destroyKeyboard()
-  {
-    return _getSingleton()._destroyKeyboard();
-  }
-
-  void InputManager::destroyMouse()
-  {
-    return _getSingleton()._destroyMouse();
-  }
-
-  void InputManager::destroyJoySticks()
-  {
-    return _getSingleton()._destroyJoySticks();
-  }
-
-
-  /**
-    @brief Adjusts the mouse window metrics.
-    This method has to be called every time the size of the window changes.
-    @param width The new width of the render window
-    @param height the new height of the render window
-  */
-  void InputManager::setWindowExtents(const int width, const int height)
-  {
-    if (_getSingleton().mouse_)
-    {
-      // Set mouse region (if window resizes, we should alter this to reflect as well)
-      const OIS::MouseState &mouseState = _getSingleton().mouse_->getMouseState();
-      mouseState.width  = width;
-      mouseState.height = height;
-    }
-  }
-
-  /**
-    @brief Sets the input mode to either GUI, inGame or Buffer
-    @param mode The new input mode
-    @remark Only has an affect if the mode actually changes
-  */
-  void InputManager::setInputState(const InputState state)
-  {
-    _getSingleton().stateRequest_ = state;
-  }
-
-  /**
-    @brief Returns the current input handling method
-    @return The current input mode.
-  */
-  InputManager::InputState InputManager::getInputState()
-  {
-    return _getSingleton().state_;
-  }
-
-  void InputManager::storeKeyStroke(const std::string& name)
-  {
-    setInputState(IS_NODETECT);
-    COUT(0) << "Binding string \"" << bindingCommmandString_s << "\" on key '" << name << "'" << std::endl;
-    CommandExecutor::execute("config KeyBinder " + name + " " + bindingCommmandString_s, false);
-  }
-
-  void InputManager::keyBind(const std::string& command)
-  {
-    bindingCommmandString_s = command;
-    setInputState(IS_DETECT);
-    COUT(0) << "Press any button/key or move a mouse/joystick axis" << std::endl;
-  }
-
-  void InputManager::calibrate()
-  {
-    _getSingleton().setInputState(IS_CALIBRATE);
-  }
-
-  void InputManager::tick(float dt)
-  {
-    _getSingleton()._tick(dt);
-  }
-
-  // ###### KeyHandler ######
-
-  /**
-    @brief Adds a new key handler.
-    @param handler Pointer to the handler object.
-    @param name Unique name of the handler.
-    @return True if added, false if name already existed.
-  */
-  bool InputManager::addKeyHandler(KeyHandler* handler, const std::string& name)
-  {
-    if (!handler)
-      return false;
-    if (_getSingleton().keyHandlers_.find(name) == _getSingleton().keyHandlers_.end())
-    {
-      _getSingleton().keyHandlers_[name] = handler;
-      return true;
-    }
-    else
-      return false;
-  }
-
-  /**
-    @brief Removes a Key handler from the list.
-    @param name Unique name of the handler.
-    @return True if removal was successful, false if name was not found.
-  */
-  bool InputManager::removeKeyHandler(const std::string &name)
-  {
-    disableKeyHandler(name);
-    std::map<std::string, KeyHandler*>::iterator it = _getSingleton().keyHandlers_.find(name);
-    if (it != _getSingleton().keyHandlers_.end())
-    {
-      _getSingleton().keyHandlers_.erase(it);
-      return true;
-    }
-    else
-      return false;
-  }
-
-  /**
-    @brief Returns the pointer to a handler.
-    @param name Unique name of the handler.
-    @return Pointer to the instance, 0 if name was not found.
-  */
-  KeyHandler* InputManager::getKeyHandler(const std::string& name)
-  {
-    std::map<std::string, KeyHandler*>::iterator it = _getSingleton().keyHandlers_.find(name);
-    if (it != _getSingleton().keyHandlers_.end())
-    {
-      return (*it).second;
-    }
-    else
-      return 0;
-  }
-
-  /**
-    @brief Enables a specific key handler that has already been added.
-    @param name Unique name of the handler.
-    @return False if name was not found, true otherwise.
-  */
-  bool InputManager::enableKeyHandler(const std::string& name)
-  {
-    // get pointer from the map with all stored handlers
-    std::map<std::string, KeyHandler*>::const_iterator mapIt = _getSingleton().keyHandlers_.find(name);
-    if (mapIt == _getSingleton().keyHandlers_.end())
-      return false;
-    // see whether the handler already is in the list
-    for (std::vector<KeyHandler*>::iterator it = _getSingleton().activeKeyHandlers_.begin();
-          it != _getSingleton().activeKeyHandlers_.end(); it++)
-    {
-      if ((*it) == (*mapIt).second)
-      {
-        return true;
-      }
-    }
-    _getSingleton().activeKeyHandlers_.push_back((*mapIt).second);
-    _getSingleton().stateRequest_ = IS_CUSTOM;
-    _getSingleton()._updateTickables();
-    return true;
-  }
-
-  /**
-    @brief Disables a specific key handler.
-    @param name Unique name of the handler.
-    @return False if name was not found, true otherwise.
-  */
-  bool InputManager::disableKeyHandler(const std::string &name)
-  {
-    // get pointer from the map with all stored handlers
-    std::map<std::string, KeyHandler*>::const_iterator mapIt = _getSingleton().keyHandlers_.find(name);
-    if (mapIt == _getSingleton().keyHandlers_.end())
-      return false;
-    // look for the handler in the list
-    for (std::vector<KeyHandler*>::iterator it = _getSingleton().activeKeyHandlers_.begin();
-          it != _getSingleton().activeKeyHandlers_.end(); it++)
-    {
-      if ((*it) == (*mapIt).second)
-      {
-        _getSingleton().activeKeyHandlers_.erase(it);
-        _getSingleton().stateRequest_ = IS_CUSTOM;
-        _getSingleton()._updateTickables();
-        return true;
-      }
-    }
-    return true;
-  }
-
-  /**
-    @brief Checks whether a key handler is active
-    @param name Unique name of the handler.
-    @return False if key handler is not active or doesn't exist, true otherwise.
-  */
-  bool InputManager::isKeyHandlerActive(const std::string& name)
-  {
-    // get pointer from the map with all stored handlers
-    std::map<std::string, KeyHandler*>::const_iterator mapIt = _getSingleton().keyHandlers_.find(name);
-    if (mapIt == _getSingleton().keyHandlers_.end())
-      return false;
-    // see whether the handler already is in the list
-    for (std::vector<KeyHandler*>::iterator it = _getSingleton().activeKeyHandlers_.begin();
-          it != _getSingleton().activeKeyHandlers_.end(); it++)
-    {
-      if ((*it) == (*mapIt).second)
-        return true;
-    }
-    return false;
-  }
-
-
-  // ###### MouseHandler ######
-  /**
-    @brief Adds a new mouse handler.
-    @param handler Pointer to the handler object.
-    @param name Unique name of the handler.
-    @return True if added, false if name already existed.
-  */
-  bool InputManager::addMouseHandler(MouseHandler* handler, const std::string& name)
-  {
-    if (!handler)
-      return false;
-    if (_getSingleton().mouseHandlers_.find(name) == _getSingleton().mouseHandlers_.end())
-    {
-      _getSingleton().mouseHandlers_[name] = handler;
-      return true;
-    }
-    else
-      return false;
-  }
-
-  /**
-    @brief Removes a Mouse handler from the list.
-    @param name Unique name of the handler.
-    @return True if removal was successful, false if name was not found.
-  */
-  bool InputManager::removeMouseHandler(const std::string &name)
-  {
-    disableMouseHandler(name);
-    std::map<std::string, MouseHandler*>::iterator it = _getSingleton().mouseHandlers_.find(name);
-    if (it != _getSingleton().mouseHandlers_.end())
-    {
-      _getSingleton().mouseHandlers_.erase(it);
-      return true;
-    }
-    else
-      return false;
-  }
-
-  /**
-    @brief Returns the pointer to a handler.
-    @param name Unique name of the handler.
-    @return Pointer to the instance, 0 if name was not found.
-  */
-  MouseHandler* InputManager::getMouseHandler(const std::string& name)
-  {
-    std::map<std::string, MouseHandler*>::iterator it = _getSingleton().mouseHandlers_.find(name);
-    if (it != _getSingleton().mouseHandlers_.end())
-    {
-      return (*it).second;
-    }
-    else
-      return 0;
-  }
-
-  /**
-    @brief Enables a specific mouse handler that has already been added.
-    @param name Unique name of the handler.
-    @return False if name was not found, true otherwise.
-  */
-  bool InputManager::enableMouseHandler(const std::string& name)
-  {
-    // get pointer from the map with all stored handlers
-    std::map<std::string, MouseHandler*>::const_iterator mapIt = _getSingleton().mouseHandlers_.find(name);
-    if (mapIt == _getSingleton().mouseHandlers_.end())
-      return false;
-    // see whether the handler already is in the list
-    for (std::vector<MouseHandler*>::iterator it = _getSingleton().activeMouseHandlers_.begin();
-          it != _getSingleton().activeMouseHandlers_.end(); it++)
-    {
-      if ((*it) == (*mapIt).second)
-      {
-        return true;
-      }
-    }
-    _getSingleton().activeMouseHandlers_.push_back((*mapIt).second);
-    _getSingleton().stateRequest_ = IS_CUSTOM;
-    _getSingleton()._updateTickables();
-    return true;
-  }
-
-  /**
-    @brief Disables a specific mouse handler.
-    @param name Unique name of the handler.
-    @return False if name was not found, true otherwise.
-  */
-  bool InputManager::disableMouseHandler(const std::string &name)
-  {
-    // get pointer from the map with all stored handlers
-    std::map<std::string, MouseHandler*>::const_iterator mapIt = _getSingleton().mouseHandlers_.find(name);
-    if (mapIt == _getSingleton().mouseHandlers_.end())
-      return false;
-    // look for the handler in the list
-    for (std::vector<MouseHandler*>::iterator it = _getSingleton().activeMouseHandlers_.begin();
-          it != _getSingleton().activeMouseHandlers_.end(); it++)
-    {
-      if ((*it) == (*mapIt).second)
-      {
-        _getSingleton().activeMouseHandlers_.erase(it);
-        _getSingleton().stateRequest_ = IS_CUSTOM;
-        _getSingleton()._updateTickables();
-        return true;
-      }
-    }
-    return true;
-  }
-
-  /**
-    @brief Checks whether a mouse handler is active
-    @param name Unique name of the handler.
-    @return False if key handler is not active or doesn't exist, true otherwise.
-  */
-  bool InputManager::isMouseHandlerActive(const std::string& name)
-  {
-    // get pointer from the map with all stored handlers
-    std::map<std::string, MouseHandler*>::const_iterator mapIt = _getSingleton().mouseHandlers_.find(name);
-    if (mapIt == _getSingleton().mouseHandlers_.end())
-      return false;
-    // see whether the handler already is in the list
-    for (std::vector<MouseHandler*>::iterator it = _getSingleton().activeMouseHandlers_.begin();
-          it != _getSingleton().activeMouseHandlers_.end(); it++)
-    {
-      if ((*it) == (*mapIt).second)
-        return true;
-    }
-    return false;
-  }
-
-
-  // ###### JoyStickHandler ######
-
-  /**
-    @brief Adds a new joy stick handler.
-    @param handler Pointer to the handler object.
-    @param name Unique name of the handler.
-    @return True if added, false if name already existed.
-  */
-  bool InputManager::addJoyStickHandler(JoyStickHandler* handler, const std::string& name)
-  {
-    if (!handler)
-      return false;
-    if (_getSingleton().joyStickHandlers_.find(name) == _getSingleton().joyStickHandlers_.end())
-    {
-      _getSingleton().joyStickHandlers_[name] = handler;
-      return true;
-    }
-    else
-      return false;
-  }
-
-  /**
-    @brief Removes a JoyStick handler from the list.
-    @param name Unique name of the handler.
-    @return True if removal was successful, false if name was not found.
-  */
-  bool InputManager::removeJoyStickHandler(const std::string &name)
-  {
-    for (std::vector<OIS::JoyStick*>::iterator itstick = _getSingleton().joySticks_.begin();
-          itstick != _getSingleton().joySticks_.end(); itstick++)
-      disableJoyStickHandler(name, itstick - _getSingleton().joySticks_.begin());
-
-    std::map<std::string, JoyStickHandler*>::iterator it = _getSingleton().joyStickHandlers_.find(name);
-    if (it != _getSingleton().joyStickHandlers_.end())
-    {
-      _getSingleton().joyStickHandlers_.erase(it);
-      return true;
-    }
-    else
-      return false;
-  }
-
-  /**
-    @brief Returns the pointer to a handler.
-    @param name Unique name of the handler.
-    @return Pointer to the instance, 0 if name was not found.
-  */
-  JoyStickHandler* InputManager::getJoyStickHandler(const std::string& name)
-  {
-    std::map<std::string, JoyStickHandler*>::iterator it = _getSingleton().joyStickHandlers_.find(name);
-    if (it != _getSingleton().joyStickHandlers_.end())
-    {
-      return (*it).second;
-    }
-    else
-      return 0;
-  }
-
-  /**
-    @brief Enables a specific joy stick handler that has already been added.
-    @param name Unique name of the handler.
-    @return False if name or id was not found, true otherwise.
-  */
-  bool InputManager::enableJoyStickHandler(const std::string& name, unsigned int ID)
-  {
-    // get handler pointer from the map with all stored handlers
-    std::map<std::string, JoyStickHandler*>::const_iterator handlerIt = _getSingleton().joyStickHandlers_.find(name);
-    if (handlerIt == _getSingleton().joyStickHandlers_.end())
-      return false;
-
-    // check for existence of the ID
-    if (ID >= _getSingleton().joySticksSize_)
-      return false;
-
-    // see whether the handler already is in the list
-    for (std::vector<JoyStickHandler*>::iterator it = _getSingleton().activeJoyStickHandlers_[ID].begin();
-          it != _getSingleton().activeJoyStickHandlers_[ID].end(); it++)
-    {
-      if ((*it) == (*handlerIt).second)
-      {
-        return true;
-      }
-    }
-    _getSingleton().activeJoyStickHandlers_[ID].push_back((*handlerIt).second);
-    _getSingleton().stateRequest_ = IS_CUSTOM;
-    _getSingleton()._updateTickables();
-    return true;
-  }
-
-  /**
-    @brief Disables a specific joy stick handler.
-    @param name Unique name of the handler.
-    @return False if name or id was not found, true otherwise.
-  */
-  bool InputManager::disableJoyStickHandler(const std::string &name, unsigned int ID)
-  {
-    // get handler pointer from the map with all stored handlers
-    std::map<std::string, JoyStickHandler*>::const_iterator handlerIt = _getSingleton().joyStickHandlers_.find(name);
-    if (handlerIt == _getSingleton().joyStickHandlers_.end())
-      return false;
-
-    // check for existence of the ID
-    if (ID >= _getSingleton().joySticksSize_)
-      return false;
-
-    // look for the handler in the list
-    for (std::vector<JoyStickHandler*>::iterator it = _getSingleton().activeJoyStickHandlers_[ID].begin();
-          it != _getSingleton().activeJoyStickHandlers_[ID].end(); it++)
-    {
-      if ((*it) == (*handlerIt).second)
-      {
-        _getSingleton().activeJoyStickHandlers_[ID].erase(it);
-        _getSingleton().stateRequest_ = IS_CUSTOM;
-        _getSingleton()._updateTickables();
-        return true;
-      }
-    }
-    return true;
-  }
-
-  /**
-    @brief Checks whether a joy stick handler is active
-    @param name Unique name of the handler.
-    @return False if key handler is not active or doesn't exist, true otherwise.
-  */
-  bool InputManager::isJoyStickHandlerActive(const std::string& name, unsigned int ID)
-  {
-    // get handler pointer from the map with all stored handlers
-    std::map<std::string, JoyStickHandler*>::const_iterator handlerIt = _getSingleton().joyStickHandlers_.find(name);
-    if (handlerIt == _getSingleton().joyStickHandlers_.end())
-      return false;
-
-    // check for existence of the ID
-    if (ID >= _getSingleton().joySticksSize_)
-      return false;
-
-    // see whether the handler already is in the list
-    for (std::vector<JoyStickHandler*>::iterator it = _getSingleton().activeJoyStickHandlers_[ID].begin();
-          it != _getSingleton().activeJoyStickHandlers_[ID].end(); it++)
-    {
-      if ((*it) == (*handlerIt).second)
-        return true;
-    }
-    return false;
-  }
-
+            return 0;
+    }
+
+    /**
+    @brief
+        Returns the current input handling method
+    @return
+        The current input mode.
+    */
+    InputState* InputManager::getCurrentState()
+    {
+        return (*_getInstance().activeStates_.rbegin()).second;
+    }
+
+    /**
+    @brief
+        Enables a specific key handler that has already been added.
+    @param name
+        Unique name of the handler.
+    @return
+        False if name was not found, true otherwise.
+    */
+    bool InputManager::requestEnterState(const std::string& name)
+    {
+        // get pointer from the map with all stored handlers
+        std::map<std::string, InputState*>::const_iterator it = _getInstance().inputStatesByName_.find(name);
+        if (it != _getInstance().inputStatesByName_.end())
+        {
+            _getInstance().stateEnterRequests_.push_back((*it).second);
+            return true;
+        }
+        return false;
+    }
+
+    bool InputManager::requestLeaveState(const std::string& name)
+    {
+        // get pointer from the map with all stored handlers
+        std::map<std::string, InputState*>::const_iterator it = _getInstance().inputStatesByName_.find(name);
+        if (it != _getInstance().inputStatesByName_.end())
+        {
+            _getInstance().stateLeaveRequests_.push_back((*it).second);
+            return true;
+        }
+        return false;
+    }
 }
Index: code/branches/gui/src/core/input/InputManager.h
===================================================================
--- code/branches/gui/src/core/input/InputManager.h	(revision 1636)
+++ code/branches/gui/src/core/input/InputManager.h	(revision 1638)
@@ -28,8 +28,9 @@
 
 /**
- @file
- @brief Implementation of a little Input handler that distributes everything
-        coming from OIS.
- */
+@file
+@brief
+    Implementation of a little Input handler that distributes everything
+    coming from OIS.
+*/
 
 #ifndef _InputManager_H__
@@ -40,5 +41,5 @@
 #include <map>
 #include <vector>
-
+#include <stack>
 #include "util/Math.h"
 #include "core/OrxonoxClass.h"
@@ -47,213 +48,170 @@
 namespace orxonox
 {
-  /**
-  * Helper class to realise a vector<int[4]>
-  */
-  class POVStates
-  {
-  public:
-    int operator[](unsigned int index) { return povStates[index]; }
-    int povStates[4];
-  };
-
-  /**
-  * Helper class to realise a vector< {int[4], int[4]} >
-  */
-  class SliderStates
-  {
-  public:
-    IntVector2 sliderStates[4];
-  };
-
-  /**
-  * Struct for storing a custom input state
-  */
-  struct StoredState
-  {
-    std::vector<KeyHandler*>                    activeKeyHandlers_;
-    std::vector<MouseHandler*>                  activeMouseHandlers_;
-    std::vector<std::vector<JoyStickHandler*> > activeJoyStickHandlers_;
-    std::vector<std::pair<InputTickable*, HandlerState> > activeHandlers_;
-  };
-
-  struct JoyStickCalibration
-  {
-    int zeroStates[24];
-    float positiveCoeff[24];
-    float negativeCoeff[24];
-  };
-
-  /**
-    @brief Captures and distributes mouse and keyboard input.
-  */
-  class _CoreExport InputManager
+    /**
+    @brief
+        Helper class to realise a vector<int[4]>
+    */
+    class POVStates
+    {
+    public:
+        int operator[](unsigned int index) { return povStates[index]; }
+        int povStates[4];
+    };
+
+    /**
+    @brief
+        Helper class to realise a vector< {int[4], int[4]} >
+    */
+    class SliderStates
+    {
+    public:
+        IntVector2 sliderStates[4];
+    };
+
+    struct JoyStickCalibration
+    {
+        int zeroStates[24];
+        float positiveCoeff[24];
+        float negativeCoeff[24];
+    };
+
+    /**
+    @brief
+        Captures and distributes mouse and keyboard input.
+    */
+    class _CoreExport InputManager
         : public OrxonoxClass,
-          public OIS::KeyListener, public OIS::MouseListener, public OIS::JoyStickListener
-  {
-  public: // enumerations
-    /**
-      @brief Designates the way input is handled and redirected.
-    */
-    enum InputState
-    {
-      IS_UNINIT,    //!< InputManager has not yet been initialised.
-      IS_NONE,      //!< Input is discarded.
-      IS_NORMAL,    //!< Normal play state. Key and button bindings are active.
-      IS_GUI,       //!< All OIS input events are passed to CEGUI.
-      IS_CONSOLE,   //!< Keyboard input is redirected to the InputBuffer.
-      IS_DETECT,    //!< All the input additionally goes to the KeyDetector
-      IS_NODETECT,  //!< remove KeyDetector
-      IS_NOCALIBRATE,
-      IS_CALIBRATE,
-      IS_CUSTOM     //!< Any possible configuration.
-    };
-
-  public: // member functions
-    void setConfigValues();
-
-  public: // static functions
-    static bool initialise(const size_t windowHnd, int windowWidth, int windowHeight,
-          bool createKeyboard = true, bool createMouse = true, bool createJoySticks = false);
-    static bool initialiseKeyboard();
-    static bool initialiseMouse();
-    static bool initialiseJoySticks();
-    static int  numberOfKeyboards();
-    static int  numberOfMice();
-    static int  numberOfJoySticks();
-
-    static void destroy();
-    static void destroyKeyboard();
-    static void destroyMouse();
-    static void destroyJoySticks();
-
-    //static bool isModifierDown(KeyboardModifier::Enum modifier);
-    //static bool isKeyDown(KeyCode::Enum key);
-    //static const MouseState getMouseState();
-    //static const JoyStickState getJoyStickState(unsigned int ID);
-
-    static void setWindowExtents(const int width, const int height);
-
-    static void setInputState(const InputState state);
-    static InputState getInputState();
-
-    static void storeKeyStroke(const std::string& name);
-    static void keyBind(const std::string& command);
-
-    static void calibrate();
-
-    static void tick(float dt);
-
-    static bool addKeyHandler                 (KeyHandler* handler, const std::string& name);
-    static bool removeKeyHandler              (const std::string& name);
-    static KeyHandler* getKeyHandler          (const std::string& name);
-    static bool enableKeyHandler              (const std::string& name);
-    static bool disableKeyHandler             (const std::string& name);
-    static bool isKeyHandlerActive            (const std::string& name);
-
-    static bool addMouseHandler               (MouseHandler* handler, const std::string& name);
-    static bool removeMouseHandler            (const std::string& name);
-    static MouseHandler* getMouseHandler      (const std::string& name);
-    static bool enableMouseHandler            (const std::string& name);
-    static bool disableMouseHandler           (const std::string& name);
-    static bool isMouseHandlerActive          (const std::string& name);
-
-    static bool addJoyStickHandler            (JoyStickHandler* handler, const std::string& name);
-    static bool removeJoyStickHandler         (const std::string& name);
-    static JoyStickHandler* getJoyStickHandler(const std::string& name);
-    static bool enableJoyStickHandler         (const std::string& name, unsigned int id);
-    static bool disableJoyStickHandler        (const std::string& name, unsigned int id);
-    static bool isJoyStickHandlerActive       (const std::string& name, unsigned int id);
-
-  private: // functions
-    // don't mess with a Singleton
-    InputManager ();
-    InputManager (const InputManager&);
-    ~InputManager();
-
-    // Intenal methods
-    bool _initialise(const size_t, int, int, bool, bool, bool);
-    bool _initialiseKeyboard();
-    bool _initialiseMouse();
-    bool _initialiseJoySticks();
-
-    void _destroy();
-    void _destroyKeyboard();
-    void _destroyMouse();
-    void _destroyJoySticks();
-
-    void _updateTickables();
-
-    void _saveState();
-    void _restoreState();
-
-    void _completeCalibration();
-
-    void _fireAxis(unsigned int iJoyStick, int axis, int value);
-    unsigned int _getJoystick(const OIS::JoyStickEvent& arg);
-
-    void _tick(float dt);
-
-    // input events
-    bool mousePressed  (const OIS::MouseEvent    &arg, OIS::MouseButtonID id);
-    bool mouseReleased (const OIS::MouseEvent    &arg, OIS::MouseButtonID id);
-    bool mouseMoved    (const OIS::MouseEvent    &arg);
-    bool keyPressed    (const OIS::KeyEvent      &arg);
-    bool keyReleased   (const OIS::KeyEvent      &arg);
-    bool buttonPressed (const OIS::JoyStickEvent &arg, int button);
-    bool buttonReleased(const OIS::JoyStickEvent &arg, int button);
-    bool axisMoved     (const OIS::JoyStickEvent &arg, int axis);
-    bool sliderMoved   (const OIS::JoyStickEvent &arg, int id);
-    bool povMoved      (const OIS::JoyStickEvent &arg, int id);
-    //bool vector3Moved  (const OIS::JoyStickEvent &arg, int id);
-
-    static InputManager& _getSingleton();
-    static InputManager* _getSingletonPtr() { return &_getSingleton(); }
-
-  private: // variables
-    OIS::InputManager*                          inputSystem_;     //!< OIS input manager
-    OIS::Keyboard*                              keyboard_;        //!< OIS mouse
-    OIS::Mouse*                                 mouse_;           //!< OIS keyboard
-    std::vector<OIS::JoyStick*>                 joySticks_;       //!< OIS joy sticks
-    unsigned int                                joySticksSize_;
-
-    KeyBinder*                                  keyBinder_;       //!< KeyBinder instance
-    KeyDetector*                                keyDetector_;     //!< KeyDetector instance
-    InputBuffer*                                buffer_;          //!< InputBuffer instance
-    CalibratorCallback*                         calibratorCallback_;
-
-    InputState state_;
-    InputState stateRequest_;
-    InputState savedState_;
-    unsigned int keyboardModifiers_;
-    StoredState savedHandlers_;
-
-    // joystick calibration
-    //std::vector<int> marginalsMaxConfig_;
-    //std::vector<int> marginalsMinConfig_;
-    int marginalsMax_[24];
-    int marginalsMin_[24];
-    bool bCalibrated_;
-
-    //! Keeps track of the joy stick POV states
-    std::vector<POVStates>                      povStates_;
-    //! Keeps track of the possibly two slider axes
-    std::vector<SliderStates>                   sliderStates_;
-    std::vector<JoyStickCalibration>            joySticksCalibration_;
-
-    std::map<std::string, KeyHandler*>          keyHandlers_;
-    std::map<std::string, MouseHandler*>        mouseHandlers_;
-    std::map<std::string, JoyStickHandler*>     joyStickHandlers_;
-
-    std::vector<KeyHandler*>                    activeKeyHandlers_;
-    std::vector<MouseHandler*>                  activeMouseHandlers_;
-    std::vector<std::vector<JoyStickHandler*> > activeJoyStickHandlers_;
-    std::vector<std::pair<InputTickable*, HandlerState> > activeHandlers_;
-
-    std::vector<Key>                            keysDown_;
-    std::vector<MouseButton::Enum>              mouseButtonsDown_;
-    std::vector<std::vector<int> >              joyStickButtonsDown_;
-
-    static std::string                          bindingCommmandString_s;
-  };
+        public OIS::KeyListener, public OIS::MouseListener, public OIS::JoyStickListener
+    {
+        // --> setConfigValues is private
+        friend ClassIdentifier<InputManager>;
+
+    public: // static functions
+        static bool initialise(const size_t windowHnd, int windowWidth, int windowHeight,
+                               bool createKeyboard = true, bool createMouse = true, bool createJoySticks = false);
+        static bool initialiseKeyboard();
+        static bool initialiseMouse();
+        static bool initialiseJoySticks();
+        static int  numberOfKeyboards();
+        static int  numberOfMice();
+        static int  numberOfJoySticks();
+
+        static void destroy();
+        static void destroyKeyboard();
+        static void destroyMouse();
+        static void destroyJoySticks();
+
+        //static bool isModifierDown(KeyboardModifier::Enum modifier);
+        //static bool isKeyDown(KeyCode::Enum key);
+        //static const MouseState getMouseState();
+        //static const JoyStickState getJoyStickState(unsigned int ID);
+
+        static void setWindowExtents(const int width, const int height);
+
+        static void storeKeyStroke(const std::string& name);
+        static void keyBind(const std::string& command);
+
+        static void calibrate();
+
+        static void tick(float dt);
+
+        static SimpleInputState*   createSimpleInputState  (const std::string& name, int priority);
+        static ExtendedInputState* createExtendedInputState(const std::string& name, int priority);
+        static bool destroyState (const std::string& name);
+        //static bool removeState (const std::string& name);
+        static InputState* getState       (const std::string& name);
+        static InputState* getCurrentState();
+        static bool requestEnterState     (const std::string& name);
+        static bool requestLeaveState     (const std::string& name);
+
+    private: // functions
+        // don't mess with a Singleton
+        InputManager ();
+        InputManager (const InputManager&);
+        ~InputManager();
+
+        // Intenal methods
+        bool _initialise(const size_t, int, int, bool, bool, bool);
+        bool _initialiseKeyboard();
+        bool _initialiseMouse();
+        bool _initialiseJoySticks();
+        void _redimensionLists();
+
+        void _destroy();
+        void _destroyKeyboard();
+        void _destroyMouse();
+        void _destroyJoySticks();
+        void _destroyState(InputState* state);
+
+        void _completeCalibration();
+
+        void _fireAxis(unsigned int iJoyStick, int axis, int value);
+        unsigned int _getJoystick(const OIS::JoyStickEvent& arg);
+
+        void _tick(float dt);
+
+        void _updateActiveStates();
+        bool _configureInputState(InputState* state, const std::string& name, int priority);
+
+        // input events
+        bool mousePressed  (const OIS::MouseEvent    &arg, OIS::MouseButtonID id);
+        bool mouseReleased (const OIS::MouseEvent    &arg, OIS::MouseButtonID id);
+        bool mouseMoved    (const OIS::MouseEvent    &arg);
+        bool keyPressed    (const OIS::KeyEvent      &arg);
+        bool keyReleased   (const OIS::KeyEvent      &arg);
+        bool buttonPressed (const OIS::JoyStickEvent &arg, int button);
+        bool buttonReleased(const OIS::JoyStickEvent &arg, int button);
+        bool axisMoved     (const OIS::JoyStickEvent &arg, int axis);
+        bool sliderMoved   (const OIS::JoyStickEvent &arg, int id);
+        bool povMoved      (const OIS::JoyStickEvent &arg, int id);
+
+        void setConfigValues();
+
+        static InputManager& _getInstance();
+
+    private: // variables
+        OIS::InputManager*                          inputSystem_;     //!< OIS input manager
+        OIS::Keyboard*                              keyboard_;        //!< OIS mouse
+        OIS::Mouse*                                 mouse_;           //!< OIS keyboard
+        std::vector<OIS::JoyStick*>                 joySticks_;       //!< OIS joy sticks
+        unsigned int                                joySticksSize_;
+        unsigned int                                devicesNum_;
+
+        // some internally handled states
+        SimpleInputState*                                 stateDetector_;   //!< KeyDetector instance
+        SimpleInputState*                                 stateCalibrator_;
+        SimpleInputState*                                 stateEmpty_;
+
+        std::map<std::string, InputState*>          inputStatesByName_;
+        std::map<int, InputState*>                  inputStatesByPriority_;
+
+        std::vector<InputState*> stateEnterRequests_;                  //!< Request to enter a new state
+        std::vector<InputState*> stateLeaveRequests_;                    //!< Request to leave the current state
+
+        std::map<int, InputState*> activeStates_;
+        std::vector<InputState*>   activeStatesTop_;    //!< Current input states for joy stick events.
+        std::vector<InputState*>   activeStatesTicked_;    //!< Current input states for joy stick events.
+
+        // joystick calibration
+        //std::vector<int> marginalsMaxConfig_;
+        //std::vector<int> marginalsMinConfig_;
+        int marginalsMax_[24];
+        int marginalsMin_[24];
+        bool bCalibrated_;
+        bool bCalibrating_;
+
+        unsigned int keyboardModifiers_;           //!< Bit mask representing keyboard modifiers
+        //! Keeps track of the joy stick POV states
+        std::vector<POVStates>                      povStates_;
+        //! Keeps track of the possibly two slider axes
+        std::vector<SliderStates>                   sliderStates_;
+        std::vector<JoyStickCalibration>            joySticksCalibration_;
+
+        std::vector<Key>                            keysDown_;
+        std::vector<MouseButton::Enum>              mouseButtonsDown_;
+        std::vector<std::vector<int> >              joyStickButtonsDown_;
+
+        static std::string                          bindingCommmandString_s;
+    };
 
 }
Index: code/branches/gui/src/core/input/InputState.h
===================================================================
--- code/branches/gui/src/core/input/InputState.h	(revision 1638)
+++ code/branches/gui/src/core/input/InputState.h	(revision 1638)
@@ -0,0 +1,117 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief 
+*/
+
+#ifndef _InputState_H__
+#define _InputState_H__
+
+#include "core/CorePrereqs.h"
+
+#include <string>
+#include <vector>
+#include "core/Executor.h"
+#include "InputInterfaces.h"
+
+namespace orxonox
+{
+    class _CoreExport InputState
+    {
+        friend class InputManager;
+
+    public:
+        InputState() : priority_(0), executorOnEnter_(0), executorOnLeave_(0) { }
+        virtual ~InputState() { }
+
+        const std::string& getName() const { return name_; }
+        int getPriority()            const { return priority_; }
+
+        bool isInputDeviceEnabled(unsigned int device)
+        {
+            if (device < bInputDeviceEnabled_.size())
+                return bInputDeviceEnabled_[device];
+            else
+                return false;
+        }
+
+        virtual void onEnter() { if (executorOnEnter_) (*executorOnEnter_)(); }
+        virtual void onLeave() { if (executorOnLeave_) (*executorOnLeave_)(); }
+
+        virtual void registerOnEnter(Executor* executor)      { executorOnEnter_ = executor; }
+        virtual void unRegisterOnEnter()                      { executorOnEnter_ = 0; }
+        virtual void registerOnLeave(Executor* executor)      { executorOnLeave_ = executor; }
+        virtual void unRegisterOnLeave()                      { executorOnLeave_ = 0; }
+
+        virtual void tickInput(float dt, unsigned int device) = 0;
+        virtual void tickInput(float dt) = 0;
+
+        virtual void keyPressed (const KeyEvent& evt) = 0;
+        virtual void keyReleased(const KeyEvent& evt) = 0;
+        virtual void keyHeld    (const KeyEvent& evt) = 0;
+
+        virtual void mouseButtonPressed (MouseButton::Enum id) = 0;
+        virtual void mouseButtonReleased(MouseButton::Enum id) = 0;
+        virtual void mouseButtonHeld    (MouseButton::Enum id) = 0;
+        virtual void mouseMoved         (IntVector2 abs, IntVector2 rel, IntVector2 clippingSize) = 0;
+        virtual void mouseScrolled      (int abs, int rel) = 0;
+
+        virtual void joyStickButtonPressed (unsigned int joyStickID, unsigned int button) = 0;
+        virtual void joyStickButtonReleased(unsigned int joyStickID, unsigned int button) = 0;
+        virtual void joyStickButtonHeld    (unsigned int joyStickID, unsigned int button) = 0;
+        virtual void joyStickAxisMoved     (unsigned int joyStickID, unsigned int axis, float value) = 0;
+
+    protected:
+        virtual void numberOfJoySticksChanged(unsigned int n) = 0;
+        void setInputDeviceEnabled(unsigned int device, bool bEnabled)
+        {
+            if (device < bInputDeviceEnabled_.size())
+                bInputDeviceEnabled_[device] = bEnabled;
+        }
+
+    private:
+        void setNumOfJoySticks(unsigned int n)
+        {
+            bInputDeviceEnabled_.resize(n + 2);
+            numberOfJoySticksChanged(n);
+        }
+        void setName(const std::string& name)  { name_ = name; }
+        void setPriority(int priority)         { priority_ = priority; }
+
+        std::string                                 name_;
+        int                                         priority_;
+        std::vector<bool>                           bInputDeviceEnabled_;
+
+        Executor*                                   executorOnEnter_;
+        Executor*                                   executorOnLeave_;
+    };
+}
+
+#endif /* _InputState_H__ */
Index: code/branches/gui/src/core/input/KeyBinder.cc
===================================================================
--- code/branches/gui/src/core/input/KeyBinder.cc	(revision 1636)
+++ code/branches/gui/src/core/input/KeyBinder.cc	(revision 1638)
@@ -43,499 +43,526 @@
 namespace orxonox
 {
-  /**
-    @brief Constructor that does as little as necessary.
-  */
-  KeyBinder::KeyBinder() : deriveTime_(0.0f)
-  {
-    mouseRelative_[0] = 0;
-    mouseRelative_[1] = 0;
-    mousePosition_[0] = 0;
-    mousePosition_[1] = 0;
-
-    RegisterRootObject(KeyBinder);
-
-    // keys
-    std::string keyNames[] = {
-      "UNASSIGNED",
-      "ESCAPE",
-      "1", "2", "3", "4", "5", "6", "7", "8", "9", "0",
-      "MINUS", "EQUALS", "BACK", "TAB",
-      "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P",
-      "LBRACKET", "RBRACKET",
-      "RETURN", "LCONTROL",
-      "A", "S", "D", "F", "G", "H", "J", "K", "L",
-      "SEMICOLON", "APOSTROPHE", "GRAVE",
-      "LSHIFT", "BACKSLASH",
-      "Z", "X", "C", "V", "B", "N", "M",
-      "COMMA", "PERIOD", "SLASH",
-      "RSHIFT",
-      "MULTIPLY",
-      "LMENU",
-      "SPACE",
-      "CAPITAL",
-      "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10",
-      "NUMLOCK", "SCROLL",
-      "NUMPAD7", "NUMPAD8", "NUMPAD9",
-      "SUBTRACT",
-      "NUMPAD4", "NUMPAD5", "NUMPAD6",
-      "ADD",
-      "NUMPAD1", "NUMPAD2", "NUMPAD3", "NUMPAD0",
-      "DECIMAL",
-      "","",
-      "OEM_102",
-      "F11", "F12",
-      "","","","","","","","","","","",
-      "F13", "F14", "F15",
-      "","","","","","","","","","",
-      "KANA",
-      "","",
-      "ABNT_C1",
-      "","","","","",
-      "CONVERT",
-      "",
-      "NOCONVERT",
-      "",
-      "YEN",
-      "ABNT_C2",
-      "","","","","","","","","","","","","","",
-      "NUMPADEQUALS",
-      "","",
-      "PREVTRACK",
-      "AT",
-      "COLON", "UNDERLINE",
-      "KANJI",
-      "STOP",
-      "AX",
-      "UNLABELED",
-      "NEXTTRACK",
-      "","",
-      "NUMPADENTER",
-      "RCONTROL",
-      "","",
-      "MUTE",
-      "CALCULATOR",
-      "PLAYPAUSE",
-      "",
-      "MEDIASTOP",
-      "","","","","","","","","",
-      "VOLUMEDOWN",
-      "",
-      "VOLUMEUP",
-      "",
-      "WEBHOME",
-      "NUMPADCOMMA",
-      "",
-      "DIVIDE",
-      "",
-      "SYSRQ",
-      "RMENU",
-      "","","","","","","","","","","","",
-      "PAUSE",
-      "",
-      "HOME",
-      "UP",
-      "PGUP",
-      "",
-      "LEFT",
-      "",
-      "RIGHT",
-      "",
-      "END", "DOWN", "PGDOWN", "INSERT", "DELETE",
-      "","","","","","","",
-      "LWIN", "RWIN", "APPS",
-      "POWER", "SLEEP",
-      "","","",
-      "WAKE",
-      "",
-      "WEBSEARCH", "WEBFAVORITES", "WEBREFRESH", "WEBSTOP", "WEBFORWARD", "WEBBACK",
-      "MYCOMPUTER", "MAIL", "MEDIASELECT"
-    };
-    for (unsigned int i = 0; i < nKeys_s; i++)
-      keys_[i].name_ = "Key" + keyNames[i];
-
-    // mouse buttons
-    std::string mouseButtonNames[] = {
-      "MouseLeft", "MouseRight", "MouseMiddle",
-      "MouseButton3", "MouseButton4", "MouseButton5",
-      "MouseButton6", "MouseButton7",
-      "MouseWheel1Up", "MouseWheel1Down",
-      "MouseWheel2Up", "MouseWheel2Down" };
-    for (unsigned int i = 0; i < nMouseButtons_s; i++)
-      mouseButtons_[i].name_ = mouseButtonNames[i];
-
-    // joy stick buttons
-    for (unsigned int i = 0; i < 32; i++)
-      joyStickButtons_[i].name_ = "JoyButton" + getConvertedValue<int, std::string>(i);
-    for (unsigned int i = 32; i < nJoyStickButtons_s; i += 4)
-    {
-		  joyStickButtons_[i + 0].name_ = "JoyPOV" + getConvertedValue<int, std::string>((i - 32)/4 + 1) + "North";
-		  joyStickButtons_[i + 1].name_ = "JoyPOV" + getConvertedValue<int, std::string>((i - 32)/4 + 1) + "South";
-		  joyStickButtons_[i + 2].name_ = "JoyPOV" + getConvertedValue<int, std::string>((i - 32)/4 + 1) + "East";
-		  joyStickButtons_[i + 3].name_ = "JoyPOV" + getConvertedValue<int, std::string>((i - 32)/4 + 1) + "West";
-    }
-
-    // half axes
-    std::string rawNames[nHalfAxes_s/2];
-    rawNames[0] = "MouseX";
-    rawNames[1] = "MouseY";
-    rawNames[2] = "Empty1";
-    rawNames[3] = "Empty2";
-    for (unsigned int i = 4; i < nHalfAxes_s/2; i++)
-      rawNames[i] = "JoyAxis" + getConvertedValue<int, std::string>(i - 3);
-    for (unsigned int i = 0; i < nHalfAxes_s/2; i++)
-    {
-      halfAxes_[i * 2 + 0].name_ = rawNames[i] + "Pos";
-      halfAxes_[i * 2 + 1].name_ = rawNames[i] + "Neg";
-    }
-
-    for (unsigned int i = 0; i < this->nHalfAxes_s; i++)
-      halfAxes_[i].buttonThreshold_ = buttonThreshold_;
-  }
-
-  /**
-    @brief Destructor
-  */
-  KeyBinder::~KeyBinder()
-  {
-    // almost no destructors required because most of the arrays are static.
-    clearBindings(); // does some destruction work
-  }
-
-  /**
-    @brief Loads the key and button bindings.
-    @return True if loading succeeded.
-  */
-  void KeyBinder::loadBindings()
-  {
-    COUT(3) << "KeyBinder: Loading key bindings..." << std::endl;
-
-    clearBindings();
-
-    std::ifstream infile;
-    infile.open("keybindings.ini");
-    if (!infile)
-    {
-      ConfigFileManager::getSingleton()->setFile(CFT_Keybindings, "def_keybindings.ini");
-      ConfigFileManager::getSingleton()->save(CFT_Keybindings, "keybindings.ini");
-    }
-    else
-      infile.close();
-    ConfigFileManager::getSingleton()->setFile(CFT_Keybindings, "keybindings.ini");
-
-    // parse key bindings
-    setConfigValues();
-
-    COUT(3) << "KeyBinder: Loading key bindings done." << std::endl;
-  }
-
-  /**
-    @brief Loader for the key bindings, managed by config values.
-  */
-  void KeyBinder::setConfigValues()
-  {
-    SetConfigValueGeneric(KeyBinder, analogThreshold_, 0.05f)  .description("Threshold for analog axes until which the state is 0.");
-    SetConfigValueGeneric(KeyBinder, mouseSensitivity_, 1.0f)  .description("Mouse sensitivity.");
-    SetConfigValueGeneric(KeyBinder, bDeriveMouseInput_, false).description("Whether or not to derive moues movement for the absolute value.");
-    SetConfigValueGeneric(KeyBinder, derivePeriod_, 0.05f).description("Accuracy of the mouse input deriver. The higher the more precise, but laggier.");
-    SetConfigValueGeneric(KeyBinder, mouseSensitivityDerived_, 1.0f).description("Mouse sensitivity if mouse input is derived.");
-    SetConfigValueGeneric(KeyBinder, bClipMouse_, true).description("Whether or not to clip absolute value of mouse in non derive mode.");
-
-    float oldThresh = buttonThreshold_;
-    SetConfigValueGeneric(KeyBinder, buttonThreshold_, 0.80f).description("Threshold for analog axes until which the button is not pressed.");
-    if (oldThresh != buttonThreshold_)
-      for (unsigned int i = 0; i < nHalfAxes_s; i++)
-        if (halfAxes_[i].buttonThreshold_ == oldThresh)
-          halfAxes_[i].buttonThreshold_ = buttonThreshold_;
-
-    // keys
-    for (unsigned int i = 0; i < nKeys_s; i++)
-      readTrigger(keys_[i]);
-    // mouse buttons
-    for (unsigned int i = 0; i < nMouseButtons_s; i++)
-      readTrigger(mouseButtons_[i]);
-    // joy stick buttons
-    for (unsigned int i = 0; i < nJoyStickButtons_s; i++)
-      readTrigger(joyStickButtons_[i]);
-    // half axes
-    for (unsigned int i = 0; i < nHalfAxes_s; i++)
-      readTrigger(halfAxes_[i]);
-  }
-
-  void KeyBinder::readTrigger(Button& button)
-  {
-    // config value stuff
-    ConfigValueContainer* cont = ClassIdentifier<KeyBinder>::getIdentifier()->getConfigValueContainer(button.name_);
-    if (!cont)
-    {
-      cont = new ConfigValueContainer(CFT_Keybindings, ClassIdentifier<KeyBinder>::getIdentifier(), button.name_, "");
-      ClassIdentifier<KeyBinder>::getIdentifier()->addConfigValueContainer(button.name_, cont);
-    }
-    std::string old = button.bindingString_;
-    cont->getValue(&button.bindingString_);
-
-    // keybinder stuff
-    if (old != button.bindingString_)
-    {
-      // clear everything so we don't get old axis ParamCommands mixed up
-      button.clear();
-
-      // binding has changed
-      button.parse(paramCommandBuffer_);
-    }
-  }
-
-  /**
-    @brief Overwrites all bindings with ""
-  */
-  void KeyBinder::clearBindings()
-  {
-    for (unsigned int i = 0; i < nKeys_s; i++)
-      keys_[i].clear();
-
-    for (unsigned int i = 0; i < nMouseButtons_s; i++)
-      mouseButtons_[i].clear();
-
-    for (unsigned int i = 0; i < nJoyStickButtons_s; i++)
-      joyStickButtons_[i].clear();
-
-    for (unsigned int i = 0; i < nHalfAxes_s; i++)
-      halfAxes_[i].clear();
-
-    for (unsigned int i = 0; i < paramCommandBuffer_.size(); i++)
-      delete paramCommandBuffer_[i];
-    paramCommandBuffer_.clear();
-  }
-
-  void KeyBinder::resetJoyStickAxes()
-  {
-    for (unsigned int i = 8; i < nHalfAxes_s; i++)
-    {
-      halfAxes_[i].absVal_ = 0.0f;
-      halfAxes_[i].relVal_ = 0.0f;
-    }
-  }
-
-  void KeyBinder::tickInput(float dt, const HandlerState& state)
-  {
-    // we have to process all the analog input since there is e.g. no 'mouseDoesntMove' event.
-    unsigned int iBegin = 8;
-    unsigned int iEnd   = 8;
-    if (state.joyStick)
-      iEnd = nHalfAxes_s;
-    if (state.mouse)
-      iBegin = 0;
-    for (unsigned int i = iBegin; i < iEnd; i++)
-    {
-      if (halfAxes_[i].hasChanged_)
-      {
-        if (!halfAxes_[i].wasDown_ && halfAxes_[i].absVal_ > halfAxes_[i].buttonThreshold_)
-        {
-          halfAxes_[i].wasDown_ = true;
-          if (halfAxes_[i].nCommands_[KeybindMode::OnPress])
-            halfAxes_[i].execute(KeybindMode::OnPress);
-        }
-        else if (halfAxes_[i].wasDown_ && halfAxes_[i].absVal_ < halfAxes_[i].buttonThreshold_)
-        {
-          halfAxes_[i].wasDown_ = false;
-          if (halfAxes_[i].nCommands_[KeybindMode::OnRelease])
-            halfAxes_[i].execute(KeybindMode::OnRelease);
-        }
-        halfAxes_[i].hasChanged_ = false;
-      }
-
-      if (halfAxes_[i].wasDown_)
-      {
-        if (halfAxes_[i].nCommands_[KeybindMode::OnHold])
-          halfAxes_[i].execute(KeybindMode::OnHold);
-      }
-
-      // these are the actually useful axis bindings for analog input AND output
-      if (halfAxes_[i].relVal_ > analogThreshold_ || halfAxes_[i].absVal_ > analogThreshold_)
-      {
-        //COUT(3) << halfAxes_[i].name_ << "\t" << halfAxes_[i].absVal_ << std::endl;
-        halfAxes_[i].execute();
-      }
-    }
-
-    if (bDeriveMouseInput_ && state.mouse)
-    {
-      if (deriveTime_ > derivePeriod_)
-      {
-        //CCOUT(3) << "mouse abs: ";
+    /**
+    @brief
+        Constructor that does as little as necessary.
+    */
+    KeyBinder::KeyBinder()
+        : deriveTime_(0.0f)
+    {
+        mouseRelative_[0] = 0;
+        mouseRelative_[1] = 0;
+        mousePosition_[0] = 0;
+        mousePosition_[1] = 0;
+
+        RegisterRootObject(KeyBinder);
+
+        // keys
+        std::string keyNames[] = {
+        "UNASSIGNED",
+        "ESCAPE",
+        "1", "2", "3", "4", "5", "6", "7", "8", "9", "0",
+        "MINUS", "EQUALS", "BACK", "TAB",
+        "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P",
+        "LBRACKET", "RBRACKET",
+        "RETURN", "LCONTROL",
+        "A", "S", "D", "F", "G", "H", "J", "K", "L",
+        "SEMICOLON", "APOSTROPHE", "GRAVE",
+        "LSHIFT", "BACKSLASH",
+        "Z", "X", "C", "V", "B", "N", "M",
+        "COMMA", "PERIOD", "SLASH",
+        "RSHIFT",
+        "MULTIPLY",
+        "LMENU",
+        "SPACE",
+        "CAPITAL",
+        "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10",
+        "NUMLOCK", "SCROLL",
+        "NUMPAD7", "NUMPAD8", "NUMPAD9",
+        "SUBTRACT",
+        "NUMPAD4", "NUMPAD5", "NUMPAD6",
+        "ADD",
+        "NUMPAD1", "NUMPAD2", "NUMPAD3", "NUMPAD0",
+        "DECIMAL",
+        "","",
+        "OEM_102",
+        "F11", "F12",
+        "","","","","","","","","","","",
+        "F13", "F14", "F15",
+        "","","","","","","","","","",
+        "KANA",
+        "","",
+        "ABNT_C1",
+        "","","","","",
+        "CONVERT",
+        "",
+        "NOCONVERT",
+        "",
+        "YEN",
+        "ABNT_C2",
+        "","","","","","","","","","","","","","",
+        "NUMPADEQUALS",
+        "","",
+        "PREVTRACK",
+        "AT",
+        "COLON", "UNDERLINE",
+        "KANJI",
+        "STOP",
+        "AX",
+        "UNLABELED",
+        "NEXTTRACK",
+        "","",
+        "NUMPADENTER",
+        "RCONTROL",
+        "","",
+        "MUTE",
+        "CALCULATOR",
+        "PLAYPAUSE",
+        "",
+        "MEDIASTOP",
+        "","","","","","","","","",
+        "VOLUMEDOWN",
+        "",
+        "VOLUMEUP",
+        "",
+        "WEBHOME",
+        "NUMPADCOMMA",
+        "",
+        "DIVIDE",
+        "",
+        "SYSRQ",
+        "RMENU",
+        "","","","","","","","","","","","",
+        "PAUSE",
+        "",
+        "HOME",
+        "UP",
+        "PGUP",
+        "",
+        "LEFT",
+        "",
+        "RIGHT",
+        "",
+        "END", "DOWN", "PGDOWN", "INSERT", "DELETE",
+        "","","","","","","",
+        "LWIN", "RWIN", "APPS",
+        "POWER", "SLEEP",
+        "","","",
+        "WAKE",
+        "",
+        "WEBSEARCH", "WEBFAVORITES", "WEBREFRESH", "WEBSTOP", "WEBFORWARD", "WEBBACK",
+        "MYCOMPUTER", "MAIL", "MEDIASELECT"
+        };
+        for (unsigned int i = 0; i < nKeys_s; i++)
+            keys_[i].name_ = "Key" + keyNames[i];
+
+        // mouse buttons
+        std::string mouseButtonNames[] = {
+            "MouseLeft",     "MouseRight",   "MouseMiddle",
+            "MouseButton3",  "MouseButton4", "MouseButton5",
+            "MouseButton6",  "MouseButton7",
+            "MouseWheel1Up", "MouseWheel1Down",
+            "MouseWheel2Up", "MouseWheel2Down"
+        };
+        for (unsigned int i = 0; i < nMouseButtons_s; i++)
+            mouseButtons_[i].name_ = mouseButtonNames[i];
+
+        // joy stick buttons
+        for (unsigned int i = 0; i < 32; i++)
+            joyStickButtons_[i].name_ = "JoyButton" + getConvertedValue<int, std::string>(i);
+        for (unsigned int i = 32; i < nJoyStickButtons_s; i += 4)
+        {
+            joyStickButtons_[i + 0].name_ = "JoyPOV" + convertToString((i - 32)/4 + 1) + "North";
+            joyStickButtons_[i + 1].name_ = "JoyPOV" + convertToString((i - 32)/4 + 1) + "South";
+            joyStickButtons_[i + 2].name_ = "JoyPOV" + convertToString((i - 32)/4 + 1) + "East";
+            joyStickButtons_[i + 3].name_ = "JoyPOV" + convertToString((i - 32)/4 + 1) + "West";
+        }
+
+        // half axes
+        std::string rawNames[nHalfAxes_s/2];
+        rawNames[0] = "MouseX";
+        rawNames[1] = "MouseY";
+        rawNames[2] = "Empty1";
+        rawNames[3] = "Empty2";
+        for (unsigned int i = 4; i < nHalfAxes_s/2; i++)
+            rawNames[i] = "JoyAxis" + convertToString(i - 3);
+        for (unsigned int i = 0; i < nHalfAxes_s/2; i++)
+        {
+            halfAxes_[i * 2 + 0].name_ = rawNames[i] + "Pos";
+            halfAxes_[i * 2 + 1].name_ = rawNames[i] + "Neg";
+        }
+
+        for (unsigned int i = 0; i < this->nHalfAxes_s; i++)
+            halfAxes_[i].buttonThreshold_ = buttonThreshold_;
+    }
+
+    /**
+    @brief
+        Destructor
+    */
+    KeyBinder::~KeyBinder()
+    {
+        // almost no destructors required because most of the arrays are static.
+        clearBindings(); // does some destruction work
+    }
+
+    /**
+    @brief
+        Loads the key and button bindings.
+    @return
+        True if loading succeeded.
+    */
+    void KeyBinder::loadBindings()
+    {
+        COUT(3) << "KeyBinder: Loading key bindings..." << std::endl;
+
+        clearBindings();
+
+        std::ifstream infile;
+        infile.open("keybindings.ini");
+        if (!infile)
+        {
+            ConfigFileManager::getSingleton()->setFile(CFT_Keybindings, "def_keybindings.ini");
+            ConfigFileManager::getSingleton()->save(CFT_Keybindings, "keybindings.ini");
+        }
+        else
+            infile.close();
+        ConfigFileManager::getSingleton()->setFile(CFT_Keybindings, "keybindings.ini");
+
+        // parse key bindings
+        setConfigValues();
+
+        COUT(3) << "KeyBinder: Loading key bindings done." << std::endl;
+    }
+
+    /**
+    @brief
+        Loader for the key bindings, managed by config values.
+    */
+    void KeyBinder::setConfigValues()
+    {
+        SetConfigValueGeneric(KeyBinder, analogThreshold_, 0.05f)
+            .description("Threshold for analog axes until which the state is 0.");
+        SetConfigValueGeneric(KeyBinder, mouseSensitivity_, 1.0f)
+            .description("Mouse sensitivity.");
+        SetConfigValueGeneric(KeyBinder, bDeriveMouseInput_, false)
+            .description("Whether or not to derive moues movement for the absolute value.");
+        SetConfigValueGeneric(KeyBinder, derivePeriod_, 0.05f)
+            .description("Accuracy of the mouse input deriver. The higher the more precise, but laggier.");
+        SetConfigValueGeneric(KeyBinder, mouseSensitivityDerived_, 1.0f)
+            .description("Mouse sensitivity if mouse input is derived.");
+        SetConfigValueGeneric(KeyBinder, bClipMouse_, true)
+            .description("Whether or not to clip absolute value of mouse in non derive mode.");
+
+        float oldThresh = buttonThreshold_;
+        SetConfigValueGeneric(KeyBinder, buttonThreshold_, 0.80f)
+            .description("Threshold for analog axes until which the button is not pressed.");
+        if (oldThresh != buttonThreshold_)
+            for (unsigned int i = 0; i < nHalfAxes_s; i++)
+                if (halfAxes_[i].buttonThreshold_ == oldThresh)
+                    halfAxes_[i].buttonThreshold_ = buttonThreshold_;
+
+        // keys
+        for (unsigned int i = 0; i < nKeys_s; i++)
+            readTrigger(keys_[i]);
+        // mouse buttons
+        for (unsigned int i = 0; i < nMouseButtons_s; i++)
+            readTrigger(mouseButtons_[i]);
+        // joy stick buttons
+        for (unsigned int i = 0; i < nJoyStickButtons_s; i++)
+            readTrigger(joyStickButtons_[i]);
+        // half axes
+        for (unsigned int i = 0; i < nHalfAxes_s; i++)
+            readTrigger(halfAxes_[i]);
+    }
+
+    void KeyBinder::readTrigger(Button& button)
+    {
+        // config value stuff
+        ConfigValueContainer* cont
+            = ClassIdentifier<KeyBinder>::getIdentifier()->getConfigValueContainer(button.name_);
+        if (!cont)
+        {
+            cont = new ConfigValueContainer
+                (CFT_Keybindings, ClassIdentifier<KeyBinder>::getIdentifier(), button.name_, "");
+            ClassIdentifier<KeyBinder>::getIdentifier()->addConfigValueContainer(button.name_, cont);
+        }
+        std::string old = button.bindingString_;
+        cont->getValue(&button.bindingString_);
+
+        // keybinder stuff
+        if (old != button.bindingString_)
+        {
+            // clear everything so we don't get old axis ParamCommands mixed up
+            button.clear();
+
+            // binding has changed
+            button.parse(paramCommandBuffer_);
+        }
+    }
+
+    /**
+    @brief
+        Overwrites all bindings with ""
+    */
+    void KeyBinder::clearBindings()
+    {
+        for (unsigned int i = 0; i < nKeys_s; i++)
+            keys_[i].clear();
+
+        for (unsigned int i = 0; i < nMouseButtons_s; i++)
+            mouseButtons_[i].clear();
+
+        for (unsigned int i = 0; i < nJoyStickButtons_s; i++)
+            joyStickButtons_[i].clear();
+
+        for (unsigned int i = 0; i < nHalfAxes_s; i++)
+            halfAxes_[i].clear();
+
+        for (unsigned int i = 0; i < paramCommandBuffer_.size(); i++)
+            delete paramCommandBuffer_[i];
+        paramCommandBuffer_.clear();
+    }
+
+    void KeyBinder::resetJoyStickAxes()
+    {
+        for (unsigned int i = 8; i < nHalfAxes_s; i++)
+        {
+            halfAxes_[i].absVal_ = 0.0f;
+            halfAxes_[i].relVal_ = 0.0f;
+        }
+    }
+
+    void KeyBinder::tickMouse(float dt)
+    {
+        tickDevices(0, 8);
+
+        if (bDeriveMouseInput_)
+        {
+            if (deriveTime_ > derivePeriod_)
+            {
+                //CCOUT(3) << "mouse abs: ";
+                for (int i = 0; i < 2; i++)
+                {
+                    if (mouseRelative_[i] > 0)
+                    {
+                        halfAxes_[2*i + 0].absVal_
+                            =  mouseRelative_[i] / deriveTime_ * 0.0005 * mouseSensitivityDerived_;
+                        halfAxes_[2*i + 1].absVal_ = 0.0f;
+                    }
+                    else if (mouseRelative_[i] < 0)
+                    {
+                        halfAxes_[2*i + 0].absVal_ = 0.0f;
+                        halfAxes_[2*i + 1].absVal_
+                            = -mouseRelative_[i] / deriveTime_ * 0.0005 * mouseSensitivityDerived_;
+                    }
+                    else
+                    {
+                        halfAxes_[2*i + 0].absVal_ = 0.0f;
+                        halfAxes_[2*i + 1].absVal_ = 0.0f;
+                    }
+                    //COUT(3) << mouseRelative_[i] << " | ";
+                    mouseRelative_[i] = 0;
+                    halfAxes_[2*i + 0].hasChanged_ = true;
+                    halfAxes_[2*i + 1].hasChanged_ = true;
+                }
+                deriveTime_ = 0.0f;
+                //COUT(3) << std::endl;
+            }
+            else
+                deriveTime_ += dt;
+        }
+    }
+
+    void KeyBinder::tickJoyStick(float dt, int device)
+    {
+        tickDevices(8, nHalfAxes_s);
+    }
+
+    void KeyBinder::tickInput(float dt)
+    {
+        // execute all buffered bindings (additional parameter)
+        for (unsigned int i = 0; i < paramCommandBuffer_.size(); i++)
+            paramCommandBuffer_[i]->execute();
+
+        // always reset the relative movement of the mouse
+        for (unsigned int i = 0; i < 8; i++)
+            halfAxes_[i].relVal_ = 0.0f;
+    }
+
+    void KeyBinder::tickDevices(unsigned int begin, unsigned int end)
+    {
+        for (unsigned int i = begin; i < end; i++)
+        {
+            // button mode
+            // TODO: optimize out all the half axes that don't act as a button at the moment
+            if (halfAxes_[i].hasChanged_)
+            {
+                if (!halfAxes_[i].wasDown_ && halfAxes_[i].absVal_ > halfAxes_[i].buttonThreshold_)
+                {
+                    halfAxes_[i].wasDown_ = true;
+                    if (halfAxes_[i].nCommands_[KeybindMode::OnPress])
+                        halfAxes_[i].execute(KeybindMode::OnPress);
+                }
+                else if (halfAxes_[i].wasDown_ && halfAxes_[i].absVal_ < halfAxes_[i].buttonThreshold_)
+                {
+                    halfAxes_[i].wasDown_ = false;
+                    if (halfAxes_[i].nCommands_[KeybindMode::OnRelease])
+                        halfAxes_[i].execute(KeybindMode::OnRelease);
+                }
+                halfAxes_[i].hasChanged_ = false;
+            }
+
+            if (halfAxes_[i].wasDown_)
+            {
+                if (halfAxes_[i].nCommands_[KeybindMode::OnHold])
+                    halfAxes_[i].execute(KeybindMode::OnHold);
+            }
+
+            // these are the actually useful axis bindings for analog input
+            if (halfAxes_[i].relVal_ > analogThreshold_ || halfAxes_[i].absVal_ > analogThreshold_)
+            {
+                //COUT(3) << halfAxes_[i].name_ << "\t" << halfAxes_[i].absVal_ << std::endl;
+                halfAxes_[i].execute();
+            }
+        }
+    }
+
+    void KeyBinder::keyPressed (const KeyEvent& evt)
+    { keys_[evt.key].execute(KeybindMode::OnPress); }
+
+    void KeyBinder::keyReleased(const KeyEvent& evt)
+    { keys_[evt.key].execute(KeybindMode::OnRelease); }
+
+    void KeyBinder::keyHeld    (const KeyEvent& evt)
+    { keys_[evt.key].execute(KeybindMode::OnHold); }
+
+
+    void KeyBinder::mouseButtonPressed (MouseButton::Enum id)
+    { mouseButtons_[id].execute(KeybindMode::OnPress); }
+
+    void KeyBinder::mouseButtonReleased(MouseButton::Enum id)
+    { mouseButtons_[id].execute(KeybindMode::OnRelease); }
+
+    void KeyBinder::mouseButtonHeld    (MouseButton::Enum id)
+    { mouseButtons_[id].execute(KeybindMode::OnHold); }
+
+
+    void KeyBinder::joyStickButtonPressed (unsigned int joyStickID, unsigned int button)
+    { joyStickButtons_[button].execute(KeybindMode::OnPress); }
+
+    void KeyBinder::joyStickButtonReleased(unsigned int joyStickID, unsigned int button)
+    { joyStickButtons_[button].execute(KeybindMode::OnRelease); }
+
+    void KeyBinder::joyStickButtonHeld    (unsigned int joyStickID, unsigned int button)
+    { joyStickButtons_[button].execute(KeybindMode::OnHold); }
+
+    /**
+    @brief
+        Event handler for the mouseMoved Event.
+    @param e
+        Mouse state information
+    */
+    void KeyBinder::mouseMoved(IntVector2 abs_, IntVector2 rel_, IntVector2 clippingSize)
+    {
+        // y axis of mouse input is inverted
+        int rel[] = { rel_.x, -rel_.y };
+
+        if (!bDeriveMouseInput_)
+        {
+            for (int i = 0; i < 2; i++)
+            {
+                if (rel[i])
+                {
+                    // absolute
+                    halfAxes_[2*i + 0].hasChanged_ = true;
+                    halfAxes_[2*i + 1].hasChanged_ = true;
+                    mousePosition_[i] += rel[i];
+
+                    if (bClipMouse_)
+                    {
+                        if (mousePosition_[i] > 1024)
+                            mousePosition_[i] =  1024;
+                        if (mousePosition_[i] < -1024)
+                            mousePosition_[i] = -1024;
+                    }
+
+                    if (mousePosition_[i] >= 0)
+                    {
+                        halfAxes_[2*i + 0].absVal_ =   mousePosition_[i]/1024.0f * mouseSensitivity_;
+                        halfAxes_[2*i + 1].absVal_ =  0.0f;
+                    }
+                    else
+                    {
+                        halfAxes_[2*i + 0].absVal_ =  0.0f;
+                        halfAxes_[2*i + 1].absVal_ =  -mousePosition_[i]/1024.0f * mouseSensitivity_;
+                    }
+                }
+            }
+        }
+        else
+        {
+            mouseRelative_[0] += rel[0];
+            mouseRelative_[1] += rel[1];
+        }
+
+        // relative
         for (int i = 0; i < 2; i++)
         {
-          if (mouseRelative_[i] > 0)
-          {
-            halfAxes_[2*i + 0].absVal_ =  mouseRelative_[i] / deriveTime_ * 0.0005 * mouseSensitivityDerived_;
-            halfAxes_[2*i + 1].absVal_ = 0.0f;
-          }
-          else if (mouseRelative_[i] < 0)
-          {
-            halfAxes_[2*i + 0].absVal_ = 0.0f;
-            halfAxes_[2*i + 1].absVal_ = -mouseRelative_[i] / deriveTime_ * 0.0005 * mouseSensitivityDerived_;
-          }
-          else
-          {
-            halfAxes_[2*i + 0].absVal_ = 0.0f;
-            halfAxes_[2*i + 1].absVal_ = 0.0f;
-          }
-          //COUT(3) << mouseRelative_[i] << " | ";
-          mouseRelative_[i] = 0;
-          halfAxes_[2*i + 0].hasChanged_ = true;
-          halfAxes_[2*i + 1].hasChanged_ = true;
-        }
-        deriveTime_ = 0.0f;
-        //COUT(3) << std::endl;
-      }
-      else
-        deriveTime_ += dt;
-    }
-
-    // execute all buffered bindings (addional parameter)
-    for (unsigned int i = 0; i < paramCommandBuffer_.size(); i++)
-      paramCommandBuffer_[i]->execute();
-
-    // always reset the relative movement of the mouse
-    if (state.mouse)
-      for (unsigned int i = 0; i < 8; i++)
-        halfAxes_[i].relVal_ = 0.0f;
-  }
-
-  void KeyBinder::keyPressed (const KeyEvent& evt)
-  { keys_[evt.key].execute(KeybindMode::OnPress); }
-
-  void KeyBinder::keyReleased(const KeyEvent& evt)
-  { keys_[evt.key].execute(KeybindMode::OnRelease); }
-
-  void KeyBinder::keyHeld    (const KeyEvent& evt)
-  { keys_[evt.key].execute(KeybindMode::OnHold); }
-
-
-  void KeyBinder::mouseButtonPressed (MouseButton::Enum id)
-  { mouseButtons_[id].execute(KeybindMode::OnPress); }
-
-  void KeyBinder::mouseButtonReleased(MouseButton::Enum id)
-  { mouseButtons_[id].execute(KeybindMode::OnRelease); }
-
-  void KeyBinder::mouseButtonHeld    (MouseButton::Enum id)
-  { mouseButtons_[id].execute(KeybindMode::OnHold); }
-
-
-  void KeyBinder::joyStickButtonPressed (int joyStickID, int button)
-  { joyStickButtons_[button].execute(KeybindMode::OnPress); }
-
-  void KeyBinder::joyStickButtonReleased(int joyStickID, int button)
-  { joyStickButtons_[button].execute(KeybindMode::OnRelease); }
-
-  void KeyBinder::joyStickButtonHeld    (int joyStickID, int button)
-  { joyStickButtons_[button].execute(KeybindMode::OnHold); }
-
-  /**
-    @brief Event handler for the mouseMoved Event.
-    @param e Mouse state information
-  */
-  void KeyBinder::mouseMoved(IntVector2 abs_, IntVector2 rel_, IntVector2 clippingSize)
-  {
-    // y axis of mouse input is inverted
-    int rel[] = { rel_.x, -rel_.y };
-
-    if (!bDeriveMouseInput_)
-    {
-      for (int i = 0; i < 2; i++)
-      {
-        if (rel[i])
-        {
-          // absolute
-          halfAxes_[2*i + 0].hasChanged_ = true;
-          halfAxes_[2*i + 1].hasChanged_ = true;
-          mousePosition_[i] += rel[i];
-
-          if (bClipMouse_)
-          {
-            if (mousePosition_[i] > 1024)
-              mousePosition_[i] =  1024;
-            if (mousePosition_[i] < -1024)
-              mousePosition_[i] = -1024;
-          }
-
-          if (mousePosition_[i] >= 0)
-          {
-            halfAxes_[2*i + 0].absVal_ =   mousePosition_[i]/1024.0f * mouseSensitivity_;
-            halfAxes_[2*i + 1].absVal_ =  0.0f;
-          }
-          else
-          {
-            halfAxes_[2*i + 0].absVal_ =  0.0f;
-            halfAxes_[2*i + 1].absVal_ =  -mousePosition_[i]/1024.0f * mouseSensitivity_;
-          }
-        }
-      }
-    }
-    else
-    {
-      mouseRelative_[0] += rel[0];
-      mouseRelative_[1] += rel[1];
-    }
-
-    // relative
-    for (int i = 0; i < 2; i++)
-    {
-      if (rel[i] > 0)
-        halfAxes_[0 + 2*i].relVal_ =  ((float)rel[i])/1024 * mouseSensitivity_;
-      else
-        halfAxes_[1 + 2*i].relVal_ = -((float)rel[i])/1024 * mouseSensitivity_;
-    }
-  }
-
-  /**
+            if (rel[i] > 0)
+                halfAxes_[0 + 2*i].relVal_ =  ((float)rel[i])/1024 * mouseSensitivity_;
+            else
+                halfAxes_[1 + 2*i].relVal_ = -((float)rel[i])/1024 * mouseSensitivity_;
+        }
+    }
+
+    /**
     @brief Event handler for the mouseScrolled Event.
     @param e Mouse state information
-  */
-  void KeyBinder::mouseScrolled(int abs, int rel)
-  {
-    //COUT(3) << mouseButtons_[8].name_ << "   " << abs << " | " << rel << std::endl;
-
-    if (rel > 0)
-      for (int i = 0; i < rel/120; i++)
-        mouseButtons_[8].execute(KeybindMode::OnPress, ((float)abs)/120.0f);
-    else
-      for (int i = 0; i < -rel/120; i++)
-        mouseButtons_[9].execute(KeybindMode::OnPress, ((float)abs)/120.0f);
-  }
-
-  void KeyBinder::joyStickAxisMoved(int joyStickID, int axis, float value)
-  {
-    // TODO: Use proper calibration values instead of generally 16-bit integer
-    int i = 8 + axis * 2;
-    if (value >= 0)
-    {
-      //if (value > 10000)
-      //{ CCOUT(3) << halfAxes_[i].name_ << std::endl; }
-
-      halfAxes_[i].absVal_ = value;
-      halfAxes_[i].relVal_ = value;
-      halfAxes_[i].hasChanged_ = true;
-      if (halfAxes_[i + 1].absVal_ > 0.0f)
-      {
-        halfAxes_[i + 1].absVal_ = -0.0f;
-        halfAxes_[i + 1].relVal_ = -0.0f;
-        halfAxes_[i + 1].hasChanged_ = true;
-      }
-    }
-    else
-    {
-      //if (value < -10000)
-      //{ CCOUT(3) << halfAxes_[i + 1].name_ << std::endl; }
-
-      halfAxes_[i + 1].absVal_ = -value;
-      halfAxes_[i + 1].relVal_ = -value;
-      halfAxes_[i + 1].hasChanged_ = true;
-      if (halfAxes_[i].absVal_ > 0.0f)
-      {
-        halfAxes_[i].absVal_ = -0.0f;
-        halfAxes_[i].relVal_ = -0.0f;
-        halfAxes_[i].hasChanged_ = true;
-      }
-    }
-  }
+    */
+    void KeyBinder::mouseScrolled(int abs, int rel)
+    {
+        //COUT(3) << mouseButtons_[8].name_ << "   " << abs << " | " << rel << std::endl;
+
+        if (rel > 0)
+            for (int i = 0; i < rel/120; i++)
+                mouseButtons_[8].execute(KeybindMode::OnPress, ((float)abs)/120.0f);
+        else
+            for (int i = 0; i < -rel/120; i++)
+                mouseButtons_[9].execute(KeybindMode::OnPress, ((float)abs)/120.0f);
+    }
+
+    void KeyBinder::joyStickAxisMoved(unsigned int joyStickID, unsigned int axis, float value)
+    {
+        int i = 8 + axis * 2;
+        if (value >= 0)
+        {
+            //if (value > 10000)
+            //{ CCOUT(3) << halfAxes_[i].name_ << std::endl; }
+
+            halfAxes_[i].absVal_ = value;
+            halfAxes_[i].relVal_ = value;
+            halfAxes_[i].hasChanged_ = true;
+            if (halfAxes_[i + 1].absVal_ > 0.0f)
+            {
+                halfAxes_[i + 1].absVal_ = -0.0f;
+                halfAxes_[i + 1].relVal_ = -0.0f;
+                halfAxes_[i + 1].hasChanged_ = true;
+            }
+        }
+        else
+        {
+            //if (value < -10000)
+            //{ CCOUT(3) << halfAxes_[i + 1].name_ << std::endl; }
+
+            halfAxes_[i + 1].absVal_ = -value;
+            halfAxes_[i + 1].relVal_ = -value;
+            halfAxes_[i + 1].hasChanged_ = true;
+            if (halfAxes_[i].absVal_ > 0.0f)
+            {
+                halfAxes_[i].absVal_ = -0.0f;
+                halfAxes_[i].relVal_ = -0.0f;
+                halfAxes_[i].hasChanged_ = true;
+            }
+        }
+    }
 }
Index: code/branches/gui/src/core/input/KeyBinder.h
===================================================================
--- code/branches/gui/src/core/input/KeyBinder.h	(revision 1636)
+++ code/branches/gui/src/core/input/KeyBinder.h	(revision 1638)
@@ -28,7 +28,8 @@
 
 /**
- @file
- @brief Different definitions of input processing.
- */
+@file
+@brief
+    Different definitions of input processing.
+*/
 
 #ifndef _KeyBinder_H__
@@ -46,97 +47,106 @@
 namespace orxonox
 {
-  /**
-    @brief Handles mouse, keyboard and joy stick input while in the actual game mode.
-           Manages the key bindings.
-  */
-  class _CoreExport KeyBinder : public KeyHandler, public MouseHandler, public JoyStickHandler, public OrxonoxClass
-  {
-  public:
-    KeyBinder ();
-    virtual ~KeyBinder();
+    /**
+    @brief
+        Handles mouse, keyboard and joy stick input while in the actual game mode.
+        Manages the key bindings.
+    */
+    class _CoreExport KeyBinder : public KeyHandler, public MouseHandler, public JoyStickHandler, public OrxonoxClass
+    {
+    public:
+        KeyBinder ();
+        virtual ~KeyBinder();
 
-    void loadBindings();
-    void clearBindings();
-    void setConfigValues();
-    void resetJoyStickAxes();
+        void loadBindings();
+        void clearBindings();
+        void setConfigValues();
+        void resetJoyStickAxes();
 
-  protected: // functions
-    void tickInput(float dt, const HandlerState& state);
+    protected: // functions
+        void tickInput(float dt);
+        //void tickInput(float dt, int device);
+        void tickKey(float dt) { }
+        void tickMouse(float dt);
+        void tickJoyStick(float dt, int device);
+        void tickDevices(unsigned int begin, unsigned int end);
 
-    virtual void readTrigger(Button& button);
+        virtual void readTrigger(Button& button);
 
-    void keyPressed (const KeyEvent& evt);
-    void keyReleased(const KeyEvent& evt);
-    void keyHeld    (const KeyEvent& evt);
+        void keyPressed (const KeyEvent& evt);
+        void keyReleased(const KeyEvent& evt);
+        void keyHeld    (const KeyEvent& evt);
 
-    void mouseButtonPressed (MouseButton::Enum id);
-    void mouseButtonReleased(MouseButton::Enum id);
-    void mouseButtonHeld    (MouseButton::Enum id);
-    void mouseMoved         (IntVector2 abs, IntVector2 rel, IntVector2 clippingSize);
-    void mouseScrolled      (int abs, int rel);
+        void mouseButtonPressed (MouseButton::Enum id);
+        void mouseButtonReleased(MouseButton::Enum id);
+        void mouseButtonHeld    (MouseButton::Enum id);
+        void mouseMoved         (IntVector2 abs, IntVector2 rel, IntVector2 clippingSize);
+        void mouseScrolled      (int abs, int rel);
 
-    void joyStickButtonPressed (int joyStickID, int button);
-    void joyStickButtonReleased(int joyStickID, int button);
-    void joyStickButtonHeld    (int joyStickID, int button);
-    void joyStickAxisMoved     (int joyStickID, int axis, float value);
+        void joyStickButtonPressed (unsigned int joyStickID, unsigned int button);
+        void joyStickButtonReleased(unsigned int joyStickID, unsigned int button);
+        void joyStickButtonHeld    (unsigned int joyStickID, unsigned int button);
+        void joyStickAxisMoved     (unsigned int joyStickID, unsigned int axis, float value);
 
-  protected: // variables
-    //! denotes the number of different keys there are in OIS.
-    static const unsigned int nKeys_s = 0xEE;
-    //! Actual key bindings as bundle for Press, Hold and Release
-    Button keys_ [nKeys_s];
+    protected: // variables
+        //! denotes the number of different keys there are in OIS.
+        static const unsigned int nKeys_s = 0xEE;
+        //! Actual key bindings as bundle for Press, Hold and Release
+        Button keys_ [nKeys_s];
 
-    //! denotes the number of different mouse buttons there are in OIS.
-    static const unsigned int nMouseButtons_s = 8 + 2*2; // 8 buttons and 2 scroll wheels
-    //! Actual key bindings as bundle for Press, Hold and Release
-    Button mouseButtons_ [nMouseButtons_s];
+        //! denotes the number of different mouse buttons there are in OIS.
+        static const unsigned int nMouseButtons_s = 8 + 2*2; // 8 buttons and 2 scroll wheels
+        //! Actual key bindings as bundle for Press, Hold and Release
+        Button mouseButtons_ [nMouseButtons_s];
 
-    //! denotes the number of different joy stick buttons there are in OIS.
-    static const unsigned int nJoyStickButtons_s = 32 + 4 * 4; // 32 buttons and 4 POVs with 4 buttons
-    //! Actual key bindings as bundle for Press, Hold and Release
-    Button joyStickButtons_ [nJoyStickButtons_s];
+        //! denotes the number of different joy stick buttons there are in OIS.
+        static const unsigned int nJoyStickButtons_s = 32 + 4 * 4; // 32 buttons and 4 POVs with 4 buttons
+        //! Actual key bindings as bundle for Press, Hold and Release
+        Button joyStickButtons_ [nJoyStickButtons_s];
 
-    //! denotes the number of half axes (every axis twice) there can be.
-    static const unsigned int nHalfAxes_s = 56;
-    /**
-    * Array with all the half axes for mouse and joy sticks.
-    * Keep in mind that the positions are fixed and that the first entry is the
-    * positive one and the second is negative.
-    * Sequence is as follows:
-    *  0 -  3: Mouse x and y
-    *  4 -  7: empty
-    *  8 - 23: joy stick slider axes 1 to 8
-    * 24 - 55: joy stick axes 1 - 16
-    */
-    HalfAxis halfAxes_[nHalfAxes_s];
+        //! denotes the number of half axes (every axis twice) there can be.
+        static const unsigned int nHalfAxes_s = 56;
+        /**
+        * Array with all the half axes for mouse and joy sticks.
+        * Keep in mind that the positions are fixed and that the first entry is the
+        * positive one and the second is negative.
+        * Sequence is as follows:
+        *  0 -  3: Mouse x and y
+        *  4 -  7: empty
+        *  8 - 23: joy stick slider axes 1 to 8
+        * 24 - 55: joy stick axes 1 - 16
+        */
+        HalfAxis halfAxes_[nHalfAxes_s];
 
-    /**
-    * Commands that have additional parameters (axes) are executed at the end of
-    * the tick() so that all values can be buffered for single execution.
-    */
-    std::vector<BufferedParamCommand*> paramCommandBuffer_;
+        /**
+        @brief
+            Commands that have additional parameters (axes) are executed at the end of
+            the tick() so that all values can be buffered for single execution.
+        */
+        std::vector<BufferedParamCommand*> paramCommandBuffer_;
 
-    //! Keeps track of the absolute mouse value (incl. scroll wheel)
-    int mousePosition_[2];
-    //! Used to derive mouse input if requested
-    int mouseRelative_[2];
-    float deriveTime_;
+        //! Keeps track of the absolute mouse value (incl. scroll wheel)
+        int mousePosition_[2];
+        //! Used to derive mouse input if requested
+        int mouseRelative_[2];
+        float deriveTime_;
 
-    //##### ConfigValues #####
-    //! Threshold for analog triggers until which the state is 0.
-    float analogThreshold_;
-    //! Threshold for analog triggers until which the button is not pressed.
-    float buttonThreshold_;
-    //! Derive mouse input for absolute values?
-    bool bDeriveMouseInput_;
-    //! Accuracy of the mouse input deriver. The higher the more precise, but laggier.
-    float derivePeriod_;
-    //! mouse sensitivity
-    float mouseSensitivity_;
-    //! mouse sensitivity if mouse input is derived
-    float mouseSensitivityDerived_;
-    //! Whether or not to clip abslute mouse values to 1024
-    bool bClipMouse_;
-  };
+
+        //##### ConfigValues #####
+
+        //! Threshold for analog triggers until which the state is 0.
+        float analogThreshold_;
+        //! Threshold for analog triggers until which the button is not pressed.
+        float buttonThreshold_;
+        //! Derive mouse input for absolute values?
+        bool bDeriveMouseInput_;
+        //! Accuracy of the mouse input deriver. The higher the more precise, but laggier.
+        float derivePeriod_;
+        //! mouse sensitivity
+        float mouseSensitivity_;
+        //! mouse sensitivity if mouse input is derived
+        float mouseSensitivityDerived_;
+        //! Whether or not to clip abslute mouse values to 1024
+        bool bClipMouse_;
+    };
 }
 
Index: code/branches/gui/src/core/input/KeyDetector.cc
===================================================================
--- code/branches/gui/src/core/input/KeyDetector.cc	(revision 1636)
+++ code/branches/gui/src/core/input/KeyDetector.cc	(revision 1638)
@@ -28,7 +28,8 @@
 
 /**
- @file
- @brief Implementation of the different input handlers.
- */
+@file
+@brief
+    Implementation of the different input handlers.
+*/
 
 #include "KeyDetector.h"
@@ -42,36 +43,41 @@
 namespace orxonox
 {
-  /**
-    @brief Constructor
-  */
-  KeyDetector::KeyDetector()
-  {
-    RegisterObject(KeyDetector);
-  }
+    /**
+    @brief
+        Constructor
+    */
+    KeyDetector::KeyDetector()
+    {
+        RegisterObject(KeyDetector);
+    }
 
-  /**
-    @brief Destructor
-  */
-  KeyDetector::~KeyDetector()
-  {
-  }
+    /**
+    @brief
+        Destructor
+    */
+    KeyDetector::~KeyDetector()
+    {
+    }
 
-  /**
-    @brief Loads the key and button bindings.
-    @return True if loading succeeded.
-  */
-  void KeyDetector::loadBindings()
-  {
-    clearBindings();
-    setConfigValues();
-  }
+    /**
+    @brief
+        Loads the key and button bindings.
+    @return
+        True if loading succeeded.
+    */
+    void KeyDetector::loadBindings(const std::string& command)
+    {
+        clearBindings();
+        setConfigValues();
+        this->command_ = command;
+    }
 
-  void KeyDetector::readTrigger(Button& button)
-  {
-    SimpleCommand* cmd = new SimpleCommand();
-    cmd->evaluation_ = CommandExecutor::evaluate("storeKeyStroke " + button.name_);
-    button.commands_[KeybindMode::OnPress] = new BaseCommand*[1];
-    button.commands_[KeybindMode::OnPress][0] = cmd;
-    button.nCommands_[KeybindMode::OnPress] = 1;
-  }
+    void KeyDetector::readTrigger(Button& button)
+    {
+        SimpleCommand* cmd = new SimpleCommand();
+        cmd->evaluation_ = CommandExecutor::evaluate(this->command_ + " " + button.name_);
+        button.commands_[KeybindMode::OnPress] = new BaseCommand*[1];
+        button.commands_[KeybindMode::OnPress][0] = cmd;
+        button.nCommands_[KeybindMode::OnPress] = 1;
+    }
 }
Index: code/branches/gui/src/core/input/KeyDetector.h
===================================================================
--- code/branches/gui/src/core/input/KeyDetector.h	(revision 1636)
+++ code/branches/gui/src/core/input/KeyDetector.h	(revision 1638)
@@ -28,7 +28,8 @@
 
 /**
- @file
- @brief Different definitions of input processing.
- */
+@file
+@brief
+    Different definitions of input processing.
+*/
 
 #ifndef _KeyDetector_H__
@@ -41,14 +42,17 @@
 namespace orxonox
 {
-  class _CoreExport KeyDetector : public KeyBinder
-  {
-  public:
-    KeyDetector();
-    ~KeyDetector();
-    void loadBindings();
+    class _CoreExport KeyDetector : public KeyBinder
+    {
+    public:
+        KeyDetector();
+        ~KeyDetector();
+        void loadBindings(const std::string& command);
 
-  protected:
-    void readTrigger(Button& button);
-  };
+    protected:
+        void readTrigger(Button& button);
+
+    private:
+        std::string command_;
+    };
 }
 
Index: code/branches/gui/src/core/input/SimpleInputState.cc
===================================================================
--- code/branches/gui/src/core/input/SimpleInputState.cc	(revision 1638)
+++ code/branches/gui/src/core/input/SimpleInputState.cc	(revision 1638)
@@ -0,0 +1,270 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief
+    Implementation of the SimpleInputState class.
+*/
+
+#include "SimpleInputState.h"
+
+#include <assert.h>
+#include "core/Debug.h"
+#include "core/Executor.h"
+
+namespace orxonox
+{
+    using namespace InputDevice;
+
+    SimpleInputState::SimpleInputState()
+        : keyHandler_(0)
+        , mouseHandler_(0)
+        , joyStickHandlerAll_(0)
+    {
+    }
+
+    void SimpleInputState::numberOfJoySticksChanged(unsigned int n)
+    {
+        unsigned int oldSize = joyStickHandler_.size();
+        joyStickHandler_.resize(n);
+
+        if (oldSize > n)
+        {
+            // we have to add the handler in joyStickHandlerAll_ to the joyStickHandler_[>n]
+            for (unsigned int i = oldSize; i < n; ++i)
+            {
+                joyStickHandler_[i] = joyStickHandlerAll_;
+            }
+        }
+        update();
+    }
+
+    void SimpleInputState::keyPressed(const KeyEvent& evt)
+    {
+        if (keyHandler_)
+            keyHandler_->keyPressed(evt);
+    }
+
+    void SimpleInputState::keyReleased(const KeyEvent& evt)
+    {
+        if (keyHandler_)
+            keyHandler_->keyReleased(evt);
+    }
+
+    void SimpleInputState::keyHeld(const KeyEvent& evt)
+    {
+        if (keyHandler_)
+            keyHandler_->keyHeld(evt);
+    }
+
+
+    void SimpleInputState::mouseMoved(IntVector2 abs, IntVector2 rel, IntVector2 clippingSize)
+    {
+        if (mouseHandler_)
+            mouseHandler_->mouseMoved(abs, rel, clippingSize);
+    }
+
+    void SimpleInputState::mouseScrolled(int abs, int rel)
+    {
+        if (mouseHandler_)
+            mouseHandler_->mouseScrolled(abs, rel);
+    }
+
+    void SimpleInputState::mouseButtonPressed(MouseButton::Enum id)
+    {
+        if (mouseHandler_)
+            mouseHandler_->mouseButtonPressed(id);
+    }
+
+    void SimpleInputState::mouseButtonReleased(MouseButton::Enum id)
+    {
+        if (mouseHandler_)
+            mouseHandler_->mouseButtonReleased(id);
+    }
+
+    void SimpleInputState::mouseButtonHeld(MouseButton::Enum id)
+    {
+        if (mouseHandler_)
+            mouseHandler_->mouseButtonHeld(id);
+    }
+
+
+    void SimpleInputState::joyStickAxisMoved(unsigned int joyStickID, unsigned int axis, float value)
+    {
+        assert(joyStickID < joyStickHandler_.size());
+        if (joyStickHandler_[joyStickID])
+            joyStickHandler_[joyStickID]->joyStickAxisMoved(joyStickID, axis, value);
+    }
+
+    void SimpleInputState::joyStickButtonPressed(unsigned int joyStickID, unsigned int button)
+    {
+        assert(joyStickID < joyStickHandler_.size());
+        if (joyStickHandler_[joyStickID])
+            joyStickHandler_[joyStickID]->joyStickButtonPressed(joyStickID, button);
+    }
+
+    void SimpleInputState::joyStickButtonReleased(unsigned int joyStickID, unsigned int button)
+    {
+        assert(joyStickID < joyStickHandler_.size());
+        if (joyStickHandler_[joyStickID])
+            joyStickHandler_[joyStickID]->joyStickButtonReleased(joyStickID, button);
+    }
+
+    void SimpleInputState::joyStickButtonHeld(unsigned int joyStickID, unsigned int button)
+    {
+        assert(joyStickID < joyStickHandler_.size());
+        if (joyStickHandler_[joyStickID])
+            joyStickHandler_[joyStickID]->joyStickButtonHeld(joyStickID, button);
+    }
+
+    /**
+    @brief
+        Adds a joy stick handler.
+    @param handler
+        Pointer to the handler object.
+    @param joyStickID
+        ID of the joy stick
+    @return
+        True if added, false otherwise.
+    */
+    bool SimpleInputState::setJoyStickHandler(JoyStickHandler* handler, unsigned int joyStickID)
+    {
+        if (joyStickID >= joyStickHandler_.size())
+            return false;
+
+        joyStickHandler_[joyStickID] = handler;
+        update();
+        return true;
+    }
+
+    /**
+    @brief
+        Adds a joy stick handler.
+    @param handler
+        Pointer to the handler object.
+    @return
+        True if added, false if handler already existed.
+    */
+    bool SimpleInputState::setJoyStickHandler(JoyStickHandler* handler)
+    {
+        if (handler == joyStickHandlerAll_)
+            return false;
+
+        joyStickHandlerAll_ = handler;
+        for (unsigned int iJoyStick = 0; iJoyStick < joyStickHandler_.size(); ++iJoyStick)
+            setJoyStickHandler(handler, iJoyStick);
+        update();
+        return true;
+    }
+
+    void SimpleInputState::removeAndDestroyAllHandlers()
+    {
+        for (std::vector<InputTickable*>::iterator it = allHandlers_.begin();
+            it != allHandlers_.end(); ++it)
+            delete *it;
+
+        allHandlers_.clear();
+        keyHandler_ = 0;
+        mouseHandler_ = 0;
+        joyStickHandlerAll_ = 0;
+        for (unsigned int iJoyStick = 0; iJoyStick < joyStickHandler_.size(); ++iJoyStick)
+            joyStickHandler_[iJoyStick] = 0;
+
+        update();
+    }
+
+    /**
+    @brief
+        Adds a handler of any kind. dynamic_cast determines to which list it is added.
+    @param handler
+        Pointer to the handler object.
+    @return
+        True if added, false if handler already existed.
+    */
+    bool SimpleInputState::setHandler(InputTickable* handler)
+    {
+        setKeyHandler(dynamic_cast<KeyHandler*>(handler));
+        setMouseHandler(dynamic_cast<MouseHandler*>(handler));
+        return setJoyStickHandler(dynamic_cast<JoyStickHandler*>(handler));
+    }
+
+    void SimpleInputState::tickInput(float dt)
+    {
+        for (unsigned int i = 0; i < allHandlers_.size(); ++i)
+        {
+            allHandlers_[i]->tickInput(dt);
+        }
+    }
+
+    void SimpleInputState::tickInput(float dt, unsigned int device)
+    {
+        switch (device)
+        {
+        case Keyboard:
+            if (keyHandler_)
+                keyHandler_->tickKey(dt);
+            break;
+
+        case Mouse:
+            if (mouseHandler_)
+                mouseHandler_->tickMouse(dt);
+            break;
+
+        default: // joy sticks
+            if (joyStickHandler_[device - 2])
+                joyStickHandler_[device - 2]->tickJoyStick(dt, device - 2);
+            break;
+        }
+    }
+
+    void SimpleInputState::update()
+    {
+        // we can use a set to have a list of unique pointers (an object can implement all 3 handlers)
+        std::set<InputTickable*> tempSet;
+        if (keyHandler_)
+            tempSet.insert(keyHandler_);
+        if (mouseHandler_)
+            tempSet.insert(mouseHandler_);
+        for (unsigned int iJoyStick = 0; iJoyStick < joyStickHandler_.size(); iJoyStick++)
+            if (joyStickHandler_[iJoyStick])
+                tempSet.insert(joyStickHandler_[iJoyStick]);
+
+        // copy the content of the map back to the actual vector
+        allHandlers_.clear();
+        for (std::set<InputTickable*>::const_iterator itHandler = tempSet.begin();
+            itHandler != tempSet.end(); itHandler++)
+            allHandlers_.push_back(*itHandler);
+
+        // update the deviceEnabled options
+        setInputDeviceEnabled(Keyboard, (keyHandler_ != 0));
+        setInputDeviceEnabled(Mouse, (mouseHandler_ != 0));
+        for (unsigned int i = 0; i < joyStickHandler_.size(); ++i)
+            setInputDeviceEnabled(2 + i, (joyStickHandler_[i] != 0));
+    }
+}
Index: code/branches/gui/src/core/input/SimpleInputState.h
===================================================================
--- code/branches/gui/src/core/input/SimpleInputState.h	(revision 1638)
+++ code/branches/gui/src/core/input/SimpleInputState.h	(revision 1638)
@@ -0,0 +1,90 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+@file
+@brief 
+*/
+
+#ifndef _SimpleInputState_H__
+#define _SimpleInputState_H__
+
+#include "core/CorePrereqs.h"
+
+#include <vector>
+#include "InputInterfaces.h"
+#include "InputState.h"
+
+namespace orxonox
+{
+
+    class _CoreExport SimpleInputState : public InputState
+    {
+
+    public:
+        SimpleInputState();
+        ~SimpleInputState() { }
+
+        void setKeyHandler        (KeyHandler* handler) { keyHandler_ = handler; update(); }
+        void setMouseHandler      (MouseHandler* handler) { mouseHandler_ = handler; update(); }
+        bool setJoyStickHandler   (JoyStickHandler* handler, unsigned int joyStickID);
+        bool setJoyStickHandler   (JoyStickHandler* handler);
+        bool setHandler(InputTickable* handler);
+        void removeAndDestroyAllHandlers();
+
+    private:
+        void tickInput(float dt);
+        void tickInput(float dt, unsigned int device);
+
+        void keyPressed (const KeyEvent& evt);
+        void keyReleased(const KeyEvent& evt);
+        void keyHeld    (const KeyEvent& evt);
+
+        void mouseButtonPressed (MouseButton::Enum id);
+        void mouseButtonReleased(MouseButton::Enum id);
+        void mouseButtonHeld    (MouseButton::Enum id);
+        void mouseMoved         (IntVector2 abs, IntVector2 rel, IntVector2 clippingSize);
+        void mouseScrolled      (int abs, int rel);
+
+        void joyStickButtonPressed (unsigned int joyStickID, unsigned int button);
+        void joyStickButtonReleased(unsigned int joyStickID, unsigned int button);
+        void joyStickButtonHeld    (unsigned int joyStickID, unsigned int button);
+        void joyStickAxisMoved     (unsigned int joyStickID, unsigned int axis, float value);
+
+        void update();
+        void numberOfJoySticksChanged(unsigned int n);
+
+        KeyHandler*                   keyHandler_;
+        MouseHandler*                 mouseHandler_;
+        std::vector<JoyStickHandler*> joyStickHandler_;
+        JoyStickHandler*              joyStickHandlerAll_;
+        std::vector<InputTickable*>   allHandlers_;
+    };
+}
+
+#endif /* _SimpleInputState_H__ */
Index: code/branches/gui/src/core/tolua/tolua.pkg
===================================================================
--- code/branches/gui/src/core/tolua/tolua.pkg	(revision 1636)
+++ code/branches/gui/src/core/tolua/tolua.pkg	(revision 1638)
@@ -1,1 +1,2 @@
 $cfile "../../src/core/Script_clean.h"
+$cfile "../../src/core/CommandExecutor.h"
Index: code/branches/gui/src/network/Client.cc
===================================================================
--- code/branches/gui/src/network/Client.cc	(revision 1636)
+++ code/branches/gui/src/network/Client.cc	(revision 1638)
@@ -227,9 +227,9 @@
   void Client::processClassid(classid *clid){
     orxonox::Identifier *id;
-    id=ID(std::string(clid->message));
+    id=GetIdentifier(std::string(clid->message));
     if(id!=NULL)
       id->setNetworkID(clid->clid);
     COUT(4) << "Client: received and set network id: " << clid->clid << "; classname: " << clid->message << std::endl;
-    COUT(4) << "id(classid)->getName " << ID((unsigned int)clid->clid)->getName() << std::endl;
+    COUT(4) << "id(classid)->getName " << GetIdentifier((unsigned int)clid->clid)->getName() << std::endl;
     delete clid;
     return;
Index: code/branches/gui/src/network/ClientConnection.cc
===================================================================
--- code/branches/gui/src/network/ClientConnection.cc	(revision 1636)
+++ code/branches/gui/src/network/ClientConnection.cc	(revision 1638)
@@ -42,4 +42,5 @@
 #include <iostream>
 // boost.thread library for multithreading support
+#include <boost/thread/thread.hpp>
 #include <boost/bind.hpp>
 
Index: code/branches/gui/src/network/ClientConnection.h
===================================================================
--- code/branches/gui/src/network/ClientConnection.h	(revision 1636)
+++ code/branches/gui/src/network/ClientConnection.h	(revision 1638)
@@ -45,7 +45,8 @@
 #include <string>
 #include <enet/enet.h>
-#include <boost/thread/thread.hpp>
+#include <boost/thread/recursive_mutex.hpp>
+#include "PacketBuffer.h"
 
-#include "PacketBuffer.h"
+namespace boost { class thread; }
 
 namespace network
Index: code/branches/gui/src/network/ConnectionManager.cc
===================================================================
--- code/branches/gui/src/network/ConnectionManager.cc	(revision 1636)
+++ code/branches/gui/src/network/ConnectionManager.cc	(revision 1638)
@@ -40,4 +40,5 @@
 #include <iostream>
 // boost.thread library for multithreading support
+#include <boost/thread/thread.hpp>
 #include <boost/bind.hpp>
 
Index: code/branches/gui/src/network/ConnectionManager.h
===================================================================
--- code/branches/gui/src/network/ConnectionManager.h	(revision 1636)
+++ code/branches/gui/src/network/ConnectionManager.h	(revision 1638)
@@ -47,9 +47,10 @@
 // enet library for networking support
 #include <enet/enet.h>
-#include <boost/thread/thread.hpp>
 #include <boost/thread/recursive_mutex.hpp>
 
 #include "PacketBuffer.h"
 #include "PacketManager.h"
+
+namespace boost { class thread; }
 
 namespace std
Index: code/branches/gui/src/network/GameStateClient.cc
===================================================================
--- code/branches/gui/src/network/GameStateClient.cc	(revision 1636)
+++ code/branches/gui/src/network/GameStateClient.cc	(revision 1638)
@@ -177,5 +177,5 @@
           ///sigsegv may happen here again for some reason
           ///sigsegv is receved after the COUT(4) above
-          orxonox::Identifier* id = ID((unsigned int)sync.classID);
+          orxonox::Identifier* id = GetIdentifier((unsigned int)sync.classID);
           if(!id){
             COUT(3) << "We could not identify a new object; classid: " << sync.classID << " uint: " << (unsigned int)sync.classID << " objectID: " << sync.objectID << " size: " << sync.length << std::endl;
Index: code/branches/gui/src/network/GameStateManager.cc
===================================================================
--- code/branches/gui/src/network/GameStateManager.cc	(revision 1636)
+++ code/branches/gui/src/network/GameStateManager.cc	(revision 1638)
@@ -44,5 +44,5 @@
 #include <iostream>
 #include <zlib.h>
-#include <assert.h>
+#include <cassert>
 
 #include "core/CoreIncludes.h"
@@ -278,5 +278,5 @@
         COUT(4) << "loadsnapshot: creating new object " << std::endl;
         //COUT(4) << "loadSnapshot:\tclassid: " << sync.classID << ", name: " << ID((unsigned int) sync.classID)->getName() << std::endl;
-        orxonox::Identifier* id = ID((unsigned int)sync.classID);
+        orxonox::Identifier* id = GetIdentifier((unsigned int)sync.classID);
         if(!id){
           COUT(4) << "We could not identify a new object; classid: " << sync.classID << std::endl;
Index: code/branches/gui/src/network/Server.cc
===================================================================
--- code/branches/gui/src/network/Server.cc	(revision 1636)
+++ code/branches/gui/src/network/Server.cc	(revision 1638)
@@ -42,4 +42,5 @@
 
 #include <iostream>
+#include <cassert>
 
 
@@ -370,5 +371,5 @@
     if(!client)
       return false;
-    orxonox::Identifier* id = ID("SpaceShip");
+    orxonox::Identifier* id = GetIdentifier("SpaceShip");
     if(!id){
       COUT(4) << "We could not create the SpaceShip for client: " << client->getID() << std::endl;
Index: code/branches/gui/src/orxonox/GraphicsEngine.cc
===================================================================
--- code/branches/gui/src/orxonox/GraphicsEngine.cc	(revision 1636)
+++ code/branches/gui/src/orxonox/GraphicsEngine.cc	(revision 1638)
@@ -27,8 +27,9 @@
  */
 
- /**
-    @file orxonox.cc
-    @brief Orxonox class
-  */
+/**
+@file
+@brief
+    Implementation of an partial interface to Ogre.
+*/
 
 #include "OrxonoxStableHeaders.h"
@@ -50,4 +51,5 @@
 #include "core/CommandExecutor.h"
 #include "core/ConsoleCommand.h"
+#include "core/Exception.h"
 
 #include "overlays/console/InGameConsole.h"
@@ -57,423 +59,444 @@
 #include "tools/WindowEventListener.h"
 
+#include "objects/CameraHandler.h"
 
 namespace orxonox
 {
-  /**
-    @brief Returns the singleton instance and creates it the first time.
-    @return The only instance of GraphicsEngine.
-  */
-  /*static*/ GraphicsEngine& GraphicsEngine::getSingleton()
-  {
-    static GraphicsEngine theOnlyInstance;
-    return theOnlyInstance;
-  }
-
-  /**
-    @brief Only use constructor to initialise variables and pointers!
-  */
-  GraphicsEngine::GraphicsEngine() :
-    root_(0),
-    scene_(0),
-    renderWindow_(0)
-  {
-    RegisterObject(GraphicsEngine);
-
-    this->detailLevelParticle_ = 0;
-
-    this->setConfigValues();
-    CCOUT(4) << "Constructed" << std::endl;
-  }
-
-  void GraphicsEngine::setConfigValues()
-  {
-    SetConfigValue(resourceFile_,    "resources.cfg").description("Location of the resources file in the data path.");
-    SetConfigValue(ogreConfigFile_,  "ogre.cfg").description("Location of the Ogre config file");
-    SetConfigValue(ogrePluginsFile_, "plugins.cfg").description("Location of the Ogre plugins file");
-    SetConfigValue(ogreLogFile_,     "ogre.log").description("Logfile for messages from Ogre. \
-                                                             Use \"\" to suppress log file creation.");
-    SetConfigValue(ogreLogLevelTrivial_ , 5).description("Corresponding orxonox debug level for ogre Trivial");
-    SetConfigValue(ogreLogLevelNormal_  , 4).description("Corresponding orxonox debug level for ogre Normal");
-    SetConfigValue(ogreLogLevelCritical_, 2).description("Corresponding orxonox debug level for ogre Critical");
-
-    unsigned int old = this->detailLevelParticle_;
-    SetConfigValue(detailLevelParticle_, 2).description("O: off, 1: low, 2: normal, 3: high");
-
-    if (this->detailLevelParticle_ != old)
-      for (Iterator<ParticleInterface> it = ObjectList<ParticleInterface>::begin(); it; ++it)
-        it->detailLevelChanged(this->detailLevelParticle_);
-  }
-
-  /**
-    @brief Called after main() --> call destroyObjects()!
-  */
-  GraphicsEngine::~GraphicsEngine()
-  {
-    this->destroy();
-  }
-
-  /**
-    @brief Destroys all the internal objects. Call this method when you
-           normally would call the destructor.
-  */
-  void GraphicsEngine::destroy()
-  {
-    CCOUT(4) << "Destroying objects..." << std::endl;
-    Ogre::WindowEventUtilities::removeWindowEventListener(this->renderWindow_, this);
-    if (this->root_)
-      delete this->root_;
-    this->root_ = 0;
-    this->scene_ = 0;
-    this->renderWindow_ = 0;
-    // delete the ogre log and the logManager (since we have created it).
-    if (Ogre::LogManager::getSingletonPtr() != 0)
-    {
-      Ogre::LogManager::getSingleton().getDefaultLog()->removeListener(this);
-      Ogre::LogManager::getSingleton().destroyLog(Ogre::LogManager::getSingleton().getDefaultLog());
-      delete Ogre::LogManager::getSingletonPtr();
-    }
-    CCOUT(4) << "Destroying objects done" << std::endl;
-  }
-
-  /**
-    @brief Creates the Ogre Root object and sets up the ogre log.
-  */
-  bool GraphicsEngine::setup()
-  {
-    CCOUT(3) << "Setting up..." << std::endl;
-    // temporary overwrite of dataPath, change ini file for permanent change
-
-// TODO: LogManager doesn't work on specific systems. The why is unknown yet.
+    GraphicsEngine* GraphicsEngine::singletonRef_s = 0;
+
+    /**
+    @brief
+        Returns the singleton instance.
+    @return
+        The only instance of GraphicsEngine.
+    */
+    /*static*/ GraphicsEngine& GraphicsEngine::getSingleton()
+    {
+        assert(singletonRef_s);
+        return *singletonRef_s;
+    }
+
+    /**
+    @brief
+        Non-initialising constructor.
+    */
+    GraphicsEngine::GraphicsEngine()
+        : root_(0)
+        , renderWindow_(0)
+        , levelSceneManager_(0)
+        , levelViewport_(0)
+    {
+        RegisterObject(GraphicsEngine);
+
+        singletonRef_s = this;
+
+        this->detailLevelParticle_ = 0;
+
+        this->setConfigValues();
+        CCOUT(4) << "Constructed" << std::endl;
+    }
+
+    void GraphicsEngine::setConfigValues()
+    {
+        SetConfigValue(resourceFile_,    "resources.cfg").description("Location of the resources file in the data path.");
+        SetConfigValue(ogreConfigFile_,  "ogre.cfg").description("Location of the Ogre config file");
+        SetConfigValue(ogrePluginsFile_, "plugins.cfg").description("Location of the Ogre plugins file");
+        SetConfigValue(ogreLogFile_,     "ogre.log").description("Logfile for messages from Ogre. \
+                                                                 Use \"\" to suppress log file creation.");
+        SetConfigValue(ogreLogLevelTrivial_ , 5).description("Corresponding orxonox debug level for ogre Trivial");
+        SetConfigValue(ogreLogLevelNormal_  , 4).description("Corresponding orxonox debug level for ogre Normal");
+        SetConfigValue(ogreLogLevelCritical_, 2).description("Corresponding orxonox debug level for ogre Critical");
+
+        unsigned int old = this->detailLevelParticle_;
+        SetConfigValue(detailLevelParticle_, 2).description("O: off, 1: low, 2: normal, 3: high");
+
+        if (this->detailLevelParticle_ != old)
+            for (Iterator<ParticleInterface> it = ObjectList<ParticleInterface>::begin(); it; ++it)
+                it->detailLevelChanged(this->detailLevelParticle_);
+    }
+
+    /**
+    @brief
+        Destroys all the Ogre related objects
+    */
+    GraphicsEngine::~GraphicsEngine()
+    {
+        CCOUT(4) << "Destroying objects..." << std::endl;
+        Ogre::WindowEventUtilities::removeWindowEventListener(this->renderWindow_, this);
+        if (this->root_)
+            delete this->root_;
+        this->root_ = 0;
+        this->levelSceneManager_ = 0;
+        this->renderWindow_ = 0;
+
 #if ORXONOX_PLATFORM == ORXONOX_PLATFORM_WIN32
-    // create a logManager
-    // note: If there's already a logManager, Ogre will complain by a failed assertation.
-    // but that shouldn't happen, since this is the first time to create a logManager..
-    Ogre::LogManager* logger = new Ogre::LogManager();
-    CCOUT(4) << "Ogre LogManager created" << std::endl;
-
-    // create our own log that we can listen to
-    Ogre::Log *myLog;
-    if (this->ogreLogFile_ == "")
-      myLog = logger->createLog("ogre.log", true, false, true);
-    else
-      myLog = logger->createLog(this->ogreLogFile_, true, false, false);
-    CCOUT(4) << "Ogre Log created" << std::endl;
-
-    myLog->setLogDetail(Ogre::LL_BOREME);
-    myLog->addListener(this);
+        // delete the ogre log and the logManager (since we have created it).
+        if (Ogre::LogManager::getSingletonPtr() != 0)
+        {
+            Ogre::LogManager::getSingleton().getDefaultLog()->removeListener(this);
+            Ogre::LogManager::getSingleton().destroyLog(Ogre::LogManager::getSingleton().getDefaultLog());
+            delete Ogre::LogManager::getSingletonPtr();
+        }
+        CCOUT(4) << "Destroying objects done" << std::endl;
 #endif
 
-    // Root will detect that we've already created a Log
-    CCOUT(4) << "Creating Ogre Root..." << std::endl;
-
-    if (ogrePluginsFile_ == "")
-    {
-      COUT(1) << "Error: Ogre plugins file set to \"\". Cannot load." << std::endl;
-      return false;
-    }
-    if (ogreConfigFile_ == "")
-    {
-      COUT(1) << "Error: Ogre config file set to \"\". Cannot load." << std::endl;
-      return false;
-    }
-    if (ogreLogFile_ == "")
-    {
-      COUT(1) << "Error: Ogre log file set to \"\". Cannot load." << std::endl;
-      return false;
-    }
-
-    try
-    {
-      root_ = new Ogre::Root(ogrePluginsFile_, ogreConfigFile_, ogreLogFile_);
-    }
-    catch (Ogre::Exception ex)
-    {
-      COUT(2) << "Error: There was an exception when creating Ogre Root." << std::endl;
-      return false;
-    }
-
-    if (!root_->getInstalledPlugins().size())
-    {
-      COUT(1) << "Error: No plugins declared. Cannot load Ogre." << std::endl;
-      COUT(0) << "Is the plugins file correctly declared?" << std::endl;
-      return false;
-    }
-
-#if 0
-    // tame the ogre ouput so we don't get all the mess in the console
-    Ogre::Log* defaultLog = Ogre::LogManager::getSingleton().getDefaultLog();
-    defaultLog->setDebugOutputEnabled(false);
-    defaultLog->setLogDetail(Ogre::LL_BOREME);
-    defaultLog->addListener(this);
+        singletonRef_s = 0;
+    }
+
+    /**
+    @brief
+        Creates the Ogre Root object and sets up the ogre log.
+    */
+    void GraphicsEngine::setup()
+    {
+        CCOUT(3) << "Setting up..." << std::endl;
+
+        // TODO: LogManager doesn't work on linux platform. The why is yet unknown.
+#if ORXONOX_PLATFORM == ORXONOX_PLATFORM_WIN32
+        // create a new logManager
+        Ogre::LogManager* logger = new Ogre::LogManager();
+        CCOUT(4) << "Ogre LogManager created" << std::endl;
+
+        // create our own log that we can listen to
+        Ogre::Log *myLog;
+        if (this->ogreLogFile_ == "")
+            myLog = logger->createLog("ogre.log", true, false, true);
+        else
+            myLog = logger->createLog(this->ogreLogFile_, true, false, false);
+        CCOUT(4) << "Ogre Log created" << std::endl;
+
+        myLog->setLogDetail(Ogre::LL_BOREME);
+        myLog->addListener(this);
 #endif
 
-    CCOUT(4) << "Creating Ogre Root done" << std::endl;
-
-    // specify where Ogre has to look for resources. This call doesn't parse anything yet!
-    if (!declareRessourceLocations())
-      return false;
-
-    CCOUT(3) << "Set up done." << std::endl;
-    return true;
-  }
-
-  bool GraphicsEngine::declareRessourceLocations()
-  {
-    CCOUT(4) << "Declaring Resources" << std::endl;
-    //TODO: Specify layout of data file and maybe use xml-loader
-    //TODO: Work with ressource groups (should be generated by a special loader)
-
-    if (resourceFile_ == "")
-    {
-      COUT(1) << "Error: Resource file set to \"\". Cannot load." << std::endl;
-      return false;
-    }
-
-    // Load resource paths from data file using configfile ressource type
-    Ogre::ConfigFile cf;
-    try
-    {
-      cf.load(Settings::getDataPath() + resourceFile_);
-    }
-    catch (Ogre::Exception ex)
-    {
-      COUT(1) << "Error: Could not load resources.cfg in path " << Settings::getDataPath() << std::endl;
-      COUT(0) << "Have you forgotten to set the data path in orxnox.ini?" << std::endl;
-      return false;
-    }
-
-    // Go through all sections & settings in the file
-    Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
-
-    std::string secName, typeName, archName;
-    while (seci.hasMoreElements())
-    {
-      try
-      {
-        secName = seci.peekNextKey();
-        Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
-        Ogre::ConfigFile::SettingsMultiMap::iterator i;
-        for (i = settings->begin(); i != settings->end(); ++i)
-        {
-          typeName = i->first; // for instance "FileSystem" or "Zip"
-          archName = i->second; // name (and location) of archive
-
-          Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
-              std::string(Settings::getDataPath() + archName), typeName, secName);
-        }
-      }
-      catch (Ogre::Exception ex)
-      {
-        COUT(2) << "Exception while reading resources.cfg. Proceeding.." << ex.getDescription() << std::endl;
-      }
-    }
-    return true;
-  }
-
-  bool GraphicsEngine::loadRenderer()
-  {
-    CCOUT(4) << "Configuring Renderer" << std::endl;
-
-    // check for file existence because Ogre displays exceptions if not
-    std::ifstream probe;
-    probe.open(ogreConfigFile_.c_str());
-    if (!probe)
-    {
-      // create a zero sized file
-      std::ofstream creator;
-      creator.open(ogreConfigFile_.c_str());
-      creator.close();
-    }
-    else
-      probe.close();
-
-    if (!root_->restoreConfig())
-      if (!root_->showConfigDialog())
-        return false;
-
-    CCOUT(4) << "Creating render window" << std::endl;
-    try
-    {
-      this->renderWindow_ = root_->initialise(true, "OrxonoxV2");
-    }
-    catch (Ogre::Exception ex)
-    {
-      COUT(2) << "Error: There was an exception when initialising Ogre Root." << std::endl;
-      return false;
-    }
-
-    if (!root_->isInitialised())
-    {
-      CCOUT(2) << "Error: Initialising Ogre root object failed." << std::endl;
-      return false;
-    }
-    Ogre::WindowEventUtilities::addWindowEventListener(this->renderWindow_, this);
-    Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
-    return true;
-  }
-
-  bool GraphicsEngine::initialiseResources()
-  {
-    CCOUT(4) << "Initialising resources" << std::endl;
-    //TODO: Do NOT load all the groups, why are we doing that? And do we really do that? initialise != load...
-    try
-    {
-      Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
-      /*Ogre::StringVector str = Ogre::ResourceGroupManager::getSingleton().getResourceGroups();
-      for (unsigned int i = 0; i < str.size(); i++)
-      {
-        Ogre::ResourceGroupManager::getSingleton().loadResourceGroup(str[i]);
-      }*/
-    }
-    catch (Ogre::Exception e)
-    {
-      CCOUT(2) << "Error: There was an Error when initialising the resources." << std::endl;
-      CCOUT(2) << "ErrorMessage: " << e.getFullDescription() << std::endl;
-      return false;
-    }
-    return true;
-  }
-
-  /**
-   * @brief Creates the SceneManager
-   */
-  bool GraphicsEngine::createNewScene()
-  {
-    CCOUT(4) << "Creating new SceneManager..." << std::endl;
-    if (scene_)
-    {
-      CCOUT(2) << "SceneManager already exists! Skipping." << std::endl;
-      return false;
-    }
-    scene_ = root_->createSceneManager(Ogre::ST_GENERIC, "Default SceneManager");
-    CCOUT(3) << "Created SceneManager: " << scene_ << std::endl;
-    return true;
-  }
-
-  /**
-    Returns the window handle of the render window.
-    At least the InputHandler uses this to create the OIS::InputManager
-    @return The window handle of the render window
-  */
-  size_t GraphicsEngine::getWindowHandle()
-  {
-    if (this->renderWindow_)
-    {
-      size_t windowHnd = 0;
-      this->renderWindow_->getCustomAttribute("WINDOW", &windowHnd);
-      return windowHnd;
-    }
-    else
-      return 0;
-  }
-
-  /**
-    Get the width of the current render window
-    @return The width of the current render window
-  */
-  int GraphicsEngine::getWindowWidth() const
-  {
-    if (this->renderWindow_)
-      return this->renderWindow_->getWidth();
-    else
-      return 0;
-  }
-
-  /**
-    Get the height of the current render window
-    @return The height of the current render window
-  */
-  int GraphicsEngine::getWindowHeight() const
-  {
-    if (this->renderWindow_)
-      return this->renderWindow_->getHeight();
-    else
-      return 0;
-  }
-
-  /**
-    @brief Returns the window aspect ratio height/width.
-    @return The ratio
-  */
-  float GraphicsEngine::getWindowAspectRatio() const
-  {
-    if (this->renderWindow_)
-        return (float)this->renderWindow_->getHeight() / (float)this->renderWindow_->getWidth();
-    else
-        return 1.0f;
-  }
-
-  /**
-    @brief Method called by the LogListener interface from Ogre.
-    We use it to capture Ogre log messages and handle it ourselves.
-    @param message The message to be logged
-    @param lml The message level the log is using
-    @param maskDebug If we are printing to the console or not
-    @param logName the name of this log (so you can have several listeners
-                   for different logs, and identify them)
-  */
-  void GraphicsEngine::messageLogged(const std::string& message,
-    Ogre::LogMessageLevel lml, bool maskDebug, const std::string &logName)
-  {
-    int orxonoxLevel;
-    switch (lml)
-    {
-      case Ogre::LML_TRIVIAL:
-        orxonoxLevel = this->ogreLogLevelTrivial_;
-        break;
-      case Ogre::LML_NORMAL:
-        orxonoxLevel = this->ogreLogLevelNormal_;
-        break;
-      case Ogre::LML_CRITICAL:
-        orxonoxLevel = this->ogreLogLevelCritical_;
-        break;
-      default:
-        orxonoxLevel = 0;
-    }
-    OutputHandler::getOutStream().setOutputLevel(orxonoxLevel)
-        << "Ogre: " << message << std::endl;
-  }
-
-  /**
-  * Window has moved.
-  * @param rw The render window it occured in
-  */
-  void GraphicsEngine::windowMoved(Ogre::RenderWindow *rw)
-  {
-    for (Iterator<orxonox::WindowEventListener> it = ObjectList<orxonox::WindowEventListener>::start(); it; ++it)
-      it->windowMoved();
-  }
-
-  /**
-  * Window has resized.
-  * @param rw The render window it occured in
-  * @note GraphicsEngine has a render window stored itself. This is the same
-  *       as rw. But we have to be careful when using multiple render windows!
-  */
-  void GraphicsEngine::windowResized(Ogre::RenderWindow *rw)
-  {
-    for (Iterator<orxonox::WindowEventListener> it = ObjectList<orxonox::WindowEventListener>::start(); it; ++it)
-      it->windowResized(this->renderWindow_->getWidth(), this->renderWindow_->getHeight());
-  }
-
-  /**
-  * Window has changed Focus.
-  * @param rw The render window it occured in
-  */
-  void GraphicsEngine::windowFocusChanged(Ogre::RenderWindow *rw)
-  {
-    for (Iterator<orxonox::WindowEventListener> it = ObjectList<orxonox::WindowEventListener>::start(); it; ++it)
-      it->windowFocusChanged();
-  }
-
-  /**
-  * Window was closed.
-  * @param rw The render window it occured in
-  */
-  void GraphicsEngine::windowClosed(Ogre::RenderWindow *rw)
-  {
-    // using CommandExecutor in order to avoid depending on Orxonox.h.
-    CommandExecutor::execute("exit", false);
-  }
+        // Root will detect that we've already created a Log
+        CCOUT(4) << "Creating Ogre Root..." << std::endl;
+
+        if (ogrePluginsFile_ == "")
+        {
+            COUT(2) << "Warning: Ogre plugins file set to \"\". Defaulting to plugins.cfg" << std::endl;
+            ModifyConfigValue(ogrePluginsFile_, tset, "plugins.cfg");
+        }
+        if (ogreConfigFile_ == "")
+        {
+            COUT(2) << "Warning: Ogre config file set to \"\". Defaulting to config.cfg" << std::endl;
+            ModifyConfigValue(ogreConfigFile_, tset, "config.cfg");
+        }
+        if (ogreLogFile_ == "")
+        {
+            COUT(2) << "Warning: Ogre log file set to \"\". Defaulting to ogre.log" << std::endl;
+            ModifyConfigValue(ogreLogFile_, tset, "ogre.log");
+        }
+
+        root_ = new Ogre::Root(ogrePluginsFile_, ogreConfigFile_, ogreLogFile_);
+
+        if (!root_->getInstalledPlugins().size())
+        {
+            ThrowException(PluginsNotFound, "No Ogre plugins declared. Cannot load Ogre.");
+        }
+
+#if 0 // Ogre 1.4.3 doesn't support setDebugOutputEnabled(.)
+//#if ORXONOX_PLATFORM != ORXONOX_PLATFORM_WIN32
+        // tame the ogre ouput so we don't get all the mess in the console
+        Ogre::Log* defaultLog = Ogre::LogManager::getSingleton().getDefaultLog();
+        defaultLog->setDebugOutputEnabled(false);
+        defaultLog->setLogDetail(Ogre::LL_BOREME);
+        defaultLog->addListener(this);
+#endif
+
+        CCOUT(4) << "Creating Ogre Root done" << std::endl;
+
+        // specify where Ogre has to look for resources. This call doesn't parse anything yet!
+        declareRessourceLocations();
+
+        CCOUT(3) << "Set up done." << std::endl;
+    }
+
+    void GraphicsEngine::declareRessourceLocations()
+    {
+        CCOUT(4) << "Declaring Resources" << std::endl;
+        //TODO: Specify layout of data file and maybe use xml-loader
+        //TODO: Work with ressource groups (should be generated by a special loader)
+
+        if (resourceFile_ == "")
+        {
+            COUT(2) << "Warning: Ogre resource file set to \"\". Defaulting to resources.cfg" << std::endl;
+            ModifyConfigValue(resourceFile_, tset, "resources.cfg");
+        }
+
+        // Load resource paths from data file using configfile ressource type
+        Ogre::ConfigFile cf;
+        try
+        {
+            cf.load(Settings::getDataPath() + resourceFile_);
+        }
+        catch (Ogre::Exception& ex)
+        {
+            COUT(1) << ex.getFullDescription() << std::endl;
+            COUT(0) << "Have you forgotten to set the data path in orxnox.ini?" << std::endl;
+            throw;
+        }
+
+        // Go through all sections & settings in the file
+        Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
+
+        std::string secName, typeName, archName;
+        while (seci.hasMoreElements())
+        {
+            try
+            {
+                secName = seci.peekNextKey();
+                Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
+                Ogre::ConfigFile::SettingsMultiMap::iterator i;
+                for (i = settings->begin(); i != settings->end(); ++i)
+                {
+                    typeName = i->first; // for instance "FileSystem" or "Zip"
+                    archName = i->second; // name (and location) of archive
+
+                    Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
+                        std::string(Settings::getDataPath() + archName), typeName, secName);
+                }
+            }
+            catch (Ogre::Exception& ex)
+            {
+                COUT(1) << ex.getFullDescription() << std::endl;
+            }
+        }
+    }
+
+    bool GraphicsEngine::loadRenderer()
+    {
+        CCOUT(4) << "Configuring Renderer" << std::endl;
+
+        // check for file existence because Ogre displays exceptions if not
+        std::ifstream probe;
+        probe.open(ogreConfigFile_.c_str());
+        if (!probe)
+        {
+            // create a zero sized file
+            std::ofstream creator;
+            creator.open(ogreConfigFile_.c_str());
+            creator.close();
+        }
+        else
+            probe.close();
+
+        if (!root_->restoreConfig())
+            if (!root_->showConfigDialog())
+                return false;
+
+        CCOUT(4) << "Creating render window" << std::endl;
+        try
+        {
+            this->renderWindow_ = root_->initialise(true, "OrxonoxV2");
+        }
+        catch (...)
+        {
+            COUT(2) << "Error: There was an exception when initialising Ogre Root." << std::endl;
+            return false;
+        }
+
+        if (!root_->isInitialised())
+        {
+            CCOUT(2) << "Error: Initialising Ogre root object failed." << std::endl;
+            return false;
+        }
+        Ogre::WindowEventUtilities::addWindowEventListener(this->renderWindow_, this);
+        //Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
+
+        // create a full screen viewport in which to render the scene and the loading screen
+        // The GUI uses its own one to be able to render on top of everything.
+        // That explains why the Z order here is only 1 and not 0 (top most)
+        this->levelViewport_ = this->renderWindow_->addViewport(0, 1);
+
+        return true;
+    }
+
+    bool GraphicsEngine::initialiseResources()
+    {
+        CCOUT(4) << "Initialising resources" << std::endl;
+        //TODO: Do NOT load all the groups, why are we doing that? And do we really do that? initialise != load...
+        try
+        {
+            Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
+            /*Ogre::StringVector str = Ogre::ResourceGroupManager::getSingleton().getResourceGroups();
+            for (unsigned int i = 0; i < str.size(); i++)
+            {
+            Ogre::ResourceGroupManager::getSingleton().loadResourceGroup(str[i]);
+            }*/
+        }
+        catch (Ogre::Exception& e)
+        {
+            CCOUT(2) << "Error: There was an Error when initialising the resources." << std::endl;
+            CCOUT(2) << "ErrorMessage: " << e.getFullDescription() << std::endl;
+            return false;
+        }
+        return true;
+    }
+
+    /**
+    @brief
+        Creates the SceneManager
+    */
+    bool GraphicsEngine::createNewScene()
+    {
+        CCOUT(4) << "Creating new SceneManager..." << std::endl;
+        if (levelSceneManager_)
+        {
+            CCOUT(2) << "SceneManager already exists! Skipping." << std::endl;
+            return false;
+        }
+        this->levelSceneManager_ = this->root_->createSceneManager(Ogre::ST_GENERIC, "LevelSceneManager");
+        CCOUT(3) << "Created SceneManager: " << levelSceneManager_ << std::endl;
+        return true;
+    }
+
+    /**
+    @brief
+        Returns the window handle of the render window.
+        At least the InputHandler uses this to create the OIS::InputManager
+    @return
+        The window handle of the render window
+    */
+    size_t GraphicsEngine::getWindowHandle()
+    {
+        if (this->renderWindow_)
+        {
+            size_t windowHnd = 0;
+            this->renderWindow_->getCustomAttribute("WINDOW", &windowHnd);
+            return windowHnd;
+        }
+        else
+            return 0;
+    }
+
+    /**
+    @brief
+        Get the width of the render window
+    @return
+        The width of the render window
+    */
+    int GraphicsEngine::getWindowWidth() const
+    {
+        if (this->renderWindow_)
+            return this->renderWindow_->getWidth();
+        else
+            return 0;
+    }
+
+    /**
+    @brief
+        Get the height of the render window
+    @return
+        The height of the render window
+    */
+    int GraphicsEngine::getWindowHeight() const
+    {
+        if (this->renderWindow_)
+            return this->renderWindow_->getHeight();
+        else
+            return 0;
+    }
+
+    /**
+    @brief
+        Returns the window aspect ratio height/width.
+    @return
+        The window aspect ratio
+    */
+    float GraphicsEngine::getWindowAspectRatio() const
+    {
+        if (this->renderWindow_)
+            return (float)this->renderWindow_->getHeight() / (float)this->renderWindow_->getWidth();
+        else
+            return 1.0f;
+    }
+
+    /**
+    @brief
+        Method called by the LogListener interface from Ogre.
+        We use it to capture Ogre log messages and handle it ourselves.
+    @param message
+        The message to be logged
+    @param lml
+        The message level the log is using
+    @param maskDebug
+        If we are printing to the console or not
+    @param logName
+        The name of this log (so you can have several listeners
+        for different logs, and identify them)
+    */
+    void GraphicsEngine::messageLogged(const std::string& message,
+        Ogre::LogMessageLevel lml, bool maskDebug, const std::string &logName)
+    {
+        int orxonoxLevel;
+        switch (lml)
+        {
+        case Ogre::LML_TRIVIAL:
+            orxonoxLevel = this->ogreLogLevelTrivial_;
+            break;
+        case Ogre::LML_NORMAL:
+            orxonoxLevel = this->ogreLogLevelNormal_;
+            break;
+        case Ogre::LML_CRITICAL:
+            orxonoxLevel = this->ogreLogLevelCritical_;
+            break;
+        default:
+            orxonoxLevel = 0;
+        }
+        OutputHandler::getOutStream().setOutputLevel(orxonoxLevel)
+            << "Ogre: " << message << std::endl;
+    }
+
+    /**
+    @brief
+        Window has moved.
+    @param rw
+        The render window it occured in
+    */
+    void GraphicsEngine::windowMoved(Ogre::RenderWindow *rw)
+    {
+        for (Iterator<orxonox::WindowEventListener> it = ObjectList<orxonox::WindowEventListener>::start(); it; ++it)
+            it->windowMoved();
+    }
+
+    /**
+    @brief
+        Window has resized.
+    @param rw
+        The render window it occured in
+    @note
+        GraphicsEngine has a render window stored itself. This is the same
+        as rw. But we have to be careful when using multiple render windows!
+    */
+    void GraphicsEngine::windowResized(Ogre::RenderWindow *rw)
+    {
+        for (Iterator<orxonox::WindowEventListener> it = ObjectList<orxonox::WindowEventListener>::start(); it; ++it)
+            it->windowResized(this->renderWindow_->getWidth(), this->renderWindow_->getHeight());
+    }
+
+    /**
+    @brief
+        Window focus has changed.
+    @param rw
+        The render window it occured in
+    */
+    void GraphicsEngine::windowFocusChanged(Ogre::RenderWindow *rw)
+    {
+        for (Iterator<orxonox::WindowEventListener> it = ObjectList<orxonox::WindowEventListener>::start(); it; ++it)
+            it->windowFocusChanged();
+    }
+
+    /**
+    @brief
+        Window was closed.
+    @param rw
+        The render window it occured in
+    */
+    void GraphicsEngine::windowClosed(Ogre::RenderWindow *rw)
+    {
+        // using CommandExecutor in order to avoid depending on Orxonox.h.
+        CommandExecutor::execute("exit", false);
+    }
 
 }
Index: code/branches/gui/src/orxonox/GraphicsEngine.h
===================================================================
--- code/branches/gui/src/orxonox/GraphicsEngine.h	(revision 1636)
+++ code/branches/gui/src/orxonox/GraphicsEngine.h	(revision 1638)
@@ -54,65 +54,74 @@
     class _OrxonoxExport GraphicsEngine : public Ogre::WindowEventListener, public Ogre::LogListener, public OrxonoxClass
     {
-        public:
-            void setConfigValues();
-            bool setup();
-            bool declareRessourceLocations();
-            bool loadRenderer();
-            bool initialiseResources();
-            bool createNewScene();
+    public:
+        GraphicsEngine();
+        ~GraphicsEngine();
 
-            void destroy();
+        void setConfigValues();
+        void setup();
+        void declareRessourceLocations();
+        bool loadRenderer();
+        bool initialiseResources();
+        bool createNewScene();
 
-            Ogre::SceneManager* getSceneManager() { return scene_; }
+        void setLevelSceneManager(Ogre::SceneManager* sceneMgr) { this->levelSceneManager_ = sceneMgr; }
+        Ogre::SceneManager* getLevelSceneManager() { return levelSceneManager_; }
 
-            // several window properties
-            Ogre::RenderWindow* getRenderWindow() { return this->renderWindow_; }
-            size_t getWindowHandle();
-            int getWindowWidth() const;
-            int getWindowHeight() const;
-            float getWindowAspectRatio() const;
-            float getAverageFramesPerSecond() const { return this->avgFramesPerSecond_; }
-            float getAverageTickTime() const { return this->avgTickTime_; }
-            void setAverageTickTime(float tickTime) { this->avgTickTime_ = tickTime; }
-            void setAverageFramesPerSecond(float fps) { this->avgFramesPerSecond_ = fps; }
+        Ogre::Viewport* getLevelViewport() { return this->levelViewport_; }
 
-            void setWindowActivity(bool activity)
-            { if (this->renderWindow_) this->renderWindow_->setActive(activity); }
+        // several window properties
+        Ogre::RenderWindow* getRenderWindow() { return this->renderWindow_; }
+        size_t getWindowHandle();
+        int getWindowWidth() const;
+        int getWindowHeight() const;
+        float getWindowAspectRatio() const;
+        float getAverageFramesPerSecond() const   { return this->avgFramesPerSecond_; }
+        float getAverageTickTime() const          { return this->avgTickTime_; }
+        void setAverageTickTime(float tickTime)   { this->avgTickTime_ = tickTime; }
+        void setAverageFramesPerSecond(float fps) { this->avgFramesPerSecond_ = fps; }
 
-            void windowMoved       (Ogre::RenderWindow* rw);
-            void windowResized     (Ogre::RenderWindow* rw);
-            void windowFocusChanged(Ogre::RenderWindow* rw);
-            void windowClosed      (Ogre::RenderWindow* rw);
+        void setWindowActivity(bool activity)
+        { if (this->renderWindow_) this->renderWindow_->setActive(activity); }
 
-            inline unsigned int getDetailLevelParticle() const
-              { return this->detailLevelParticle_; }
+        inline unsigned int getDetailLevelParticle() const
+        { return this->detailLevelParticle_; }
 
-            static GraphicsEngine& getSingleton();
-            static GraphicsEngine* getSingletonPtr() { return &getSingleton(); }
+        static GraphicsEngine& getSingleton();
+        static GraphicsEngine* getSingletonPtr() { return &getSingleton(); }
 
+    private:
+        // don't mess with singletons
+        GraphicsEngine(GraphicsEngine&) { }
 
-        private:
-            // don't mess with singletons
-            GraphicsEngine();
-            ~GraphicsEngine();
-            GraphicsEngine(GraphicsEngine&) { }
+        //! Method called by the LogListener from Ogre
+        void messageLogged(const std::string&, Ogre::LogMessageLevel,
+            bool, const std::string&);
 
-            //! Method called by the LogListener from Ogre
-            void messageLogged(const std::string&, Ogre::LogMessageLevel,
-                             bool, const std::string&);
+        // window events from Ogre::WindowEventListener
+        void windowMoved       (Ogre::RenderWindow* rw);
+        void windowResized     (Ogre::RenderWindow* rw);
+        void windowFocusChanged(Ogre::RenderWindow* rw);
+        void windowClosed      (Ogre::RenderWindow* rw);
 
-            Ogre::Root*         root_;                  //!< Ogre's root
-            Ogre::SceneManager* scene_;                 //!< scene manager of the game
-            Ogre::RenderWindow* renderWindow_;          //!< the current render window
-            std::string         resourceFile_;          //!< resources file name
-            std::string         ogreConfigFile_;        //!< ogre config file name
-            std::string         ogrePluginsFile_;       //!< ogre plugins file name
-            std::string         ogreLogFile_;           //!< log file name for Ogre log messages
-            int                 ogreLogLevelTrivial_;   //!< Corresponding Orxonx debug level for LL_TRIVIAL
-            int                 ogreLogLevelNormal_;    //!< Corresponding Orxonx debug level for LL_NORMAL
-            int                 ogreLogLevelCritical_;  //!< Corresponding Orxonx debug level for LL_CRITICAL
-            unsigned int        detailLevelParticle_;   //!< Detail level of particle effects (0: off, 1: low, 2: normal, 3: high)
-            float               avgTickTime_;           //!< time in ms to tick() one frame
-            float               avgFramesPerSecond_;    //!< number of frames processed in one second
+        Ogre::Root*         root_;                  //!< Ogre's root
+        Ogre::RenderWindow* renderWindow_;          //!< the current render window
+        Ogre::SceneManager* levelSceneManager_;     //!< scene manager of the game
+        Ogre::Viewport*     levelViewport_;         //!< default full size viewport for the level
+
+        // stats
+        float               avgTickTime_;           //!< time in ms to tick() one frame
+        float               avgFramesPerSecond_;    //!< number of frames processed in one second
+
+        // config values
+        std::string         resourceFile_;          //!< resources file name
+        std::string         ogreConfigFile_;        //!< ogre config file name
+        std::string         ogrePluginsFile_;       //!< ogre plugins file name
+        std::string         ogreLogFile_;           //!< log file name for Ogre log messages
+        int                 ogreLogLevelTrivial_;   //!< Corresponding Orxonx debug level for LL_TRIVIAL
+        int                 ogreLogLevelNormal_;    //!< Corresponding Orxonx debug level for LL_NORMAL
+        int                 ogreLogLevelCritical_;  //!< Corresponding Orxonx debug level for LL_CRITICAL
+        unsigned int        detailLevelParticle_;   //!< Detail level of particle effects (0: off, 1: low, 2: normal, 3: high)
+
+        static GraphicsEngine* singletonRef_s;      //!< Pointer to the Singleton
     };
 }
Index: code/branches/gui/src/orxonox/Main.cc
===================================================================
--- code/branches/gui/src/orxonox/Main.cc	(revision 1636)
+++ code/branches/gui/src/orxonox/Main.cc	(revision 1638)
@@ -22,4 +22,5 @@
  *   Author:
  *      Benjamin Knecht <beni_at_orxonox.net>, (C) 2007
+ *      Reto Grieder
  *   Co-authors:
  *      ...
@@ -35,10 +36,16 @@
 
 #include <exception>
+#include <cassert>
 
 #include "util/OrxonoxPlatform.h"
+#include "util/ArgReader.h"
 #include "core/SignalHandler.h"
+#include "core/Debug.h"
+#include "network/ClientConnection.h"
+#include "Settings.h"
 #include "Orxonox.h"
 
 using namespace orxonox;
+
 #if ORXONOX_PLATFORM == ORXONOX_PLATFORM_APPLE
 #include <CoreFoundation/CoreFoundation.h>
@@ -49,22 +56,57 @@
              std::string macBundlePath()
 {
-  char path[1024];
-  CFBundleRef mainBundle = CFBundleGetMainBundle();
-  assert(mainBundle);
+    char path[1024];
+    CFBundleRef mainBundle = CFBundleGetMainBundle();
+    assert(mainBundle);
 
-  CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
-  assert(mainBundleURL);
+    CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
+    assert(mainBundleURL);
 
-  CFStringRef cfStringRef = CFURLCopyFileSystemPath( mainBundleURL, kCFURLPOSIXPathStyle);
-  assert(cfStringRef);
+    CFStringRef cfStringRef = CFURLCopyFileSystemPath( mainBundleURL, kCFURLPOSIXPathStyle);
+    assert(cfStringRef);
 
-  CFStringGetCString(cfStringRef, path, 1024, kCFStringEncodingASCII);
+    CFStringGetCString(cfStringRef, path, 1024, kCFStringEncodingASCII);
 
-  CFRelease(mainBundleURL);
-  CFRelease(cfStringRef);
+    CFRelease(mainBundleURL);
+    CFRelease(cfStringRef);
 
-  return std::string(path);
+    return std::string(path);
 }
 #endif
+
+bool parseCommandLine(int argc, char** argv)
+{
+    ArgReader args;
+    std::string errorStr = args.parse(argc, argv);
+    if (errorStr != "")
+    {
+        COUT(1) << "Command Line: Parsing failed.\n" << errorStr << std::endl;
+        return false;
+    }
+
+    // Argument reader parses the command line to check syntax.
+    // Settings Singleton then stores the arguments. It always
+    // expects a default value.
+    bool success = true;
+    success &= Settings::addCommandLineArgument<std::string>
+        ("mode",     args.getArgument("mode"),     "standalone");
+    success &= Settings::addCommandLineArgument<std::string>
+        ("dataPath", args.getArgument("dataPath"), "./");
+    success &= Settings::addCommandLineArgument<std::string>
+        ("ip",       args.getArgument("ip"),       "127.0.0.0");
+    success &= Settings::addCommandLineArgument<int>
+        ("port",     args.getArgument("port"),     NETWORK_PORT);
+
+    if (!success)
+        return false;
+
+    if (!args.allChecked())
+    {
+        COUT(1) << "Command Line: Parsing failed.\nNot all arguments were matched." << std::endl;
+        return false;
+    }
+
+    return true;
+}
 
 #ifdef __cplusplus
@@ -72,29 +114,33 @@
 #endif
 
-int main(int argc, char **argv)
+int main(int argc, char** argv)
 {
-  //try {
+    // create a signal handler (only works for linux)
     SignalHandler::getInstance()->doCatch(argv[0], "orxonox.log");
-    Orxonox* orx = Orxonox::getSingleton();
 
-    bool res = false;
+    if (!parseCommandLine(argc, argv))
+    {
+        COUT(0) << "Usage:" << std::endl << "orxonox [--mode client|server|dedicated|standalone] "
+                << "[--data PATH] [--ip IP] [--port PORT]" << std::endl;
+        return 0;
+    }
+
+    Orxonox orxonoxInstance;
+
+    try
+    {
 #if ORXONOX_PLATFORM == ORXONOX_PLATFORM_APPLE
-    res = orx->init(argc, argv, macBundlePath());
+        orxonoxInstance.start(macBundlePath());
 #else
-    res = orx->init(argc, argv);
+        orxonoxInstance.start();
 #endif
+    }
+    catch (std::exception& ex)
+    {
+        COUT(1) << ex.what() << std::endl;
+        COUT(1) << "Abort." << std::endl;
+    }
 
-    if (res)
-      orx->start();
-    orx->destroySingleton();
-  /*}
-  catch (std::exception &ex)
-  {
-    std::cerr << "Exception:\n";
-    std::cerr << ex.what() << "\n";
-    return 1;
-  }*/
-
-  return 0;
+    return 0;
 }
 
Index: code/branches/gui/src/orxonox/Orxonox.cc
===================================================================
--- code/branches/gui/src/orxonox/Orxonox.cc	(revision 1636)
+++ code/branches/gui/src/orxonox/Orxonox.cc	(revision 1638)
@@ -22,6 +22,7 @@
  *   Author:
  *      Reto Grieder
+ *      Benjamin Knecht <beni_at_orxonox.net>, (C) 2007
  *   Co-authors:
- *      Benjamin Knecht <beni_at_orxonox.net>, (C) 2007
+ *      ...
  *
  */
@@ -38,4 +39,5 @@
 //****** STD *******
 #include <deque>
+#include <cassert>
 
 //****** OGRE ******
@@ -50,12 +52,15 @@
 // util
 //#include "util/Sleep.h"
-#include "util/ArgReader.h"
 
 // core
 #include "core/ConfigFileManager.h"
+#include "core/ConfigValueIncludes.h"
 #include "core/ConsoleCommand.h"
 #include "core/Debug.h"
 #include "core/Loader.h"
+#include "core/Exception.h"
 #include "core/input/InputManager.h"
+#include "core/input/SimpleInputState.h"
+#include "core/input/KeyBinder.h"
 #include "core/TclBind.h"
 #include "core/Core.h"
@@ -69,9 +74,9 @@
 
 // objects and tools
-#include "overlays/OverlayGroup.h"
 #include "overlays/console/InGameConsole.h"
 #include "objects/Tickable.h"
 #include "objects/Backlight.h"
 #include "tools/ParticleInterface.h"
+#include "gui/GUIManager.h"
 
 #include "GraphicsEngine.h"
@@ -85,7 +90,8 @@
 namespace orxonox
 {
-  SetConsoleCommandShortcut(Orxonox, exit).setKeybindMode(KeybindMode::OnPress);
-  SetConsoleCommandShortcut(Orxonox, slomo).setAccessLevel(AccessLevel::Offline).setDefaultValue(0, 1.0).setAxisParamIndex(0).setIsAxisRelative(false);
-  SetConsoleCommandShortcut(Orxonox, setTimeFactor).setAccessLevel(AccessLevel::Offline).setDefaultValue(0, 1.0);
+  SetConsoleCommand(Orxonox, exit, true).setKeybindMode(KeybindMode::OnPress);
+  SetConsoleCommand(Orxonox, slomo, true).setAccessLevel(AccessLevel::Offline).setDefaultValue(0, 1.0).setAxisParamIndex(0).setIsAxisRelative(false);
+  SetConsoleCommand(Orxonox, setTimeFactor, true).setAccessLevel(AccessLevel::Offline).setDefaultValue(0, 1.0);
+  SetConsoleCommand(Orxonox, loadGame, true).setAccessLevel(AccessLevel::User).setDefaultValue(0, "standalone");
 
   /**
@@ -106,8 +112,11 @@
     , bAbort_(false)
     , timefactor_(1.0f)
-    , mode_(STANDALONE)
-    , serverIp_("")
-    , serverPort_(NETWORK_PORT)
-  {
+    , mode_(GameMode::GM_Unspecified)
+    , debugRefreshTime_(0.0f)
+  {
+    RegisterRootObject(Orxonox);
+
+    assert(singletonRef_s == 0);
+    singletonRef_s = this;
   }
 
@@ -118,5 +127,5 @@
   {
     // keep in mind: the order of deletion is very important!
-    Loader::unload(startLevel_);
+    Loader::unload();
     if (this->startLevel_)
       delete this->startLevel_;
@@ -136,5 +145,7 @@
       delete this->timer_;
     InputManager::destroy();
-    GraphicsEngine::getSingleton().destroy();
+
+    if (this->ogre_)
+      delete ogre_;
 
     if (network::Client::getSingleton())
@@ -142,4 +153,11 @@
     if (server_g)
       delete network::Server::getSingleton();
+
+    singletonRef_s = 0;
+  }
+
+  void Orxonox::setConfigValues()
+  {
+    SetConfigValue(debugRefreshTime_, 0.2).description("Sets the time interval at which average fps, etc. get updated.");
   }
 
@@ -157,19 +175,8 @@
    * @return singleton reference
    */
-  Orxonox* Orxonox::getSingleton()
-  {
-    if (!singletonRef_s)
-      singletonRef_s = new Orxonox();
-    return singletonRef_s;
-  }
-
-  /**
-    @brief Destroys the Orxonox singleton.
-  */
-  void Orxonox::destroySingleton()
-  {
-    if (singletonRef_s)
-      delete singletonRef_s;
-    singletonRef_s = 0;
+  Orxonox& Orxonox::getSingleton()
+  {
+    assert(singletonRef_s);
+    return *singletonRef_s;
   }
 
@@ -179,20 +186,19 @@
   void Orxonox::setTimeFactor(float factor)
   {
-    float change = factor / Orxonox::getSingleton()->getTimeFactor();
-    Orxonox::getSingleton()->timefactor_ = factor;
+    float change = factor / Orxonox::getSingleton().getTimeFactor();
+    Orxonox::getSingleton().timefactor_ = factor;
     for (Iterator<ParticleInterface> it = ObjectList<ParticleInterface>::begin(); it; ++it)
         it->setSpeedFactor(it->getSpeedFactor() * change);
 
     for (Iterator<Backlight> it = ObjectList<Backlight>::begin(); it; ++it)
-        it->setTimeFactor(Orxonox::getSingleton()->getTimeFactor());
-  }
-
-  /**
-   * initialization of Orxonox object
-   * @param argc argument counter
-   * @param argv list of argumenst
+        it->setTimeFactor(Orxonox::getSingleton().getTimeFactor());
+  }
+
+
+  /**
+   * Starts the whole Game.
    * @param path path to config (in home dir or something)
    */
-  bool Orxonox::init(int argc, char **argv)
+  void Orxonox::start()
   {
 #ifdef _DEBUG
@@ -203,130 +209,138 @@
     Factory::createClassHierarchy();
 
-    std::string mode;
-    std::string tempDataPath;
-
-    ArgReader ar(argc, argv);
-    ar.checkArgument("mode", &mode, false);
-    ar.checkArgument("data", &tempDataPath, false);
-    ar.checkArgument("ip",   &serverIp_, false);
-    ar.checkArgument("port", &serverPort_, false);
-    if(ar.errorHandling())
-    {
-      COUT(1) << "Error while parsing command line arguments" << std::endl;
-      COUT(1) << ar.getErrorString();
-      COUT(0) << "Usage:" << std::endl << "orxonox [mode client|server|dedicated|standalone] "
-        << "[--data PATH] [--ip IP] [--port PORT]" << std::endl;
-      return false;
-    }
-
-    if (mode == "client")
-      mode_ = CLIENT;
-    else if (mode == "server")
-      mode_ = SERVER;
-    else if (mode == "dedicated")
-      mode_ = DEDICATED;
-    else
-    {
-      if (mode == "")
-        mode = "standalone";
-      if (mode != "standalone")
+    setConfigValues();
+
+    const Settings::CommandLineArgument* mode = Settings::getCommandLineArgument("mode");
+    assert(mode);
+    if (!mode->bHasDefaultValue_)
+    {
+      Settings::setGameMode(mode->value_);
+      this->mode_ = Settings::getGameMode();
+    }
+    COUT(3) << "Orxonox: Game mode is " << mode_.name << "." << std::endl;
+
+    const Settings::CommandLineArgument* dataPath = Settings::getCommandLineArgument("dataPath");
+    assert(dataPath);
+    if (!dataPath->bHasDefaultValue_)
+    {
+      if (*dataPath->value_.getString().end() != '/' && *dataPath->value_.getString().end() != '\\')
+        Settings::tsetDataPath(dataPath->value_.getString() + "/");
+      else
+        Settings::tsetDataPath(dataPath->value_.getString());
+    }
+
+    try
+    {
+        // initialise TCL
+        TclBind::getInstance().setDataPath(Settings::getDataPath());
+
+        ogre_ = new GraphicsEngine();
+        ogre_->setup();       // creates ogre root and other essentials
+
+        if (mode_.showsGraphics)
+        {
+          ogre_->loadRenderer();    // creates the render window
+
+          // TODO: Spread this so that this call only initialises things needed for the Console and GUI
+          ogre_->initialiseResources();
+
+          // Calls the InputManager which sets up the input devices.
+          // The render window width and height are used to set up the mouse movement.
+          InputManager::initialise(ogre_->getWindowHandle(),
+                ogre_->getWindowWidth(), ogre_->getWindowHeight(), true, true, true);
+          KeyBinder* keyBinder = new KeyBinder();
+          InputManager::createSimpleInputState("game", 20)->setHandler(keyBinder);
+
+          // Load the InGameConsole
+          InGameConsole::getInstance().initialise();
+
+          // load the CEGUI interface
+          GUIManager::getInstance().initialise();
+        }
+
+        bool showGUI = true;
+        if (mode_.mode != GameMode::Unspecified)
+        {
+          showGUI = false;
+          // a game mode was specified with the command line
+          // we therefore load the game and level directly
+
+          if (!loadLevel(this->mode_))
+          {
+            COUT(1) << "Loading with predefined mode failed. Showing main menu." << std::endl;
+            showGUI = true;
+            mode_ = GameMode::GM_Unspecified;
+          }
+        }
+        
+        if (showGUI)
+        {
+          // show main menu
+          //GraphicsEngine::getSingleton().createNewScene();
+          GUIManager::getInstance().showGUI("MainMenu", true);
+        }
+    }
+    catch (std::exception& ex)
+    {
+      COUT(1) << ex.what() << std::endl;
+      COUT(1) << "Loading sequence aborted." << std::endl;
+      return;
+    }
+
+    modeRequest_ = mode_;
+    // here happens the game
+    startRenderLoop();
+
+    if (mode_.mode == GameMode::Client)
+      network::Client::getSingleton()->closeConnection();
+
+    if (mode_.hasServer)
+      server_g->close();
+  }
+
+  void Orxonox::loadGame(const std::string& name)
+  {
+      const GameMode& mode = Settings::getGameMode(name);
+      if (mode.mode == GameMode::None)
+          return;
+
+      getSingleton().modeRequest_ = mode;
+  }
+
+  bool Orxonox::loadLevel(const GameMode& mode)
+  {
+      bool success = true;
+
+      if (mode.showsGraphics)
       {
-        COUT(2) << "Warning: mode \"" << mode << "\" doesn't exist. "
-          << "Defaulting to standalone" << std::endl;
-        mode = "standalone";
+        // create Ogre SceneManager for the level
+        ogre_->createNewScene();
+
+        if (!loadPlayground())
+            return false;
       }
-      mode_ = STANDALONE;
-    }
-    COUT(3) << "Orxonox: Mode is " << mode << "." << std::endl;
-
-    if (tempDataPath != "")
-    {
-      if (tempDataPath[tempDataPath.size() - 1] != '/')
-        tempDataPath += "/";
-      Settings::tsetDataPath(tempDataPath);
-    }
-
-    // initialise TCL
-    TclBind::getInstance().setDataPath(Settings::getDataPath());
-
-    //if (mode_ == DEDICATED)
-      // TODO: decide what to do here
-    //else
-
-    // for playable server, client and standalone, the startup
-    // procedure until the GUI is identical
-
-    ogre_ = &GraphicsEngine::getSingleton();
-    if (!ogre_->setup())       // creates ogre root and other essentials
-      return false;
-
-    return true;
-  }
-
-  /**
-   * start modules
-   */
-  bool Orxonox::start()
-  {
-    if (mode_ == DEDICATED)
-    {
-      // do something else
-    }
-    else
-    { // not dedicated server
-      if (!ogre_->loadRenderer())    // creates the render window
-        return false;
-
-      // TODO: Spread this so that this call only initialises things needed for the Console
-      if (!ogre_->initialiseResources())
-        return false;
-
-      // Load the InGameConsole
-      InGameConsole::getInstance().initialise();
-
-      // Calls the InputManager which sets up the input devices.
-      // The render window width and height are used to set up the mouse movement.
-      if (!InputManager::initialise(ogre_->getWindowHandle(),
-            ogre_->getWindowWidth(), ogre_->getWindowHeight(), true, true, true))
-        return false;
-
-      // TOOD: load the GUI here
-      // set InputManager to GUI mode
-      InputManager::setInputState(InputManager::IS_GUI);
-      // TODO: run GUI here
-
-      // The following lines depend very much on the GUI output, so they're probably misplaced here..
-
-      InputManager::setInputState(InputManager::IS_NONE);
-
-      // create Ogre SceneManager
-      ogre_->createNewScene();
-
-      if (!loadPlayground())
-        return false;
-    }
-
-    switch (mode_)
-    {
-    case SERVER:
-      if (!serverLoad())
-        return false;
-      break;
-    case CLIENT:
-      if (!clientLoad())
-        return false;
-      break;
-    case DEDICATED:
-      if (!serverLoad())
-        return false;
-      break;
-    default:
-      if (!standaloneLoad())
-        return false;
-    }
-
-    InputManager::setInputState(InputManager::IS_NORMAL);
-
-    return startRenderLoop();
+
+      switch (mode.mode)
+      {
+      case GameMode::Server:
+        success &= serverLoad();
+        break;
+      case GameMode::Client:
+        success &= clientLoad();
+        break;
+      case GameMode::Dedicated:
+        success &= serverLoad();
+        break;
+      case GameMode::Standalone:
+        success &= standaloneLoad();
+        break;
+      default: // never happens
+          assert(false);
+      }
+      
+      if (success)
+        InputManager::requestEnterState("game");
+
+      return success;
   }
 
@@ -337,21 +351,21 @@
   bool Orxonox::loadPlayground()
   {
-    // Init audio
-    //auMan_ = new audio::AudioManager();
-    //auMan_->ambientAdd("a1");
-    //auMan_->ambientAdd("a2");
-    //auMan_->ambientAdd("a3");
-    //auMan->ambientAdd("ambient1");
-    //auMan_->ambientStart();
+    // Start the Radar
+    this->radar_ = new Radar();
 
     // Load the HUD
     COUT(3) << "Orxonox: Loading HUD" << std::endl;
     hud_ = new Level(Settings::getDataPath() + "overlay/hud.oxo");
-    Loader::load(hud_);
-
-    // Start the Radar
-    this->radar_ = new Radar();
-
-    return true;
+    return Loader::load(hud_);
+  }
+
+  /**
+   * Helper method to load a level.
+   */
+  bool Orxonox::loadScene()
+  {
+    COUT(0) << "Loading level..." << std::endl;
+    startLevel_ = new Level(Settings::getDataPath() + "levels/sample.oxw");
+    return Loader::open(startLevel_);
   }
 
@@ -363,6 +377,8 @@
     COUT(0) << "Loading level in server mode" << std::endl;
 
+    assert(Settings::getCommandLineArgument("port"));
+    int serverPort = Settings::getCommandLineArgument("port")->value_;
     //server_g = new network::Server(serverPort_);
-    server_g = network::Server::createSingleton(serverPort_);
+    server_g = network::Server::createSingleton(serverPort);
 
     if (!loadScene())
@@ -381,9 +397,13 @@
     COUT(0) << "Loading level in client mode" << std::endl;\
 
-    if (serverIp_.compare("") == 0)
+    assert(Settings::getCommandLineArgument("port"));
+    assert(Settings::getCommandLineArgument("ip"));
+    int serverPort = Settings::getCommandLineArgument("port")->value_;
+    std::string serverIP = Settings::getCommandLineArgument("ip")->value_;
+
+    if (serverIP.compare("") == 0)
       client_g = network::Client::createSingleton();
     else
-
-      client_g = network::Client::createSingleton(serverIp_, serverPort_);
+      client_g = network::Client::createSingleton(serverIP, serverPort);
 
     if(!client_g->establishConnection())
@@ -408,33 +428,19 @@
 
   /**
-   * Helper method to load a level.
-   */
-  bool Orxonox::loadScene()
-  {
-    startLevel_ = new Level("levels/sample.oxw");
-    Loader::open(startLevel_);
-
-    return true;
-  }
-
-
-  /**
     Main loop of the orxonox game.
-    About the loop: The design is almost exactly like the one in ogre, so that
-    if any part of ogre registers a framelisteners, it will still behave
-    correctly. Furthermore the time smoothing feature from ogre has been
-    implemented too. If turned on (see orxonox constructor), it will calculate
-    the dt_n by means of the recent most dt_n-1, dt_n-2, etc.
+    We use the Ogre::Timer to measure time since it uses the most precise
+    method an a platform (however the windows timer lacks time when under
+    heavy kernel load!).
+    There is a simple mechanism to measure the average time spent in our
+    ticks as it may indicate performance issues.
+    A note about the Ogre::FrameListener: Even though we don't use them,
+    they still get called. However, the delta times are not correct (except
+    for timeSinceLastFrame, which is the most important). A little research
+    as shown that there is probably only one FrameListener that doesn't even
+    need the time. So we shouldn't run into problems.
   */
-  bool Orxonox::startRenderLoop()
-  {
-    // first check whether ogre root object has been created
-    if (Ogre::Root::getSingletonPtr() == 0)
-    {
-      COUT(2) << "Orxonox Error: Could not start rendering. No Ogre root object found" << std::endl;
-      return false;
-    }
+  void Orxonox::startRenderLoop()
+  {
     Ogre::Root& ogreRoot = Ogre::Root::getSingleton();
-
 
     // use the ogre timer class to measure time.
@@ -444,6 +450,5 @@
     unsigned long frameCount = 0;
     
-    // TODO: this would very well fit into a configValue
-    const unsigned long refreshTime = 200000;
+    const unsigned long refreshTime = debugRefreshTime_ * 1000000.0f;
     unsigned long refreshStartTime = 0;
     unsigned long tickTime = 0;
@@ -454,80 +459,108 @@
     unsigned long timeAfterTick = 0;
 
+    int sleepTime = 0;
+
+    // TODO: Update time in seconds every 7 seconds to avoid any overflow (7 secs is very tight)
+
     COUT(3) << "Orxonox: Starting the main loop." << std::endl;
 
+    try
+    {
     timer_->reset();
     while (!bAbort_)
     {
-      // get current time
-      timeBeforeTickOld = timeBeforeTick;
-      timeBeforeTick    = timer_->getMicroseconds();
-      float dt = (timeBeforeTick - timeBeforeTickOld) / 1000000.0;
-
-
-      // tick the core (needs real time for input and tcl thread management)
-      Core::tick(dt);
-
-      // Call those objects that need the real time
-      for (Iterator<TickableReal> it = ObjectList<TickableReal>::start(); it; ++it)
-        it->tick(dt);
-      // Call the scene objects
-      for (Iterator<Tickable> it = ObjectList<Tickable>::start(); it; ++it)
-        it->tick(dt * this->timefactor_);
-
-      // call server/client with normal dt
-      if (client_g)
-        client_g->tick(dt * this->timefactor_);
-      if (server_g)
-        server_g->tick(dt * this->timefactor_);
-
-
-      // get current time once again
-      timeAfterTick = timer_->getMicroseconds();
-
-      tickTime += timeAfterTick - timeBeforeTick;
-      if (timeAfterTick > refreshStartTime + refreshTime)
-      {
-        GraphicsEngine::getSingleton().setAverageTickTime(
-            (float)tickTime * 0.001 / (frameCount - oldFrameCount));
-        GraphicsEngine::getSingleton().setAverageFramesPerSecond(
-            (float)(frameCount - oldFrameCount) / (timeAfterTick - refreshStartTime) * 1000000.0);
-        oldFrameCount = frameCount;
-        tickTime = 0;
-        refreshStartTime = timeAfterTick;
-      }
-
-
-      // don't forget to call _fireFrameStarted in ogre to make sure
-      // everything goes smoothly
-      Ogre::FrameEvent evt;
-      evt.timeSinceLastFrame = dt;
-      evt.timeSinceLastEvent = dt; // note: same time, but shouldn't matter anyway
-      ogreRoot._fireFrameStarted(evt);
-
-      if (mode_ != DEDICATED)
-      {
-        // Pump messages in all registered RenderWindows
-        // This calls the WindowEventListener objects.
-        Ogre::WindowEventUtilities::messagePump();
-        // make sure the window stays active even when not focused
-        // (probably only necessary on windows)
-        GraphicsEngine::getSingleton().setWindowActivity(true);
-
-        // render
-        ogreRoot._updateAllRenderTargets();
-      }
-
-      // again, just to be sure ogre works fine
-      ogreRoot._fireFrameEnded(evt); // note: uses the same time as _fireFrameStarted
-
-      ++frameCount;
-    }
-
-    if (mode_ == CLIENT)
-      network::Client::getSingleton()->closeConnection();
-    else if (mode_ == SERVER)
-      server_g->close();
-
-    return true;
+        // get current time
+        timeBeforeTickOld = timeBeforeTick;
+        timeBeforeTick    = timer_->getMicroseconds();
+        float dt = (timeBeforeTick - timeBeforeTickOld) / 1000000.0;
+
+        // check whether we have to load a game
+        if (mode_.mode != modeRequest_.mode && mode_.mode == GameMode::Unspecified)
+        {
+            this->loadLevel(modeRequest_);
+            this->modeRequest_ = GameMode::GM_None;
+        }
+
+
+        // tick the core (needs real time for input and tcl thread management)
+        Core::tick(dt);
+
+        // Call those objects that need the real time
+        for (Iterator<TickableReal> it = ObjectList<TickableReal>::start(); it; ++it)
+          it->tick(dt);
+        // Call the scene objects
+        for (Iterator<Tickable> it = ObjectList<Tickable>::start(); it; ++it)
+          it->tick(dt * this->timefactor_);
+
+        // call server/client with normal dt
+        if (client_g)
+          client_g->tick(dt * this->timefactor_);
+        if (server_g)
+          server_g->tick(dt * this->timefactor_);
+
+
+        // get current time once again
+        timeAfterTick = timer_->getMicroseconds();
+
+        tickTime += timeAfterTick - timeBeforeTick;
+        if (timeAfterTick > refreshStartTime + refreshTime)
+        {
+          GraphicsEngine::getSingleton().setAverageTickTime(
+              (float)tickTime * 0.001 / (frameCount - oldFrameCount));
+          float avgFPS = (float)(frameCount - oldFrameCount) / (timeAfterTick - refreshStartTime) * 1000000.0;
+          GraphicsEngine::getSingleton().setAverageFramesPerSecond(avgFPS);
+
+          if (avgFPS > 60.0)
+            sleepTime++;
+          else
+            sleepTime--;
+          if (sleepTime < 0)
+              sleepTime = 0;
+
+          oldFrameCount = frameCount;
+          tickTime = 0;
+          refreshStartTime = timeAfterTick;
+        }
+
+        // do some sleeping when the frameRate is over 60
+        if (sleepTime > 0)
+          msleep(sleepTime);
+
+
+        // don't forget to call _fireFrameStarted in ogre to make sure
+        // everything goes smoothly
+        Ogre::FrameEvent evt;
+        evt.timeSinceLastFrame = dt;
+        evt.timeSinceLastEvent = dt; // note: same time, but shouldn't matter anyway
+        ogreRoot._fireFrameStarted(evt);
+
+        if (mode_.showsGraphics)
+        {
+          // Pump messages in all registered RenderWindows
+          // This calls the WindowEventListener objects.
+          Ogre::WindowEventUtilities::messagePump();
+          // make sure the window stays active even when not focused
+          // (probably only necessary on windows)
+          GraphicsEngine::getSingleton().setWindowActivity(true);
+
+          // tick CEGUI
+          GUIManager::getInstance().tick(dt);
+
+          // render
+          ogreRoot._updateAllRenderTargets();
+        }
+
+        // again, just to be sure ogre works fine
+        ogreRoot._fireFrameEnded(evt); // note: uses the same time as _fireFrameStarted
+
+        ++frameCount;
+    }
+    }
+    catch (std::exception& ex)
+    {
+      // something went wrong.
+      COUT(1) << ex.what() << std::endl;
+      COUT(1) << "Main loop was stopped by an unhandled exception. Shutting down." << std::endl;
+    }
   }
 }
Index: code/branches/gui/src/orxonox/Orxonox.h
===================================================================
--- code/branches/gui/src/orxonox/Orxonox.h	(revision 1636)
+++ code/branches/gui/src/orxonox/Orxonox.h	(revision 1638)
@@ -22,6 +22,7 @@
  *   Author:
  *      Reto Grieder
+ *      Benjamin Knecht <beni_at_orxonox.net>, (C) 2007
  *   Co-authors:
- *      Benjamin Knecht <beni_at_orxonox.net>, (C) 2007
+ *      ...
  *
  */
@@ -41,52 +42,44 @@
 
 #include <OgrePrerequisites.h>
+
+#include "core/OrxonoxClass.h"
 #include "audio/AudioPrereqs.h"
+#include "GraphicsEngine.h"
+#include "Settings.h"
 
-#include "GraphicsEngine.h"
-
-namespace orxonox {
-
-  enum gameMode{
-    SERVER,
-    CLIENT,
-    STANDALONE,
-    DEDICATED
-  };
-
+namespace orxonox
+{
   //! Orxonox singleton class
-  class _OrxonoxExport Orxonox
+    class _OrxonoxExport Orxonox : public OrxonoxClass
   {
     public:
-      bool init(int argc, char **argv);
-      bool start();
+      Orxonox();
+      ~Orxonox();
+
+      void start();
+      void setConfigValues();
 
       void abortRequest();
 
-      static Orxonox* getSingleton();
-      static void destroySingleton();
+      static Orxonox& getSingleton();
 
-      static inline void slomo(float factor) { Orxonox::setTimeFactor(factor); }
+      static void slomo(float factor) { Orxonox::setTimeFactor(factor); }
+      static float getTimeFactor()    { return Orxonox::getSingleton().timefactor_; }
+      static void loadGame(const std::string& name);
+      static void exit()              { Orxonox::getSingleton().abortRequest(); }
       static void setTimeFactor(float factor = 1.0);
-      static inline float getTimeFactor() { return Orxonox::getSingleton()->timefactor_; }
-      static inline void exit() { Orxonox::getSingleton()->abortRequest(); }
 
    private:
       // don't mess with singletons
-      Orxonox();
       Orxonox(Orxonox& instance);
-      Orxonox& operator=(const Orxonox& instance);
-      ~Orxonox();
 
-      bool loadPlayground();
-
+      bool loadLevel(const GameMode& mode);
       bool serverLoad();
       bool clientLoad();
       bool standaloneLoad();
 
+      bool loadPlayground();
       bool loadScene();
-
-      bool startRenderLoop();
-
-      float calculateEventTime(unsigned long, std::deque<unsigned long>&);
+      void startRenderLoop();
 
     private:
@@ -101,7 +94,9 @@
 
       // this is used to identify the mode (server/client/...) we're in
-      gameMode              mode_;
-      std::string           serverIp_;
-      int                   serverPort_;
+      GameMode              mode_;
+      GameMode              modeRequest_;
+
+      // config values
+      float                 debugRefreshTime_;
 
       static Orxonox *singletonRef_s;
Index: code/branches/gui/src/orxonox/OrxonoxStableHeaders.h
===================================================================
--- code/branches/gui/src/orxonox/OrxonoxStableHeaders.h	(revision 1636)
+++ code/branches/gui/src/orxonox/OrxonoxStableHeaders.h	(revision 1638)
@@ -45,40 +45,8 @@
 #  define WIN32_LEAN_AND_MEAN
 #endif
-// not including the entire Ogre.h doesn't exceed the default heap size for pch
-//#include <Ogre.h>
-#include <OgreBillboardSet.h>
-#include <OgreCamera.h>
-#include <OgreColourValue.h>
-#include <OgreConfigFile.h>
-#include <OgreEntity.h>
-#include <OgreException.h>
-#include <OgreFrameListener.h>
-#include <OgreLight.h>
-#include <OgreLog.h>
-#include <OgreLogManager.h>
-#include <OgreMath.h>
-#include <OgreMatrix3.h>
-#include <OgreMatrix4.h>
-#include <OgreMesh.h>
-#include <OgreOverlay.h>
-#include <OgreOverlayElement.h>
-#include <OgreOverlayManager.h>
-#include <OgreParticleEmitter.h>
-#include <OgreParticleSystem.h>
-#include <OgreQuaternion.h>
-#include <OgreResourceGroupManager.h>
-#include <OgreRenderWindow.h>
-#include <OgreRoot.h>
-#include <OgreSceneManager.h>
-#include <OgreSceneNode.h>
-#include <OgreString.h>
-#include <OgreStringConverter.h>
-#include <OgreTextureManager.h>
-#include <OgreTimer.h>
-#include <OgreVector2.h>
-#include <OgreVector3.h>
-#include <OgreVector3.h>
-#include <OgreViewport.h>
-#include <OgreWindowEventUtilities.h>
+
+#include <Ogre.h>
+#include <CEGUI.h>
+#include <boost/thread/recursive_mutex.hpp>
 
 //-----------------------------------------------------------------------
@@ -86,6 +54,4 @@
 //-----------------------------------------------------------------------
 
-#include "ois/OIS.h"
-#include "cpptcl/CppTcl.h"
 #include "tinyxml/ticpp.h"
 #include "tinyxml/tinyxml.h"
@@ -104,8 +70,9 @@
 #include "core/CoreIncludes.h"
 #include "core/ConfigValueIncludes.h"
+#include "core/CommandExecutor.h"
 #include "core/Debug.h"
+#include "core/Executor.h"
 #include "core/OutputBuffer.h"
 #include "core/OutputHandler.h"
-#include "core/Executor.h"
 #include "core/XMLPort.h"
 
Index: code/branches/gui/src/orxonox/Radar.cc
===================================================================
--- code/branches/gui/src/orxonox/Radar.cc	(revision 1636)
+++ code/branches/gui/src/orxonox/Radar.cc	(revision 1638)
@@ -34,5 +34,6 @@
 #include "OrxonoxStableHeaders.h"
 #include "Radar.h"
-#include <float.h>
+#include <cfloat>
+#include <cassert>
 #include "objects/WorldEntity.h"
 #include "objects/SpaceShip.h"
Index: code/branches/gui/src/orxonox/RadarViewable.h
===================================================================
--- code/branches/gui/src/orxonox/RadarViewable.h	(revision 1636)
+++ code/branches/gui/src/orxonox/RadarViewable.h	(revision 1638)
@@ -32,4 +32,5 @@
 #include "OrxonoxPrereqs.h"
 #include <string>
+#include <cassert>
 #include "util/Math.h"
 #include "core/Debug.h"
Index: code/branches/gui/src/orxonox/Settings.cc
===================================================================
--- code/branches/gui/src/orxonox/Settings.cc	(revision 1636)
+++ code/branches/gui/src/orxonox/Settings.cc	(revision 1638)
@@ -28,6 +28,7 @@
 
 /**
-    @file
-    @brief Implementation of the Settings class.
+@file
+@brief
+    Implementation of the Settings class.
 */
 
@@ -35,4 +36,5 @@
 #include "Settings.h"
 
+#include "util/String.h"
 #include "core/CoreIncludes.h"
 #include "core/ConfigValueIncludes.h"
@@ -40,66 +42,113 @@
 namespace orxonox
 {
-  /**
-    @brief Constructor: Registers the object and sets the config-values.
-  */
-  Settings::Settings()
-  {
-    RegisterRootObject(Settings);
-    setConfigValues();
-  }
 
-  Settings::~Settings()
-  {
-  }
+// Using a macro makes the above list much more readable.
+// Settings::addGameMode adds the mode in a map, so we can access game modes by string.
+#define CreateGameMode(name, showsGraphics, isMaster, hasServer)                                        \
+    const GameMode GameMode::GM_##name = { GameMode::name, showsGraphics, isMaster, hasServer, #name }; \
+    bool temporaryVariable##name = Settings::addGameMode(&GameMode::GM_##name)
 
-  /**
-    @brief Returns a unique instance of Core.
-    @return The instance
-  */
-  Settings& Settings::getSingleton()
-  {
-    static Settings instance;
-    return instance;
-  }
+    //                          showsGraphics  isMaster  hasServer
+    CreateGameMode(None,        false,         false,    false);
+    CreateGameMode(Unspecified, true,          false,    false);
+    CreateGameMode(Server,      true,          true,     true );
+    CreateGameMode(Client,      true,          false,    false);
+    CreateGameMode(Standalone,  true,          true,     false);
+    CreateGameMode(Dedicated,   false,         true,     true );
 
-  /**
-    @brief Function to collect the SetConfigValue-macro calls.
-  */
-  void Settings::setConfigValues()
-  {
-    SetConfigValue(dataPath_, "../../Media/").description("Relative path to the game data.");
-    if (dataPath_ != "" && dataPath_[dataPath_.size() - 1] != '/')
+    /**
+    @brief
+        Constructor: Registers the object and sets the config-values.
+    */
+    Settings::Settings()
     {
-      ModifyConfigValue(dataPath_, set, dataPath_ + "/");
+        RegisterRootObject(Settings);
+        gameMode_ = GameMode::GM_Unspecified;
+        setConfigValues();
     }
 
-    if (dataPath_ == "")
+    /**
+    @brief
+        Returns a unique instance of Core.
+    @return
+        The instance
+    */
+    Settings& Settings::getInstance()
     {
-      ModifyConfigValue(dataPath_, set, "/");
-      COUT(2) << "Warning: Data path set to \"/\", is that really correct?" << std::endl;
+        static Settings instance;
+        return instance;
     }
-  }
 
-  /**
-    @brief Temporary sets the data path
-    @param path The new data path
-  */
-  void Settings::_tsetDataPath(const std::string& path)
-  {
-    ModifyConfigValue(dataPath_, tset, path);
-  }
+    /**
+    @brief
+        Function to collect the SetConfigValue-macro calls.
+    */
+    void Settings::setConfigValues()
+    {
+        SetConfigValue(dataPath_, "../../Media/").description("Relative path to the game data.");
+        if (dataPath_ != "" && dataPath_[dataPath_.size() - 1] != '/')
+        {
+            ModifyConfigValue(dataPath_, set, dataPath_ + "/");
+        }
 
-  /*static*/ void Settings::tsetDataPath(const std::string& path)
-  {
-    getSingleton()._tsetDataPath(path);
-  }
+        if (dataPath_ == "")
+        {
+            ModifyConfigValue(dataPath_, set, "/");
+            COUT(2) << "Warning: Data path set to \"/\", is that really correct?" << std::endl;
+        }
+    }
 
-  /**
-    @brief Returns the relative path to the game data.
-    @return The path to the game data
-  */
-  /*static*/ const std::string& Settings::getDataPath()
-  {
-    return getSingleton().dataPath_;
-  }
+    /**
+    @brief
+        Temporary sets the data path
+    @param path
+        The new data path
+    */
+    void Settings::_tsetDataPath(const std::string& path)
+    {
+        ModifyConfigValue(dataPath_, tset, path);
+    }
+
+    /**
+    @brief
+        Sets the game mode.
+    */
+    /*static*/ void Settings::setGameMode(const std::string& mode)
+    {
+        std::string modeL = getLowercase(mode);
+        std::map<std::string, const GameMode*>::const_iterator it = getInstance().gameModes_.find(modeL);
+        if (it != getInstance().gameModes_.end())
+            getInstance().gameMode_ = *(*it).second;
+        else
+        {
+            COUT(2) << "Warning: mode \"" << mode << "\" doesn't exist. "
+                    << "Defaulting to 'Standalone'" << std::endl;
+            getInstance().gameMode_ = GameMode::GM_Standalone;
+        }
+    }
+
+    /*static*/ bool Settings::addGameMode(const GameMode* mode)
+    {
+        getInstance().gameModes_[getLowercase(mode->name)] = mode;
+        return true;
+    }
+
+
+    /**
+    @brief
+        Gets an argument from the command line by name.
+    @return
+        Is 0 if name was not found.
+    */
+    /*static*/ const Settings::CommandLineArgument* Settings::getCommandLineArgument(const std::string &name)
+    {
+        std::map<std::string, CommandLineArgument>::const_iterator it = getInstance().commandArguments_.find(name);
+        if (it != getInstance().commandArguments_.end())
+        {
+            return &((*it).second);
+        }
+        else
+            return 0;
+    }
+
 }
Index: code/branches/gui/src/orxonox/Settings.h
===================================================================
--- code/branches/gui/src/orxonox/Settings.h	(revision 1636)
+++ code/branches/gui/src/orxonox/Settings.h	(revision 1638)
@@ -29,5 +29,5 @@
 /**
     @file Core.h
-    @brief Definition of the Settings class.
+    @brief Declaration of the Settings class.
 
     The static Settings class is only used to configure some variables
@@ -41,26 +41,151 @@
 #include <string>
 #include "core/OrxonoxClass.h"
+#include "core/Debug.h"
+#include "util/MultiTypeMath.h"
+#include "util/Convert.h"
 
 namespace orxonox
 {
-  class _OrxonoxExport Settings : public OrxonoxClass
-  {
+    /**
+    @brief
+        Defines a bit field structure that holds the mode as enum plus
+        the attributes as single named bits.
+        Every different GameMode is stored as static const, but if you wish to
+        compare two modes, you will have to use the 'mode' member variable.
+    */
+    struct GameMode
+    {
+        enum Mode
+        {
+            None,
+            Unspecified,
+            Server,
+            Client,
+            Standalone,
+            Dedicated,
+        };
+
+        Mode mode;
+        bool showsGraphics;
+        bool isMaster;
+        bool hasServer;
+        std::string name;
+
+        static const GameMode GM_None;
+        static const GameMode GM_Unspecified;
+        static const GameMode GM_Server;
+        static const GameMode GM_Client;
+        static const GameMode GM_Standalone;
+        static const GameMode GM_Dedicated;
+    };
+
+
+    class _OrxonoxExport Settings : public OrxonoxClass
+    {
     public:
-      void setConfigValues();
+        struct CommandLineArgument
+        {
+            std::string name_;
+            MultiTypeMath value_;
+            bool bHasDefaultValue_;
+        };
 
-      static const std::string& getDataPath();
+        void setConfigValues();
 
-      static void tsetDataPath(const std::string& path);
+        static const std::string& getDataPath();
+        static void tsetDataPath(const std::string& path);
+
+        static const GameMode& getGameMode();
+        static const GameMode& getGameMode(const std::string& name);
+        static void setGameMode(const GameMode& mode);
+        static void setGameMode(const std::string& mode);
+        static bool addGameMode(const GameMode* mode);
+
+        static const CommandLineArgument* getCommandLineArgument(const std::string& name);
+        template <class T>
+        static bool addCommandLineArgument(const std::string &name, const std::string& valueStr, const T& defaultValue);
 
     private:
-      Settings();
-      Settings(const Settings& instance);
-      ~Settings();
-      static Settings& getSingleton();
+        Settings();
+        Settings(const Settings& instance);
+        ~Settings() { }
+        static Settings& getInstance();
 
-      void _tsetDataPath(const std::string& path);
+        void _tsetDataPath(const std::string& path);
 
-      std::string dataPath_;               //!< Path to the game data
-  };
+        std::string dataPath_;                                        //!< Path to the game data
+        GameMode gameMode_;                                           //!< Current game mode
+        std::map<std::string, const GameMode*> gameModes_;            //!< Holds all game modes for easy string access
+        //! holds all command line arguments (even if not given!)
+        std::map<std::string, CommandLineArgument> commandArguments_;
+    };
+
+    /**
+    @brief
+        Returns the relative path to the game data.
+    */
+    inline const std::string& Settings::getDataPath()
+    {
+        return getInstance().dataPath_;
+    }
+
+    inline void Settings::tsetDataPath(const std::string& path)
+    {
+        getInstance()._tsetDataPath(path);
+    }
+
+    inline const GameMode& Settings::getGameMode()
+    {
+        return getInstance().gameMode_;
+    }
+
+    inline const GameMode& Settings::getGameMode(const std::string& name)
+    {
+        if (getInstance().gameModes_.find(name) != getInstance().gameModes_.end())
+            return *getInstance().gameModes_[name];
+        else
+        {
+            COUT(2) << "Warning: GameMode '" << name << "' doesn't exist." << std::endl;
+            return GameMode::GM_None;
+        }
+    }
+
+    inline void Settings::setGameMode(const GameMode& mode)
+    {
+        getInstance().gameMode_ = mode;
+    }
+
+    /**
+    @brief
+        Adds one argument of the command line to the map of command line arguments.
+    @param name
+        Name of the command line option.
+    @param valueStr
+        The value of the command line option as string
+    @param defaultValue
+        Default value for the option (marked when used).
+    @return
+        Dummy return value to enable code execution before main().
+    */
+    template <class T>
+    bool Settings::addCommandLineArgument(const std::string &name, const std::string& valueStr, const T& defaultValue)
+    {
+        T value;
+        bool useDefault = false;
+        if (valueStr == "")
+        {
+            // note: ArgReader only returns "" for not found arguments, " " otherwise for empty ones.
+            value = defaultValue;
+            useDefault = true;
+        }
+        else if (!convertValue(&value, valueStr))
+        {
+            COUT(1) << "Command Line: Couldn't read option '" << name << "'." << std::endl;
+            return false;
+        }
+        CommandLineArgument arg = { name, MultiTypeMath(value), useDefault };
+        getInstance().commandArguments_[name] = arg;
+        return true;
+    }
 }
 
Index: code/branches/gui/src/orxonox/gui/GUIManager.cc
===================================================================
--- code/branches/gui/src/orxonox/gui/GUIManager.cc	(revision 1638)
+++ code/branches/gui/src/orxonox/gui/GUIManager.cc	(revision 1638)
@@ -0,0 +1,295 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Implementation of the GUIManager class.
+*/
+
+#include "OrxonoxStableHeaders.h"
+#include "GUIManager.h"
+
+#include <OgreRenderWindow.h>
+#include <OgreCEGUIRenderer.h>
+#include <OgreRoot.h>
+#include <CEGUI.h>
+#include <CEGUILua.h>
+#include "core/input/InputManager.h"
+#include "core/input/SimpleInputState.h"
+#include "core/tolua/tolua_bind.h"
+#include "core/ConsoleCommand.h"
+#include "core/Exception.h"
+#include "core/Core.h"
+#include "tolua/tolua_bind.h"
+#include "GraphicsEngine.h"
+
+extern "C" {
+#include <lualib.h>
+#include <lauxlib.h>
+}
+
+namespace orxonox
+{
+    SetConsoleCommandShortcut(GUIManager, showGUI_s).setKeybindMode(KeybindMode::OnPress);
+
+    GUIManager::GUIManager()
+        : emptySceneManager_(0)
+        , backgroundSceneManager_(0)
+        , emptyCamera_(0)
+        , backgroundCamera_(0)
+        , viewport_(0)
+        , renderWindow_(0)
+        , guiRenderer_(0)
+        , resourceProvider_(0)
+        , scriptModule_(0)
+        , guiSystem_(0)
+        , state_(Uninitialised)
+    {
+    }
+
+    GUIManager::~GUIManager()
+    {
+        // TODO: destruct at least something
+    }
+
+    bool GUIManager::initialise()
+    {
+        using namespace CEGUI;
+        if (state_ == Uninitialised)
+        {
+            COUT(3) << "Intialising CEGUI." << std::endl;
+
+            try
+            {
+                // get the render window
+                renderWindow_ = GraphicsEngine::getSingleton().getRenderWindow();
+
+                // Full screen viewport with Z order = 0 (top most). Don't yet feed a camera (so nothing gets rendered)
+                this->viewport_ = renderWindow_->addViewport(0, 3);
+                this->viewport_->setOverlaysEnabled(false);
+                this->viewport_->setShadowsEnabled(false);
+                this->viewport_->setSkiesEnabled(false);
+                this->viewport_->setClearEveryFrame(false);
+
+                // Note: No SceneManager specified yet
+                this->guiRenderer_ = new OgreCEGUIRenderer(renderWindow_, Ogre::RENDER_QUEUE_MAIN, true, 3000);
+                this->resourceProvider_ = guiRenderer_->createResourceProvider();
+                this->resourceProvider_->setDefaultResourceGroup("GUI");
+                
+                // setup scripting
+                this->scriptModule_ = new LuaScriptModule();
+
+                // create the CEGUI system singleton
+                this->guiSystem_ = new System(this->guiRenderer_, this->resourceProvider_, 0, this->scriptModule_);
+                
+                // set the log level according to ours (translate by subtracting 1)
+                Logger::getSingleton().setLoggingLevel(
+                    (LoggingLevel)(Core::getSoftDebugLevel(OutputHandler::LD_Logfile) - 1));
+                
+                // do this after 'new CEGUI::Sytem' because that creates the lua state in the first place
+                tolua_Core_open(this->scriptModule_->getLuaState());
+                tolua_Orxonox_open(this->scriptModule_->getLuaState());
+
+                // register us as input handler
+                SimpleInputState* state = InputManager::createSimpleInputState("gui", 30);
+                state->setHandler(this);
+                state->setJoyStickHandler(new EmptyHandler());
+
+                // load the background scene
+                loadScenes();
+            }
+            catch (CEGUI::Exception& ex)
+            {
+                throw GeneralException(ex.getMessage().c_str(), ex.getLine(),
+                    ex.getFileName().c_str(), ex.getName().c_str());
+            }
+
+            state_ = Ready;
+        }
+        
+        return true;
+    }
+
+    void GUIManager::loadScenes()
+    {
+        // first of all, we need to have our own SceneManager for the GUI. The reason
+        // is that we might have multiple viewports when in play mode (e.g. the view of
+        // a camera fixed at the back of the ship). That forces us to create our own
+        // full screen viewport that is on top of all the others, but doesn't clear the
+        // port before rendering, so everything from the GUI gets on top eventually.
+        // But in order to realise that, we also need a SceneManager with an empty scene,
+        // because the SceneManager is responsible for the render queue.
+        this->emptySceneManager_ = Ogre::Root::getSingleton()
+            .createSceneManager(Ogre::ST_GENERIC, "GUI/EmptySceneManager");
+
+        // we also need a camera or we won't see anything at all.
+        // The camera settings don't matter at all for an empty scene since the GUI
+        // gets rendered on top of the screen rather than into the scene.
+        this->emptyCamera_ = this->emptySceneManager_->createCamera("GUI/EmptyCamera");
+
+        // Create another SceneManager that enables to display some 3D
+        // scene in the background of the main menu.
+        this->backgroundSceneManager_ = Ogre::Root::getSingleton()
+            .createSceneManager(Ogre::ST_GENERIC, "GUI/BackgroundSceneManager");
+        this->backgroundCamera_ = backgroundSceneManager_->createCamera("GUI/BackgroundCamera");
+
+        // TODO: create something 3D
+        try
+        {
+            this->scriptModule_->executeScriptFile("loadGUI.lua", "GUI");
+        }
+        catch (CEGUI::Exception& ex)
+        {
+            throw GeneralException(ex.getMessage().c_str(), ex.getLine(),
+                ex.getFileName().c_str(), ex.getName().c_str());
+        }
+    }
+
+    void GUIManager::showGUI(const std::string& name, bool showBackground)
+    {
+        if (state_ != Uninitialised)
+        {
+            if (state_ == OnDisplay)
+                _hideGUI();
+
+            COUT(3) << "Loading GUI " << name << std::endl;
+            try
+            {
+                if (showBackground)
+                {
+                    // currently, only an image is loaded. We could do 3D, see loadBackground.
+                    this->viewport_->setClearEveryFrame(true);
+                    this->guiRenderer_->setTargetSceneManager(this->backgroundSceneManager_);
+                    this->viewport_->setCamera(this->backgroundCamera_);
+
+                    lua_pushboolean(this->scriptModule_->getLuaState(), true);
+                    lua_setglobal(this->scriptModule_->getLuaState(), "showBackground");
+                }
+                else
+                {
+                    this->viewport_->setClearEveryFrame(false);
+                    this->guiRenderer_->setTargetSceneManager(this->emptySceneManager_);
+                    this->viewport_->setCamera(this->emptyCamera_);
+
+                    lua_pushboolean(this->scriptModule_->getLuaState(), false);
+                    lua_setglobal(this->scriptModule_->getLuaState(), "showBackground");
+                }
+
+                this->scriptModule_->executeScriptGlobal("showMainMenu");
+
+                InputManager::requestEnterState("gui");
+
+                this->state_ = OnDisplay;
+            }
+            catch (CEGUI::Exception& ex)
+            {
+                COUT(2) << "Error while executing lua script. Message:\n" << ex.getMessage() << std::endl;
+            }
+            catch (...)
+            {
+                COUT(2) << "Could show a menu due to unknown reasons." << std::endl;
+            }
+        }
+        else
+        {
+            COUT(2) << "Warning: GUI Manager not yet initialised, cannot load a GUI" << std::endl;
+        }
+    }
+
+    void GUIManager::_hideGUI()
+    {
+        if (this->state_ != OnDisplay)
+            return;
+        this->viewport_->setCamera(0);
+        this->state_ = Ready;
+        InputManager::requestLeaveState("gui");
+    }
+
+    void GUIManager::mouseButtonPressed(MouseButton::Enum id)
+    {
+        try
+        {
+            guiSystem_->injectMouseButtonDown(convertButton(id));
+        }
+        catch (CEGUI::ScriptException& ex)
+        {
+            // We simply ignore the exception and proceed
+            COUT(1) << ex.getMessage() << std::endl;
+        }
+    }
+
+    void GUIManager::mouseButtonReleased(MouseButton::Enum id)
+    {
+        try
+        {
+            guiSystem_->injectMouseButtonUp(convertButton(id));
+        }
+        catch (CEGUI::ScriptException& ex)
+        {
+            // We simply ignore the exception and proceed
+            COUT(1) << ex.getMessage() << std::endl;
+        }
+    }
+
+
+    /**
+    @brief
+        Returns a unique instance of GUIManager.
+    @return
+        The instance
+    */
+    GUIManager& GUIManager::getInstance()
+    {
+        static GUIManager instance;
+        return instance;
+    }
+
+    inline CEGUI::MouseButton GUIManager::convertButton(MouseButton::Enum button)
+    {
+        switch (button)
+        {
+        case MouseButton::Left:
+            return CEGUI::LeftButton;
+
+        case MouseButton::Right:
+            return CEGUI::RightButton;
+
+        case MouseButton::Middle:
+            return CEGUI::MiddleButton;
+
+        case MouseButton::Button3:
+            return CEGUI::X1Button;
+
+        case MouseButton::Button4:
+            return CEGUI::X2Button;
+
+        default:
+            return CEGUI::NoButton;
+        }
+    }
+}
Index: code/branches/gui/src/orxonox/gui/GUIManager.h
===================================================================
--- code/branches/gui/src/orxonox/gui/GUIManager.h	(revision 1638)
+++ code/branches/gui/src/orxonox/gui/GUIManager.h	(revision 1638)
@@ -0,0 +1,131 @@
+/*
+ *   ORXONOX - the hottest 3D action shooter ever to exist
+ *                    > www.orxonox.net <
+ *
+ *
+ *   License notice:
+ *
+ *   This program is free software; you can redistribute it and/or
+ *   modify it under the terms of the GNU General Public License
+ *   as published by the Free Software Foundation; either version 2
+ *   of the License, or (at your option) any later version.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program; if not, write to the Free Software
+ *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
+ *
+ *   Author:
+ *      Reto Grieder
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Declaration of the GUIManager class.
+*/
+
+#ifndef _GUIManager_H__
+#define _GUIManager_H__
+
+#include "OrxonoxPrereqs.h"
+#include <OgrePrerequisites.h>
+#include <CEGUIForwardRefs.h>
+#include <CEGUIInputEvent.h>
+#include <CEGUISystem.h>
+#include "core/input/InputInterfaces.h"
+
+// forward declarations
+namespace CEGUI
+{
+    class OgreCEGUIRenderer;
+    class LuaScriptModule;
+}
+
+namespace orxonox // tolua_export
+{ // tolua_export
+    /**
+    @brief
+        Provides a simple interface to CEGUI with tolua methods and console commands
+    */
+    class _OrxonoxExport GUIManager : public KeyHandler, public MouseHandler
+    /*
+    class GUIManager { // tolua_export
+    */
+    {
+    public:
+        enum State
+        {
+            Uninitialised,
+            Ready,
+            OnDisplay
+        };
+
+        bool initialise();
+        void tick(float dt);
+        void showGUI(const std::string& name, bool showBackground); // tolua_export
+        void _hideGUI(); // tolua_export
+
+        static GUIManager& getInstance(); // tolua_export
+        static void showGUI_s(const std::string& name, bool showBackground)
+        {
+            getInstance().showGUI(name, showBackground);
+        }
+
+    private:
+        GUIManager();
+        GUIManager(const GUIManager& instance);
+        ~GUIManager();
+
+        void keyPressed (const KeyEvent& evt)
+        { guiSystem_->injectKeyDown(evt.key); guiSystem_->injectChar(evt.text); }
+        void keyReleased(const KeyEvent& evt)
+        { guiSystem_->injectKeyUp(evt.key); }
+        void keyHeld    (const KeyEvent& evt)
+        { }
+
+        void mouseButtonPressed (MouseButton::Enum id);
+        void mouseButtonReleased(MouseButton::Enum id);
+        void mouseButtonHeld    (MouseButton::Enum id)
+        { }
+        void mouseMoved         (IntVector2 abs, IntVector2 rel, IntVector2 clippingSize)
+        { guiSystem_->injectMouseMove(rel.x, rel.y); }
+        void mouseScrolled      (int abs, int rel)
+        { guiSystem_->injectMouseWheelChange(rel);}
+
+        void tickInput(float dt) { }
+
+        void loadScenes();
+
+        Ogre::SceneManager*       emptySceneManager_;
+        Ogre::SceneManager*       backgroundSceneManager_;
+        Ogre::Camera*             emptyCamera_;
+        Ogre::Camera*             backgroundCamera_;
+        Ogre::Viewport*           viewport_;
+        Ogre::RenderWindow*       renderWindow_;
+        CEGUI::OgreCEGUIRenderer* guiRenderer_;
+        CEGUI::ResourceProvider*  resourceProvider_;
+        CEGUI::LuaScriptModule*   scriptModule_;
+        CEGUI::System*            guiSystem_;
+        CEGUI::Imageset*          backgroundImage_;
+
+        State state_;
+
+
+        static CEGUI::MouseButton convertButton(MouseButton::Enum button);
+    }; // tolua_export
+
+    inline void GUIManager::tick(float dt)
+    {
+        assert(guiSystem_);
+        guiSystem_->injectTimePulse(dt);
+    }
+} // tolua_export
+
+#endif /* _GUIManager_H__ */
Index: code/branches/gui/src/orxonox/gui/OgreCEGUIRenderer.cpp
===================================================================
--- code/branches/gui/src/orxonox/gui/OgreCEGUIRenderer.cpp	(revision 1638)
+++ code/branches/gui/src/orxonox/gui/OgreCEGUIRenderer.cpp	(revision 1638)
@@ -0,0 +1,800 @@
+/************************************************************************
+    filename: 	OgreCEGUIRenderer.cpp
+    created:	11/5/2004
+    author:		Paul D Turner
+    
+    purpose:	Implementation of Renderer class for Ogre engine
+*************************************************************************/
+/*************************************************************************
+    Crazy Eddie's GUI System (http://www.cegui.org.uk)
+    Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+*************************************************************************/
+
+#include <CEGUIImagesetManager.h>
+#include <CEGUIImageset.h>
+#include <CEGUIImage.h>
+#include <CEGUIExceptions.h>
+#include <CEGUISystem.h>
+
+#include "OgreCEGUIRenderer.h"
+#include "OgreCEGUITexture.h"
+#include "OgreCEGUIResourceProvider.h"
+
+#include <OgreRenderSystem.h>
+#include <OgreRoot.h>
+#include <OgreHardwareBufferManager.h>
+#include <OgreRenderWindow.h>
+
+// Start of CEGUI namespace section
+namespace CEGUI
+{
+/*************************************************************************
+    Constants definitions
+*************************************************************************/
+const size_t	OgreCEGUIRenderer::VERTEX_PER_QUAD			= 6;
+const size_t	OgreCEGUIRenderer::VERTEX_PER_TRIANGLE		= 3;
+const size_t	OgreCEGUIRenderer::VERTEXBUFFER_INITIAL_CAPACITY	= 256;
+const size_t    OgreCEGUIRenderer::UNDERUSED_FRAME_THRESHOLD = 50000; // halfs buffer every 8 minutes on 100fps
+
+/*************************************************************************
+    Utility function to create a render operation and vertex buffer to render quads
+*************************************************************************/
+static void createQuadRenderOp(Ogre::RenderOperation &d_render_op, 
+    Ogre::HardwareVertexBufferSharedPtr &d_buffer, size_t nquads)
+{
+    using namespace Ogre;
+    // Create and initialise the Ogre specific parts required for use in rendering later.
+    d_render_op.vertexData = new VertexData;
+    d_render_op.vertexData->vertexStart = 0;
+
+    // setup vertex declaration for the vertex format we use
+    VertexDeclaration* vd = d_render_op.vertexData->vertexDeclaration;
+    size_t vd_offset = 0;
+    vd->addElement(0, vd_offset, VET_FLOAT3, VES_POSITION);
+    vd_offset += VertexElement::getTypeSize(VET_FLOAT3);
+    vd->addElement(0, vd_offset, VET_COLOUR, VES_DIFFUSE);
+    vd_offset += VertexElement::getTypeSize(VET_COLOUR);
+    vd->addElement(0, vd_offset, VET_FLOAT2, VES_TEXTURE_COORDINATES);
+
+    // create hardware vertex buffer
+    d_buffer = HardwareBufferManager::getSingleton().createVertexBuffer(vd->getVertexSize(0), nquads,  
+        HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE, false);
+
+    // bind vertex buffer
+    d_render_op.vertexData->vertexBufferBinding->setBinding(0, d_buffer);
+
+    // complete render operation basic initialisation
+    d_render_op.operationType = RenderOperation::OT_TRIANGLE_LIST;
+    d_render_op.useIndexes = false;
+}
+
+static void destroyQuadRenderOp(Ogre::RenderOperation &d_render_op, 
+    Ogre::HardwareVertexBufferSharedPtr &d_buffer)
+{
+    delete d_render_op.vertexData;
+    d_render_op.vertexData = 0;
+    d_buffer.setNull();
+}
+
+/*************************************************************************
+    Constructor
+*************************************************************************/
+OgreCEGUIRenderer::OgreCEGUIRenderer(Ogre::RenderWindow* window, Ogre::uint8 queue_id, bool post_queue, uint max_quads)
+{
+    constructor_impl(window, queue_id, post_queue, max_quads);
+}
+
+
+/*************************************************************************
+    Constructor (specifying scene manager)
+*************************************************************************/
+OgreCEGUIRenderer::OgreCEGUIRenderer(Ogre::RenderWindow* window, Ogre::uint8 queue_id, bool post_queue, uint max_quads, Ogre::SceneManager* scene_manager)
+{
+    constructor_impl(window, queue_id, post_queue, max_quads);
+
+    // hook into ogre rendering system
+    setTargetSceneManager(scene_manager);
+}
+
+
+/*************************************************************************
+    Destructor
+*************************************************************************/
+OgreCEGUIRenderer::~OgreCEGUIRenderer(void)
+{
+    setTargetSceneManager(NULL);
+
+    if (d_ourlistener)
+    {
+        delete d_ourlistener;
+    }
+
+    // cleanup vertex data we allocated in constructor
+    destroyQuadRenderOp(d_render_op, d_buffer);
+    destroyQuadRenderOp(d_direct_render_op, d_direct_buffer);
+
+    destroyAllTextures();
+}
+
+
+/*************************************************************************
+    add's a quad to the list to be rendered
+*************************************************************************/
+void OgreCEGUIRenderer::addQuad(const Rect& dest_rect, float z, const Texture* tex, const Rect& texture_rect, const ColourRect& colours, QuadSplitMode quad_split_mode)
+{
+    // if not queueing, render directly (as in, right now!). This is used for the mouse cursor.
+    if (!d_queueing)
+    {
+        renderQuadDirect(dest_rect, z, tex, texture_rect, colours, quad_split_mode);
+    }
+    else
+    {
+        d_sorted = false;
+        QuadInfo quad;
+        
+        // set quad position, flipping y co-ordinates, and applying appropriate texel origin offset
+        quad.position.d_left	= dest_rect.d_left;
+        quad.position.d_right	= dest_rect.d_right;
+        quad.position.d_top		= d_display_area.getHeight() - dest_rect.d_top;
+        quad.position.d_bottom	= d_display_area.getHeight() - dest_rect.d_bottom;
+        quad.position.offset(d_texelOffset);
+
+        // convert quad co-ordinates for a -1 to 1 co-ordinate system.
+        quad.position.d_left	/= (d_display_area.getWidth() * 0.5f);
+        quad.position.d_right	/= (d_display_area.getWidth() * 0.5f);
+        quad.position.d_top		/= (d_display_area.getHeight() * 0.5f);
+        quad.position.d_bottom	/= (d_display_area.getHeight() * 0.5f);
+        quad.position.offset(Point(-1.0f, -1.0f));
+
+        quad.z				= -1 + z;
+        quad.texture		= ((OgreCEGUITexture*)tex)->getOgreTexture();
+        quad.texPosition	= texture_rect;
+
+        // covert colours for ogre, note that top / bottom are switched.
+        quad.topLeftCol		= colourToOgre(colours.d_bottom_left);
+        quad.topRightCol	= colourToOgre(colours.d_bottom_right);
+        quad.bottomLeftCol	= colourToOgre(colours.d_top_left);
+        quad.bottomRightCol	= colourToOgre(colours.d_top_right);
+        
+        // set quad split mode
+        quad.splitMode = quad_split_mode;
+
+        d_quadlist.insert(quad);
+    }
+}
+
+
+
+/*************************************************************************
+perform final rendering for all queued renderable quads.
+*************************************************************************/
+void OgreCEGUIRenderer::doRender(void)
+{
+    // Render if overlays enabled and the quad list is not empty
+
+    // ORXONOX CHANGE: Even render when OverlaysEnabled is deactivated
+    // The reason is that we don't want the HUD to be shown in the viewport of the
+    // GUI (uses its own viewport to be able render on top of all viewports).
+    // But since we don't use overlays in the GUI, it doesn't matter.
+    //if (d_render_sys->_getViewport()->getOverlaysEnabled() && !d_quadlist.empty())
+    if (!d_quadlist.empty())
+    {
+        /// Quad list needs to be sorted and thus the vertex buffer rebuilt. If not, we can
+        /// reuse the vertex buffer resulting in a nice speed gain.
+        if(!d_sorted)
+        {
+            sortQuads();
+            /// Resize vertex buffer if it is too small
+            size_t size = d_buffer->getNumVertices();
+            size_t requestedSize = d_quadlist.size()*VERTEX_PER_QUAD;
+            if(size < requestedSize)
+            {
+                /// Double buffer size until smaller than requested size
+                while(size < requestedSize)
+                    size = size * 2;
+                /// Reallocate the buffer
+                destroyQuadRenderOp(d_render_op, d_buffer);
+                createQuadRenderOp(d_render_op, d_buffer, size);
+            }
+            else if(requestedSize < size/2 && d_underused_framecount >= UNDERUSED_FRAME_THRESHOLD)
+            {
+                /// Resize vertex buffer if it has been to big for too long
+                size = size / 2;
+                destroyQuadRenderOp(d_render_op, d_buffer);
+                createQuadRenderOp(d_render_op, d_buffer, size);
+                /// Reset underused framecount so it takes another UNDERUSED_FRAME_THRESHOLD to half again
+                d_underused_framecount = 0;
+            }
+            /// Fill the buffer
+            QuadVertex*	buffmem;
+            buffmem = (QuadVertex*)d_buffer->lock(Ogre::HardwareVertexBuffer::HBL_DISCARD);
+            // iterate over each quad in the list
+            for (QuadList::iterator i = d_quadlist.begin(); i != d_quadlist.end(); ++i)
+            {
+                const QuadInfo& quad = (*i);
+                // setup Vertex 1...
+                buffmem->x = quad.position.d_left;
+                buffmem->y = quad.position.d_bottom;
+                buffmem->z = quad.z;
+                buffmem->diffuse = quad.topLeftCol;
+                buffmem->tu1 = quad.texPosition.d_left;
+                buffmem->tv1 = quad.texPosition.d_bottom;
+                ++buffmem;
+    
+                // setup Vertex 2...
+                
+                // top-left to bottom-right diagonal
+                if (quad.splitMode == TopLeftToBottomRight)
+                {
+                    buffmem->x = quad.position.d_right;
+                    buffmem->y = quad.position.d_bottom;
+                    buffmem->z = quad.z;
+                    buffmem->diffuse = quad.topRightCol;
+                    buffmem->tu1 = quad.texPosition.d_right;
+                    buffmem->tv1 = quad.texPosition.d_bottom;
+                }
+                // bottom-left to top-right diagonal
+                else
+                {
+                    buffmem->x = quad.position.d_right;
+                    buffmem->y = quad.position.d_top;
+                    buffmem->z = quad.z;
+                    buffmem->diffuse = quad.bottomRightCol;
+                    buffmem->tu1 = quad.texPosition.d_right;
+                    buffmem->tv1 = quad.texPosition.d_top;
+                }
+                ++buffmem;
+    
+                // setup Vertex 3...
+                buffmem->x = quad.position.d_left;
+                buffmem->y = quad.position.d_top;
+                buffmem->z = quad.z;
+                buffmem->diffuse = quad.bottomLeftCol;
+                buffmem->tu1 = quad.texPosition.d_left;
+                buffmem->tv1 = quad.texPosition.d_top;
+                ++buffmem;
+    
+                // setup Vertex 4...
+                buffmem->x = quad.position.d_right;
+                buffmem->y = quad.position.d_bottom;
+                buffmem->z = quad.z;
+                buffmem->diffuse = quad.topRightCol;
+                buffmem->tu1 = quad.texPosition.d_right;
+                buffmem->tv1 = quad.texPosition.d_bottom;
+                ++buffmem;
+    
+                // setup Vertex 5...
+                buffmem->x = quad.position.d_right;
+                buffmem->y = quad.position.d_top;
+                buffmem->z = quad.z;
+                buffmem->diffuse = quad.bottomRightCol;
+                buffmem->tu1 = quad.texPosition.d_right;
+                buffmem->tv1 = quad.texPosition.d_top;
+                ++buffmem;
+    
+                // setup Vertex 6...
+                
+                // top-left to bottom-right diagonal
+                if (quad.splitMode == TopLeftToBottomRight)
+                {
+                    buffmem->x = quad.position.d_left;
+                    buffmem->y = quad.position.d_top;
+                    buffmem->z = quad.z;
+                    buffmem->diffuse = quad.bottomLeftCol;
+                    buffmem->tu1 = quad.texPosition.d_left;
+                    buffmem->tv1 = quad.texPosition.d_top;
+                }
+                // bottom-left to top-right diagonal
+                else
+                {
+                    buffmem->x = quad.position.d_left;
+                    buffmem->y = quad.position.d_bottom;
+                    buffmem->z = quad.z;
+                    buffmem->diffuse = quad.topLeftCol;
+                    buffmem->tu1 = quad.texPosition.d_left;
+                    buffmem->tv1 = quad.texPosition.d_bottom;
+                }
+                ++buffmem;
+            }
+    
+            // ensure we leave the buffer in the unlocked state
+            d_buffer->unlock();
+        }
+        
+        /// Render the buffer
+        d_bufferPos = 0;
+        bool first = true;
+
+        // Iterate over each quad in the list and render it
+        QuadList::iterator i = d_quadlist.begin();
+        while(i != d_quadlist.end())
+        {
+            
+            d_currTexture = i->texture;
+            d_render_op.vertexData->vertexStart = d_bufferPos;
+            for (; i != d_quadlist.end(); ++i)
+            {
+                const QuadInfo& quad = (*i);
+                if (d_currTexture != quad.texture)
+                {
+                    /// If it has a different texture, render this quad in next operation
+                    /// also need to reset render states
+                    first = true;
+                    break;
+                }
+                d_bufferPos += VERTEX_PER_QUAD;
+            }
+            d_render_op.vertexData->vertexCount = d_bufferPos - d_render_op.vertexData->vertexStart;
+            /// Set texture, and do the render
+            d_render_sys->_setTexture(0, true, d_currTexture);
+            if (first)
+            {
+                initRenderStates();
+                first = false;
+            }
+            d_render_sys->_render(d_render_op);
+        }
+
+    }
+    /// Count frames to check if utilization of vertex buffer was below half the capacity for 500,000 frames
+    if(d_bufferPos < d_buffer->getNumVertices()/2)
+       d_underused_framecount++;
+    else
+       d_underused_framecount = 0;
+}
+
+
+/*************************************************************************
+    clear the queue
+*************************************************************************/
+void OgreCEGUIRenderer::clearRenderList(void)
+{
+    d_sorted = true;
+    d_quadlist.clear();
+}
+
+
+/*************************************************************************
+    create an empty texture
+*************************************************************************/
+Texture* OgreCEGUIRenderer::createTexture(void)
+{
+    OgreCEGUITexture* tex = new OgreCEGUITexture(this);
+    d_texturelist.push_back(tex);
+    return tex;
+}
+
+
+/*************************************************************************
+    create a texture and load it with the specified file.
+*************************************************************************/
+Texture* OgreCEGUIRenderer::createTexture(const String& filename, const String& resourceGroup)
+{
+    OgreCEGUITexture* tex = (OgreCEGUITexture*)createTexture();
+    tex->loadFromFile(filename, resourceGroup);
+
+    return tex;
+}
+
+
+/*************************************************************************
+    create a texture and set it to the specified size
+*************************************************************************/
+Texture* OgreCEGUIRenderer::createTexture(float size)
+{
+    OgreCEGUITexture* tex = (OgreCEGUITexture*)createTexture();
+    tex->setOgreTextureSize((uint)size);
+
+    return tex;
+}
+
+
+/*************************************************************************
+    destroy the given texture
+*************************************************************************/
+void OgreCEGUIRenderer::destroyTexture(Texture* texture)
+{
+    if (texture != NULL)
+    {
+        OgreCEGUITexture* tex = (OgreCEGUITexture*)texture;
+
+        d_texturelist.remove(tex);
+        delete tex;
+    }
+}
+
+
+/*************************************************************************
+    destroy all textures still active
+*************************************************************************/
+void OgreCEGUIRenderer::destroyAllTextures(void)
+{
+    while (!d_texturelist.empty())
+    {
+        destroyTexture(*(d_texturelist.begin()));
+    }
+}
+
+
+/*************************************************************************
+    setup states etc	
+*************************************************************************/
+void OgreCEGUIRenderer::initRenderStates(void)
+{
+    using namespace Ogre;
+
+    // set-up matrices
+    d_render_sys->_setWorldMatrix(Matrix4::IDENTITY);
+    d_render_sys->_setViewMatrix(Matrix4::IDENTITY);
+    d_render_sys->_setProjectionMatrix(Matrix4::IDENTITY);
+
+    // initialise render settings
+    d_render_sys->setLightingEnabled(false);
+    d_render_sys->_setDepthBufferParams(false, false);
+    d_render_sys->_setDepthBias(0, 0);
+    d_render_sys->_setCullingMode(CULL_NONE);
+    d_render_sys->_setFog(FOG_NONE);
+    d_render_sys->_setColourBufferWriteEnabled(true, true, true, true);
+    d_render_sys->unbindGpuProgram(GPT_FRAGMENT_PROGRAM);
+    d_render_sys->unbindGpuProgram(GPT_VERTEX_PROGRAM);
+    d_render_sys->setShadingType(SO_GOURAUD);
+    d_render_sys->_setPolygonMode(PM_SOLID);
+
+    // initialise texture settings
+    d_render_sys->_setTextureCoordCalculation(0, TEXCALC_NONE);
+    d_render_sys->_setTextureCoordSet(0, 0);
+    d_render_sys->_setTextureUnitFiltering(0, FO_LINEAR, FO_LINEAR, FO_POINT);
+    d_render_sys->_setTextureAddressingMode(0, d_uvwAddressMode);
+    d_render_sys->_setTextureMatrix(0, Matrix4::IDENTITY);
+    d_render_sys->_setAlphaRejectSettings(CMPF_ALWAYS_PASS, 0);
+    d_render_sys->_setTextureBlendMode(0, d_colourBlendMode);
+    d_render_sys->_setTextureBlendMode(0, d_alphaBlendMode);
+    d_render_sys->_disableTextureUnitsFrom(1);
+
+    // enable alpha blending
+    d_render_sys->_setSceneBlending(SBF_SOURCE_ALPHA, SBF_ONE_MINUS_SOURCE_ALPHA);
+}
+
+
+ 
+/*************************************************************************
+    sort quads list according to texture	
+*************************************************************************/
+void OgreCEGUIRenderer::sortQuads(void)
+{
+    if (!d_sorted)
+    {
+        d_sorted = true;
+    }
+
+}
+
+/*************************************************************************
+render a quad directly to the display
+*************************************************************************/
+void OgreCEGUIRenderer::renderQuadDirect(const Rect& dest_rect, float z, const Texture* tex, const Rect& texture_rect, const ColourRect& colours, QuadSplitMode quad_split_mode)
+{
+    // ORXONOX CHANGE: Even render when OverlaysEnabled is deactivated
+    // The reason is that we don't want the HUD to be shown in the viewport of the
+    // GUI (uses its own viewport to be able render on top of all viewports).
+    // But since we don't use overlays in the GUI, it doesn't matter.
+    //if (d_render_sys->_getViewport()->getOverlaysEnabled())
+    if (true)
+    {
+        z = -1 + z;
+
+        Rect final_rect;
+
+        // set quad position, flipping y co-ordinates, and applying appropriate texel origin offset
+        final_rect.d_left	= dest_rect.d_left;
+        final_rect.d_right	= dest_rect.d_right;
+        final_rect.d_top	= d_display_area.getHeight() - dest_rect.d_top;
+        final_rect.d_bottom	= d_display_area.getHeight() - dest_rect.d_bottom;
+        final_rect.offset(d_texelOffset);
+
+        // convert quad co-ordinates for a -1 to 1 co-ordinate system.
+        final_rect.d_left	/= (d_display_area.getWidth() * 0.5f);
+        final_rect.d_right	/= (d_display_area.getWidth() * 0.5f);
+        final_rect.d_top	/= (d_display_area.getHeight() * 0.5f);
+        final_rect.d_bottom	/= (d_display_area.getHeight() * 0.5f);
+        final_rect.offset(Point(-1.0f, -1.0f));
+
+        // convert colours for ogre, note that top / bottom are switched.
+        uint32 topLeftCol	= colourToOgre(colours.d_bottom_left);
+        uint32 topRightCol	= colourToOgre(colours.d_bottom_right);
+        uint32 bottomLeftCol	= colourToOgre(colours.d_top_left);
+        uint32 bottomRightCol= colourToOgre(colours.d_top_right);
+
+        QuadVertex*	buffmem = (QuadVertex*)d_direct_buffer->lock(Ogre::HardwareVertexBuffer::HBL_DISCARD);
+
+        // setup Vertex 1...
+        buffmem->x	= final_rect.d_left;
+        buffmem->y	= final_rect. d_bottom;
+        buffmem->z	= z;
+        buffmem->diffuse = topLeftCol;
+        buffmem->tu1	= texture_rect.d_left;
+        buffmem->tv1	= texture_rect.d_bottom;
+        ++buffmem;
+
+        // setup Vertex 2...
+        
+        // top-left to bottom-right diagonal
+        if (quad_split_mode == TopLeftToBottomRight)
+        {
+            buffmem->x	= final_rect.d_right;
+            buffmem->y = final_rect.d_bottom;
+            buffmem->z	= z;
+            buffmem->diffuse = topRightCol;
+            buffmem->tu1	= texture_rect.d_right;
+            buffmem->tv1	= texture_rect.d_bottom;
+            ++buffmem;
+        }
+        // bottom-left to top-right diagonal
+        else
+        {
+            buffmem->x	= final_rect.d_right;
+            buffmem->y = final_rect.d_top;
+            buffmem->z	= z;
+            buffmem->diffuse = bottomRightCol;
+            buffmem->tu1	= texture_rect.d_right;
+            buffmem->tv1	= texture_rect.d_top;
+            ++buffmem;
+        }
+
+        // setup Vertex 3...
+        buffmem->x	= final_rect.d_left;
+        buffmem->y	= final_rect.d_top;
+        buffmem->z	= z;
+        buffmem->diffuse = bottomLeftCol;
+        buffmem->tu1	= texture_rect.d_left;
+        buffmem->tv1	= texture_rect.d_top;
+        ++buffmem;
+
+        // setup Vertex 4...
+        buffmem->x	= final_rect.d_right;
+        buffmem->y	= final_rect.d_bottom;
+        buffmem->z	= z;
+        buffmem->diffuse = topRightCol;
+        buffmem->tu1	= texture_rect.d_right;
+        buffmem->tv1	= texture_rect.d_bottom;
+        ++buffmem;
+
+        // setup Vertex 5...
+        buffmem->x	= final_rect.d_right;
+        buffmem->y	= final_rect.d_top;
+        buffmem->z	= z;
+        buffmem->diffuse = bottomRightCol;
+        buffmem->tu1	= texture_rect.d_right;
+        buffmem->tv1	= texture_rect.d_top;
+        ++buffmem;
+
+        // setup Vertex 6...
+        
+        // top-left to bottom-right diagonal
+        if (quad_split_mode == TopLeftToBottomRight)
+        {
+            buffmem->x	= final_rect.d_left;
+            buffmem->y = final_rect.d_top;
+            buffmem->z	= z;
+            buffmem->diffuse = bottomLeftCol;
+            buffmem->tu1	= texture_rect.d_left;
+            buffmem->tv1	= texture_rect.d_top;
+        }
+        // bottom-left to top-right diagonal
+        else
+        {
+            buffmem->x	= final_rect.d_left;
+            buffmem->y = final_rect.d_bottom;
+            buffmem->z	= z;
+            buffmem->diffuse = topLeftCol;
+            buffmem->tu1	= texture_rect.d_left;
+            buffmem->tv1	= texture_rect.d_bottom;
+        }
+
+        d_direct_buffer->unlock();
+
+        //
+        // perform rendering...
+        //
+        d_render_sys->_setTexture(0, true, ((OgreCEGUITexture*)tex)->getOgreTexture()->getName());
+        initRenderStates();
+        d_direct_render_op.vertexData->vertexCount = VERTEX_PER_QUAD;
+        d_render_sys->_render(d_direct_render_op);
+    }
+
+}
+
+/*************************************************************************
+    convert ARGB colour value to whatever the Ogre render system is
+    expecting.	
+*************************************************************************/
+uint32 OgreCEGUIRenderer::colourToOgre(const colour& col) const
+{
+    Ogre::ColourValue cv(col.getRed(), col.getGreen(), col.getBlue(), col.getAlpha());
+
+    uint32 final;
+    d_render_sys->convertColourValue(cv, &final);
+
+    return final;
+}
+
+
+/*************************************************************************
+    Set the scene manager to be used for rendering the GUI.	
+*************************************************************************/
+void OgreCEGUIRenderer::setTargetSceneManager(Ogre::SceneManager* scene_manager)
+{
+    // unhook from current scene manager.
+    if (d_sceneMngr != NULL)
+    {
+        d_sceneMngr->removeRenderQueueListener(d_ourlistener);
+        d_sceneMngr = NULL;
+    }
+
+    // hook new scene manager if that is not NULL
+    if (scene_manager != NULL)
+    {
+        d_sceneMngr = scene_manager;
+        d_sceneMngr->addRenderQueueListener(d_ourlistener);
+    }
+
+}
+
+
+/*************************************************************************
+    Set the target render queue for GUI rendering.	
+*************************************************************************/
+void OgreCEGUIRenderer::setTargetRenderQueue(Ogre::uint8 queue_id, bool post_queue)
+{
+    d_queue_id		= queue_id;
+    d_post_queue	= post_queue;
+
+    if (d_ourlistener != NULL)
+    {
+        d_ourlistener->setTargetRenderQueue(queue_id);
+        d_ourlistener->setPostRenderQueue(post_queue);
+    }
+
+}
+
+
+/*************************************************************************
+    perform main work of the constructor
+*************************************************************************/
+void OgreCEGUIRenderer::constructor_impl(Ogre::RenderWindow* window, Ogre::uint8 queue_id, bool post_queue, uint max_quads)
+{
+    using namespace Ogre;
+
+    // initialise the renderer fields
+    d_queueing		= true;
+    d_queue_id		= queue_id;
+    d_currTexture.isNull();
+    d_post_queue	= post_queue;
+    d_sceneMngr		= NULL;
+    d_bufferPos		= 0;
+    d_sorted		= true;
+    d_ogre_root		= Root::getSingletonPtr();
+    d_render_sys	= d_ogre_root->getRenderSystem();
+    // set ID string
+    d_identifierString = "CEGUI::OgreRenderer - Official Ogre based renderer module for CEGUI";
+
+    // Create and initialise the Ogre specific parts required for use in rendering later.
+    // Main GUI
+    createQuadRenderOp(d_render_op, d_buffer, VERTEXBUFFER_INITIAL_CAPACITY);
+    d_underused_framecount = 0;
+
+    // Mouse cursor
+    createQuadRenderOp(d_direct_render_op, d_direct_buffer, VERTEX_PER_QUAD);
+
+    // Discover display settings and setup d_display_area
+    d_display_area.d_left	= 0;
+    d_display_area.d_top	= 0;
+    d_display_area.d_right	= window->getWidth();
+    d_display_area.d_bottom	= window->getHeight();
+
+    // initialise required texel offset
+    d_texelOffset = Point((float)d_render_sys->getHorizontalTexelOffset(), -(float)d_render_sys->getVerticalTexelOffset());
+
+    // create listener which will handler the rendering side of things for us.
+    d_ourlistener = new CEGUIRQListener(this, queue_id, post_queue);
+
+    // Initialise blending modes to be used.
+    d_colourBlendMode.blendType	= Ogre::LBT_COLOUR;
+    d_colourBlendMode.source1	= Ogre::LBS_TEXTURE;
+    d_colourBlendMode.source2	= Ogre::LBS_DIFFUSE;
+    d_colourBlendMode.operation	= Ogre::LBX_MODULATE;
+
+    d_alphaBlendMode.blendType	= Ogre::LBT_ALPHA;
+    d_alphaBlendMode.source1	= Ogre::LBS_TEXTURE;
+    d_alphaBlendMode.source2	= Ogre::LBS_DIFFUSE;
+    d_alphaBlendMode.operation	= Ogre::LBX_MODULATE;
+
+    d_uvwAddressMode.u = Ogre::TextureUnitState::TAM_CLAMP;
+    d_uvwAddressMode.v = Ogre::TextureUnitState::TAM_CLAMP;
+    d_uvwAddressMode.w = Ogre::TextureUnitState::TAM_CLAMP;
+}
+
+
+/*************************************************************************
+    Create a texture from an existing Ogre::TexturePtr object	
+*************************************************************************/
+Texture* OgreCEGUIRenderer::createTexture(Ogre::TexturePtr& texture)
+{
+    OgreCEGUITexture* t = (OgreCEGUITexture*)createTexture();
+
+    if (!texture.isNull())
+    {
+        t->setOgreTexture(texture);
+    }
+
+    return t;
+
+}
+
+/*************************************************************************
+    Create a resource provider object
+*************************************************************************/
+ResourceProvider* OgreCEGUIRenderer::createResourceProvider(void)
+{
+    d_resourceProvider = new OgreCEGUIResourceProvider();
+    return d_resourceProvider;
+}
+
+/*************************************************************************
+Set the size of the display in pixels.	
+*************************************************************************/
+void OgreCEGUIRenderer::setDisplaySize(const Size& sz)
+{
+    if (d_display_area.getSize() != sz)
+    {
+        d_display_area.setSize(sz);
+
+        EventArgs args;
+        fireEvent(EventDisplaySizeChanged, args, EventNamespace);
+    }
+
+}
+
+/*************************************************************************
+    Callback from Ogre invoked before other stuff in our target queue
+    is rendered
+*************************************************************************/
+void CEGUIRQListener::renderQueueStarted(Ogre::uint8 id, const Ogre::String& invocation, 
+                                         bool& skipThisQueue)
+{
+    if ((!d_post_queue) && (d_queue_id == id))
+    {
+        CEGUI::System::getSingleton().renderGUI();
+    }
+
+}
+
+
+/*************************************************************************
+Callback from Ogre invoked after other stuff in our target queue
+is rendered
+*************************************************************************/
+void CEGUIRQListener::renderQueueEnded(Ogre::uint8 id, const Ogre::String& invocation, bool& repeatThisQueue)
+{
+    if ((d_post_queue) && (d_queue_id == id))
+    {
+        CEGUI::System::getSingleton().renderGUI();
+    }
+
+}
+
+} // End of  CEGUI namespace section
Index: code/branches/gui/src/orxonox/gui/OgreCEGUIRenderer.h
===================================================================
--- code/branches/gui/src/orxonox/gui/OgreCEGUIRenderer.h	(revision 1638)
+++ code/branches/gui/src/orxonox/gui/OgreCEGUIRenderer.h	(revision 1638)
@@ -0,0 +1,464 @@
+/************************************************************************
+    filename: 	OgreCEGUIRenderer.h
+    created:	11/5/2004
+    author:		Paul D Turner
+
+    purpose:	Interface for main Ogre GUI renderer class
+*************************************************************************/
+/*************************************************************************
+    Crazy Eddie's GUI System (http://www.cegui.org.uk)
+    Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+*************************************************************************/
+/*************************************************************************
+    This file contains code that is specific to Ogre (http://www.ogre3d.org)
+*************************************************************************/
+#ifndef _OgreCEGUIRenderer_h_
+#define _OgreCEGUIRenderer_h_
+
+#include <CEGUIBase.h>
+#include <CEGUIRenderer.h>
+#include <CEGUITexture.h>
+
+#include <OgreRenderQueueListener.h>
+#include <OgreSceneManagerEnumerator.h>
+#include <OgreTextureUnitState.h>
+
+#if (OGRE_PLATFORM == OGRE_PLATFORM_WIN32) && !defined(OGRE_STATIC_LIB)
+#   ifdef OGRE_GUIRENDERER_EXPORTS
+#       define OGRE_GUIRENDERER_API __declspec(dllexport)
+#   else
+#       if defined(__MINGW32__)
+#           define OGRE_GUIRENDERER_API
+#       else
+#           define OGRE_GUIRENDERER_API __declspec(dllimport)
+#       endif
+#   endif
+#elif defined ( OGRE_GCC_VISIBILITY )
+#    define OGRE_GUIRENDERER_API  __attribute__ ((visibility("default")))
+#else
+#    define OGRE_GUIRENDERER_API
+#endif
+
+
+// Start of CEGUI namespace section
+namespace CEGUI
+{
+/*************************************************************************
+    Forward refs
+*************************************************************************/
+class OgreCEGUITexture;
+class OgreCEGUIRenderer;
+
+
+/*!
+\brief
+    RenderQueueListener based class used to hook into the ogre rendering system
+*/
+class _OgrePrivate CEGUIRQListener : public Ogre::RenderQueueListener
+{
+public:
+    CEGUIRQListener(OgreCEGUIRenderer* renderer, Ogre::uint8 queue_id, bool post_queue)
+    {
+        d_renderer		= renderer;
+        d_queue_id		= queue_id;
+        d_post_queue	= post_queue;
+    }
+
+    virtual ~CEGUIRQListener() {}
+
+    virtual void	renderQueueStarted(Ogre::uint8 id, const Ogre::String& invocation, bool& skipThisQueue);
+    virtual void	renderQueueEnded(Ogre::uint8 id, const Ogre::String& invocation, bool& repeatThisQueue);
+
+    // methods for adjusting target queue settings
+    void	setTargetRenderQueue(Ogre::uint8 queue_id)		{d_queue_id = queue_id;}
+    void	setPostRenderQueue(bool post_queue)		{d_post_queue = post_queue;}
+
+private:
+    /*************************************************************************
+        Implementation Data
+    *************************************************************************/
+    OgreCEGUIRenderer*				d_renderer;		//!< CEGUI renderer object for Ogre.
+    Ogre::uint8	d_queue_id;		//!< ID of the queue that we are hooked into
+    bool						d_post_queue;	//!< true if we render after everything else in our queue.
+};
+
+
+/*!
+\brief
+    Renderer class to interface with Ogre engine.
+*/
+class OGRE_GUIRENDERER_API OgreCEGUIRenderer : public Renderer
+{
+public:
+    /*!
+    \brief
+        Constructor for renderer class that uses Ogre for rendering. Note that if
+        you use this option you must call setTargetSceneManager before rendering.
+
+    \param window
+        Pointer to an Ogre::RenderWindow object.
+
+    \param queue_id
+        Ogre::uint8 value that specifies where the GUI should appear in the ogre rendering output.
+
+    \param post_queue
+        set to true to have GUI rendered after render queue \a queue_id, or false to have the GUI rendered before render queue
+        \a queue_id.
+
+    \param max_quads
+        Obsolete.  Set to 0.
+
+    */
+    OgreCEGUIRenderer(Ogre::RenderWindow* window,
+        Ogre::uint8 queue_id = Ogre::RENDER_QUEUE_OVERLAY,
+        bool post_queue = false, uint max_quads = 0);
+
+
+    /*!
+    \brief
+        Constructor for renderer class that uses Ogre for rendering.
+
+    \param window
+        Pointer to an Ogre::RenderWindow object.
+
+    \param queue_id
+        Ogre::uint8 value that specifies where the GUI should appear in the ogre rendering output.
+
+    \param post_queue
+        set to true to have GUI rendered after render queue \a queue_id, or false to have the GUI rendered before render queue
+        \a queue_id.
+
+    \param max_quads
+        Obsolete.  Set to 0.
+
+    \param scene_manager
+        Pointer to an Ogre::SceneManager object that is to be used for GUI rendering.
+    */
+    OgreCEGUIRenderer(Ogre::RenderWindow* window, Ogre::uint8 queue_id, bool post_queue, uint max_quads, Ogre::SceneManager* scene_manager);
+
+
+    /*!
+    \brief
+        Destructor for Ogre renderer.
+    */
+    virtual ~OgreCEGUIRenderer(void);
+
+
+
+    // add's a quad to the list to be rendered
+    virtual	void	addQuad(const Rect& dest_rect, float z, const Texture* tex, const Rect& texture_rect, const ColourRect& colours, QuadSplitMode quad_split_mode);
+
+    // perform final rendering for all queued renderable quads.
+    virtual	void	doRender(void);
+
+    // clear the queue
+    virtual	void	clearRenderList(void);
+
+
+    /*!
+    \brief
+        Enable or disable the queueing of quads from this point on.
+
+        This only affects queueing.  If queueing is turned off, any calls to addQuad will cause the quad to be rendered directly.  Note that
+        disabling queueing will not cause currently queued quads to be rendered, nor is the queue cleared - at any time the queue can still
+        be drawn by calling doRender, and the list can be cleared by calling clearRenderList.  Re-enabling the queue causes subsequent quads
+        to be added as if queueing had never been disabled.
+
+    \param setting
+        true to enable queueing, or false to disable queueing (see notes above).
+
+    \return
+        Nothing
+    */
+    virtual void	setQueueingEnabled(bool setting)		{d_queueing = setting;}
+
+
+    // create an empty texture
+    virtual	Texture*	createTexture(void);
+
+    // create a texture and load it with the specified file.
+    virtual	Texture*	createTexture(const String& filename, const String& resourceGroup = "General");
+
+    // create a texture and set it to the specified size
+    virtual	Texture*	createTexture(float size);
+
+    // create an OGRE resource provider.
+    virtual ResourceProvider* createResourceProvider(void);
+
+    // destroy the given texture
+    virtual	void		destroyTexture(Texture* texture);
+
+    // destroy all textures still active
+    virtual void		destroyAllTextures(void);
+
+
+    /*!
+    \brief
+        Return whether queueing is enabled.
+
+    \return
+        true if queueing is enabled, false if queueing is disabled.
+    */
+    virtual bool	isQueueingEnabled(void) const	{return d_queueing;}
+
+
+    /*!
+    \brief
+    Return the current width of the display in pixels
+
+    \return
+    float value equal to the current width of the display in pixels.
+    */
+    virtual float	getWidth(void) const		{return d_display_area.getWidth();}
+
+
+    /*!
+    \brief
+    Return the current height of the display in pixels
+
+    \return
+    float value equal to the current height of the display in pixels.
+    */
+    virtual float	getHeight(void) const		{return d_display_area.getHeight();}
+
+
+    /*!
+    \brief
+    Return the size of the display in pixels
+
+    \return
+    Size object describing the dimensions of the current display.
+    */
+    virtual Size	getSize(void) const			{return d_display_area.getSize();}
+
+
+    /*!
+    \brief
+    Return a Rect describing the screen
+
+    \return
+    A Rect object that describes the screen area.  Typically, the top-left values are always 0, and the size of the area described is
+    equal to the screen resolution.
+    */
+    virtual Rect	getRect(void) const			{return d_display_area;}
+
+
+    /*!
+    \brief
+        Return the maximum texture size available
+
+    \return
+        Size of the maximum supported texture in pixels (textures are always assumed to be square)
+    */
+    virtual	uint	getMaxTextureSize(void) const		{return 2048;}		// TODO: Change to proper value
+
+
+    /*!
+    \brief
+        Return the horizontal display resolution dpi
+
+    \return
+        horizontal resolution of the display in dpi.
+    */
+    virtual	uint	getHorzScreenDPI(void) const	{return 96;}
+
+
+    /*!
+    \brief
+        Return the vertical display resolution dpi
+
+    \return
+        vertical resolution of the display in dpi.
+    */
+    virtual	uint	getVertScreenDPI(void) const	{return 96;}
+
+
+    /*!
+    \brief
+        Set the scene manager to be used for rendering the GUI.
+
+        The GUI system will be unhooked from the current scene manager and attached to what ever
+        is specified here.
+
+    \param scene_manager
+        Pointer to an Ogre::SceneManager object that is the new target Ogre::SceneManager to be
+        used for GUI rendering.
+
+    \return
+        Nothing.
+    */
+    void	setTargetSceneManager(Ogre::SceneManager* scene_manager);
+
+
+    /*!
+    \brief
+        Set the target render queue for GUI rendering.
+
+    \param queue_id
+        Ogre::uint8 value specifying the render queue that the GUI system should attach to.
+
+    \param post_queue
+        - true to specify that the GUI should render after everything else in render queue \a queue_id.
+        - false to specify the GUI should render before everything else in render queue \a queue_id.
+
+    \return
+        Nothing.
+    */
+    void	setTargetRenderQueue(Ogre::uint8 queue_id, bool post_queue);
+
+
+    /*!
+    \brief
+        Create a texture from an existing Ogre::TexturePtr object.
+
+    \note
+        If you want to use an Ogre::RenderTexture (for putting rendered output onto Gui elements or other
+        advanced techniques), you can get the Ogre::TexturePtr to be used by calling Ogre::TextureManager::getByName()
+        passing the name returned from Ogre::RenderTexture::getName() (and casting the result as necessary).
+
+    \param texture
+        pointer to an Ogre::TexturePtr object to be used as the basis for the new CEGUI::Texture
+
+    \return
+        Pointer to the newly created CEGUI::TexturePtr object.
+    */
+    Texture*	createTexture(Ogre::TexturePtr& texture);
+
+
+    /*!
+    \brief
+    Set the size of the display in pixels.
+
+    You do not have to call this method under normal operation as the system
+    will automatically extract the size from the current view port.
+
+    \note
+    This method will cause the EventDisplaySizeChanged event to fire if the
+    display size has changed.
+
+    \param sz
+    Size object describing the size of the display.
+
+    \return
+    Nothing.
+    */
+    void	setDisplaySize(const Size& sz);
+
+
+private:
+    /************************************************************************
+        Implementation Constants
+    ************************************************************************/
+    static const size_t    VERTEX_PER_QUAD;						 //!< number of vertices per quad
+    static const size_t    VERTEX_PER_TRIANGLE;					 //!< number of vertices for a triangle
+    static const size_t    VERTEXBUFFER_INITIAL_CAPACITY;		 //!< initial capacity of the allocated vertex buffer
+    static const size_t    UNDERUSED_FRAME_THRESHOLD;            //!< number of frames to wait before shrinking buffer
+
+    /*************************************************************************
+        Implementation Structs & classes
+    *************************************************************************/
+    /*!
+    \brief
+        structure used for all vertices.
+    */
+    struct QuadVertex {
+        float x, y, z;			//!< The position for the vertex.
+        Ogre::RGBA diffuse;		//!< colour of the vertex
+        float tu1, tv1;			//!< texture coordinates
+    };
+
+    /*!
+    \brief
+        structure holding details about a quad to be drawn
+    */
+    struct QuadInfo
+    {
+        Ogre::TexturePtr		texture;
+        Rect				position;
+        float				z;
+        Rect				texPosition;
+        uint32		        topLeftCol;
+        uint32		        topRightCol;
+        uint32		        bottomLeftCol;
+        uint32		        bottomRightCol;
+
+        QuadSplitMode		splitMode;
+
+        bool operator<(const QuadInfo& other) const
+        {
+            // this is intentionally reversed.
+            return z > other.z;
+        }
+    };
+
+
+    /*************************************************************************
+        Implementation Methods
+    *************************************************************************/
+    // setup states etc
+    void	initRenderStates(void);
+
+    // sort quads list according to texture
+    void	sortQuads(void);
+
+    // render a quad directly to the display
+    void	renderQuadDirect(const Rect& dest_rect, float z, const Texture* tex, const Rect& texture_rect, const ColourRect& colours, QuadSplitMode quad_split_mode);
+
+    // convert colour value to whatever the Ogre render system is expecting.
+    uint32    colourToOgre(const colour& col) const;
+
+    // perform main work of the constructor.  This does everything except the final hook into the render system.
+    void	constructor_impl(Ogre::RenderWindow* window, Ogre::uint8 queue_id, bool post_queue, uint max_quads);
+
+
+    /*************************************************************************
+        Implementation Data
+    *************************************************************************/
+    Rect				d_display_area;
+
+    typedef std::multiset<QuadInfo>		QuadList;
+    QuadList d_quadlist;
+    bool	 d_queueing;		//!< setting for queueing control.
+
+    // Ogre specific bits.
+    Ogre::Root*					d_ogre_root;		//!< pointer to the Ogre root object that we attach to
+    Ogre::RenderSystem*			d_render_sys;		//!< Pointer to the render system for Ogre.
+    Ogre::uint8	d_queue_id;			//!< ID of the queue that we are hooked into
+    Ogre::TexturePtr			d_currTexture;		//!< currently set texture;
+    Ogre::RenderOperation		d_render_op;		//!< Ogre render operation we use to do our stuff.
+    Ogre::HardwareVertexBufferSharedPtr	d_buffer;	//!< vertex buffer to queue sprite rendering
+    size_t d_underused_framecount;                  //!< Number of frames elapsed since buffer utilization was above half the capacity
+    Ogre::RenderOperation		d_direct_render_op;		//!< Renderop for cursor
+    Ogre::HardwareVertexBufferSharedPtr	d_direct_buffer;	//!< Renderop for cursor
+    Ogre::SceneManager*			d_sceneMngr;		//!< The scene manager we are hooked into.
+    Ogre::LayerBlendModeEx		d_colourBlendMode;	//!< Controls colour blending mode used.
+    Ogre::LayerBlendModeEx		d_alphaBlendMode;	//!< Controls alpha blending mode used.
+    Ogre::TextureUnitState::UVWAddressingMode d_uvwAddressMode;
+
+    CEGUIRQListener*			d_ourlistener;
+    bool						d_post_queue;		//!< true if we render after everything else in our queue.
+    size_t						d_bufferPos;		//!< index into buffer where next vertex should be put.
+    bool						d_sorted;			//!< true when data in quad list is sorted.
+    Point						d_texelOffset;		//!< Offset required for proper texel mapping.
+
+    std::list<OgreCEGUITexture*> d_texturelist;		//!< List used to track textures.
+};
+
+} // End of  CEGUI namespace section
+
+
+#endif	// end of guard _OgreCEGUIRenderer_h_
Index: code/branches/gui/src/orxonox/gui/OgreCEGUIResourceProvider.cpp
===================================================================
--- code/branches/gui/src/orxonox/gui/OgreCEGUIResourceProvider.cpp	(revision 1638)
+++ code/branches/gui/src/orxonox/gui/OgreCEGUIResourceProvider.cpp	(revision 1638)
@@ -0,0 +1,97 @@
+/************************************************************************
+    filename: 	OgreCEGUIResourceProvider.cpp
+    created:	8/7/2004
+    author:		James '_mental_' O'Sullivan
+
+    purpose:	Implements the Resource Provider common functionality
+*************************************************************************/
+/*************************************************************************
+    Crazy Eddie's GUI System (http://www.cegui.org.uk)
+    Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+*************************************************************************/
+#include "OgreCEGUIResourceProvider.h"
+
+#include <CEGUIExceptions.h>
+#include <OgreArchiveManager.h>
+
+
+// Start of CEGUI namespace section
+namespace CEGUI
+{
+    OgreCEGUIResourceProvider::OgreCEGUIResourceProvider() : ResourceProvider()
+    {
+        // set deafult resource group for Ogre
+        d_defaultResourceGroup = Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME.c_str();
+    }
+
+//    void OgreResourceProvider::loadInputSourceContainer(const String& filename, InputSourceContainer& output)
+//   {
+//        Ogre::DataStreamPtr input = Ogre::ResourceGroupManager::getSingleton().openResource(filename.c_str());
+//
+//		if (input.isNull())
+//		{
+//			throw InvalidRequestException((utf8*)
+//				"Scheme::Scheme - Filename supplied for Scheme loading must be valid");
+//		}
+//
+//       XERCES_CPP_NAMESPACE_USE
+//        size_t buffsz = input->size();
+//        unsigned char* mem = reinterpret_cast<unsigned char*>(XMLPlatformUtils::fgArrayMemoryManager->allocate(buffsz));
+//        memcpy(mem, input.getPointer()->getAsString().c_str(), buffsz);
+//        InputSource* mInputSource = new MemBufInputSource(mem, buffsz, filename.c_str(), true);
+//        input.setNull();
+//
+//       output.setData(mInputSource);
+//    }
+
+    void OgreCEGUIResourceProvider::loadRawDataContainer(const String& filename, RawDataContainer& output,  const String& resourceGroup)
+    {
+        String orpGroup;
+        if (resourceGroup.empty())
+            orpGroup = d_defaultResourceGroup.empty() ? Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME.c_str() : d_defaultResourceGroup;
+        else
+            orpGroup = resourceGroup;
+
+        Ogre::DataStreamPtr input =
+            Ogre::ResourceGroupManager::getSingleton().openResource(filename.c_str(), orpGroup.c_str());
+
+        if (input.isNull())
+        {
+            throw InvalidRequestException((utf8*)
+                "OgreCEGUIResourceProvider::loadRawDataContainer - Unable to open resource file '" + filename + (utf8*)"' in resource group '" + orpGroup + (utf8*)"'.");
+        }
+
+        Ogre::String buf = input->getAsString();
+        const size_t memBuffSize = buf.length();
+
+        unsigned char* mem = new unsigned char[memBuffSize];
+        memcpy(mem, buf.c_str(), memBuffSize);
+
+        output.setData(mem);
+        output.setSize(memBuffSize);
+    }
+
+    void OgreCEGUIResourceProvider::unloadRawDataContainer(RawDataContainer& data)
+    {
+        if (data.getDataPtr())
+        {
+            delete[] data.getDataPtr();
+            data.setData(0);
+            data.setSize(0);
+        }
+    }
+} // End of  CEGUI namespace section
Index: code/branches/gui/src/orxonox/gui/OgreCEGUIResourceProvider.h
===================================================================
--- code/branches/gui/src/orxonox/gui/OgreCEGUIResourceProvider.h	(revision 1638)
+++ code/branches/gui/src/orxonox/gui/OgreCEGUIResourceProvider.h	(revision 1638)
@@ -0,0 +1,52 @@
+/************************************************************************
+    filename: 	CEGUIOgreResourceProvider.h
+    created:	8/7/2004
+    author:		James '_mental_' O'Sullivan
+    
+    purpose:	Defines abstract base class for CEGUIData objects
+*************************************************************************/
+/*************************************************************************
+    Crazy Eddie's GUI System (http://www.cegui.org.uk)
+    Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+*************************************************************************/
+#ifndef _OgreCEGUIResourceProvider_h_
+#define _OgreCEGUIResourceProvider_h_
+
+#include <CEGUIResourceProvider.h>
+#include "OgreCEGUIRenderer.h"
+
+// Start of CEGUI namespace section
+namespace CEGUI
+{
+class _OgrePrivate OgreCEGUIResourceProvider : public ResourceProvider
+{
+public:
+    /*************************************************************************
+        Construction and Destruction
+    *************************************************************************/
+    OgreCEGUIResourceProvider();
+
+    ~OgreCEGUIResourceProvider(void) {}
+
+//    void loadInputSourceContainer(const String& filename, InputSourceContainer& output);
+    void loadRawDataContainer(const String& filename, RawDataContainer& output, const String& resourceGroup);
+    void unloadRawDataContainer(RawDataContainer& output);
+};
+
+} // End of  CEGUI namespace section
+
+#endif	// end of guard _OgreCEGUIResourceProvider_h_
Index: code/branches/gui/src/orxonox/gui/OgreCEGUITexture.cpp
===================================================================
--- code/branches/gui/src/orxonox/gui/OgreCEGUITexture.cpp	(revision 1638)
+++ code/branches/gui/src/orxonox/gui/OgreCEGUITexture.cpp	(revision 1638)
@@ -0,0 +1,268 @@
+/************************************************************************
+    filename: 	OgreCEGUITexture.cpp
+    created:	11/5/2004
+    author:		Paul D Turner
+    
+    purpose:	Implementation of Texture using Ogre engine
+*************************************************************************/
+/*************************************************************************
+    Crazy Eddie's GUI System (http://www.cegui.org.uk)
+    Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+*************************************************************************/
+
+#include <CEGUISystem.h>
+#include <CEGUIExceptions.h>
+#include "OgreCEGUITexture.h"
+#include "OgreCEGUIRenderer.h"
+
+#include <OgreTextureManager.h>
+
+// Start of CEGUI namespace section
+namespace CEGUI
+{
+/*************************************************************************
+    Static data definition / initialisation
+*************************************************************************/
+uint32 OgreCEGUITexture::d_texturenumber		= 0;
+
+
+/*************************************************************************
+    Constructor
+*************************************************************************/
+OgreCEGUITexture::OgreCEGUITexture(Renderer* owner) :
+    Texture(owner)
+{
+    d_ogre_texture.setNull();
+    d_isLinked = false;
+}
+
+
+/*************************************************************************
+    Destructor
+*************************************************************************/
+OgreCEGUITexture::~OgreCEGUITexture(void)
+{
+    freeOgreTexture();
+}
+
+
+/*************************************************************************
+    Loads the specified image file into the texture.  The texture is
+    resized as required to hold the image.	
+*************************************************************************/
+void OgreCEGUITexture::loadFromFile(const String& filename, const String& resourceGroup)
+{
+    using namespace Ogre;
+
+    // unload old ogre texture
+    freeOgreTexture();
+
+    // create / load a new ogre texture from the specified image
+    try
+    {
+        TextureManager& textureManager = TextureManager::getSingleton();
+
+        // see if texture already exists
+        Ogre::TexturePtr ogreTexture = (Ogre::TexturePtr)textureManager.getByName(filename.c_str());
+
+        if (!ogreTexture.isNull())
+        {
+            // texture already exists, so create a 'linked' texture (ensures texture is not destroyed twice)
+            d_ogre_texture = ogreTexture;
+            d_isLinked = true;
+        }
+        // texture does not already exist, so load it in
+        else
+        {
+            String orpGroup;
+            if (resourceGroup.empty())
+            {
+                const String& defGrp = CEGUI::System::getSingleton().getResourceProvider()->getDefaultResourceGroup();
+                orpGroup = defGrp.empty() ? Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME.c_str() : defGrp;
+            }
+            else
+            {
+                orpGroup = resourceGroup;
+            }
+
+            d_ogre_texture = TextureManager::getSingleton().load(filename.c_str(), orpGroup.c_str(), TEX_TYPE_2D, 0, 1.0f);
+            d_isLinked = false;
+        }
+
+    }
+    catch(Ogre::Exception e)
+    {
+        throw RendererException((utf8*)"Failed to create Texture object from file '" + filename + "'. Additional Information:\n" + e.getFullDescription().c_str());
+    }
+
+    // if we got a pointer cache some details
+    if (!d_ogre_texture.isNull())
+    {
+        d_width		= d_ogre_texture->getWidth();
+        d_height	= d_ogre_texture->getHeight();
+    }
+    // no texture from image so throw.
+    else
+    {
+        throw RendererException((utf8*)"Failed to create Texture object from file '" + filename + "'.  Ogre returned a NULL pointer.");
+    }
+
+}
+
+
+/*************************************************************************
+    Loads (copies) an image in memory into the texture.  The texture is
+    resized as required to hold the image.	
+*************************************************************************/
+
+void _byteSwap(unsigned char* b, int n)
+{
+    register int i = 0;
+    register int j = n-1;
+    while (i<j)
+    {
+        std::swap(b[i], b[j]);
+        i++, j--;
+    }
+}
+#define byteSwap(x) _byteSwap((unsigned char*) &x,sizeof(x))
+
+void OgreCEGUITexture::loadFromMemory(const void* buffPtr, uint buffWidth, uint buffHeight, PixelFormat pixelFormat)
+{
+    using namespace Ogre;
+
+    // get rid of old texture
+    freeOgreTexture();
+
+    // wrap input buffer with an Ogre DataChunk
+    uint32 bytesize = ((buffWidth * sizeof(uint32)) * buffHeight);
+
+#if OGRE_ENDIAN == OGRE_ENDIAN_BIG
+    uint32* swappedBuffer = new uint32[bytesize/4];
+    memcpy(swappedBuffer, buffPtr, bytesize);
+
+    for (int i=0; i < bytesize/4; i++)
+        byteSwap(swappedBuffer[i]);
+
+    DataStreamPtr odc(new MemoryDataStream(static_cast<void*>(swappedBuffer), bytesize, false));
+#else
+    DataStreamPtr odc(new MemoryDataStream(const_cast<void*>(buffPtr), bytesize, false));
+#endif
+
+    // get pixel type for the target texture - the elements here might look wrong, but is just
+    // differences in definition (at the core level, between GL and D3D).
+    Ogre::PixelFormat targetFmt =
+        (pixelFormat == PF_RGBA) ? Ogre::PF_A8R8G8B8 : Ogre::PF_R8G8B8;
+
+    // try to create a Ogre::Texture from the input data
+    d_ogre_texture = TextureManager::getSingleton().loadRawData(getUniqueName(), "General", odc, buffWidth, buffHeight, targetFmt , TEX_TYPE_2D, 0, 1.0f);
+
+    // if we got a pointer cache some details
+    if (!d_ogre_texture.isNull())
+    {
+        d_width		= d_ogre_texture->getWidth();
+        d_height	= d_ogre_texture->getHeight();
+    }
+    // no texture from memory so throw.
+    else
+    {
+        throw RendererException((utf8*)"Failed to create Texture object from memory:  Ogre returned a NULL Ogre::Texture pointer.");
+    }
+
+}
+
+
+/*************************************************************************
+    set the size of the internal Ogre texture.  Previous Ogre texture
+    is lost.	
+*************************************************************************/
+void OgreCEGUITexture::setOgreTextureSize(uint size)
+{
+    using namespace Ogre;
+
+    // unload any current Ogre::Texture
+    freeOgreTexture();
+
+    // Try to create an empty texture of the given size
+    d_ogre_texture = TextureManager::getSingleton().createManual(getUniqueName(), "General", TEX_TYPE_2D, size, size, 0, PF_A8R8G8B8, TU_DEFAULT);
+
+    // if we got a pointer cache some details
+    if (!d_ogre_texture.isNull())
+    {
+        d_width		= d_ogre_texture->getWidth();
+        d_height	= d_ogre_texture->getHeight();
+    }
+    // no texture so throw.
+    else
+    {
+        throw RendererException((utf8*)"Failed to create texture of specified size: Ogre::Texture creation failed.");
+    }
+
+}
+
+
+/*************************************************************************
+    safely free Ogre::Texture texture (can be called multiple times with
+    no ill effect)
+*************************************************************************/
+void OgreCEGUITexture::freeOgreTexture(void)
+{
+    if ((!d_ogre_texture.isNull()) && !d_isLinked)
+    {
+        Ogre::TextureManager::getSingleton().remove(d_ogre_texture->getHandle());
+    }
+    d_ogre_texture.setNull();
+}
+
+
+/*************************************************************************
+    return a Ogre::string that contains a unique name.	
+*************************************************************************/
+Ogre::String OgreCEGUITexture::getUniqueName(void)
+{
+    Ogre::String str;
+
+#ifdef CEGUI_USEOLDOGRESTRING
+    str << "_cegui_ogre_" << d_texturenumber;
+#else
+    Ogre::StringUtil::StrStreamType strstream;
+    strstream << "_cegui_ogre_" << d_texturenumber;
+    str = strstream.str();
+#endif
+
+    ++d_texturenumber;
+
+    return str;
+}
+
+
+/*************************************************************************
+    Set the internal Ogre::Texture object.
+*************************************************************************/
+void OgreCEGUITexture::setOgreTexture(Ogre::TexturePtr& texture)
+{
+    freeOgreTexture();
+
+    d_ogre_texture = texture;
+    d_width	 = d_ogre_texture->getWidth();
+    d_height = d_ogre_texture->getHeight();
+    d_isLinked = true;
+}
+
+
+} // End of  CEGUI namespace section
+
Index: code/branches/gui/src/orxonox/gui/OgreCEGUITexture.h
===================================================================
--- code/branches/gui/src/orxonox/gui/OgreCEGUITexture.h	(revision 1638)
+++ code/branches/gui/src/orxonox/gui/OgreCEGUITexture.h	(revision 1638)
@@ -0,0 +1,179 @@
+/************************************************************************
+    filename: 	OgreCEGUITexture.h
+    created:	11/5/2004
+    author:		Paul D Turner
+    
+    purpose:	Interface to Texture implemented via Ogre engine
+*************************************************************************/
+/*************************************************************************
+    Crazy Eddie's GUI System (http://www.cegui.org.uk)
+    Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)
+
+    This library is free software; you can redistribute it and/or
+    modify it under the terms of the GNU Lesser General Public
+    License as published by the Free Software Foundation; either
+    version 2.1 of the License, or (at your option) any later version.
+
+    This library is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+    Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public
+    License along with this library; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+*************************************************************************/
+#ifndef _OgreCEGUITexture_h_
+#define _OgreCEGUITexture_h_
+
+#include <CEGUIBase.h>
+#include <CEGUIRenderer.h>
+#include <CEGUITexture.h>
+#include "OgreCEGUIRenderer.h"
+
+// Start of CEGUI namespace section
+namespace CEGUI
+{
+/*!
+\brief
+    Texture class that is created by OgreCEGUIRenderer objects
+*/
+class _OgrePrivate OgreCEGUITexture : public Texture
+{
+private:
+    /*************************************************************************
+        Friends (to allow construction and destruction)
+    *************************************************************************/
+    friend	Texture* OgreCEGUIRenderer::createTexture(void);
+    friend	Texture* OgreCEGUIRenderer::createTexture(const String& filename, const String& resourceGroup);
+    friend	Texture* OgreCEGUIRenderer::createTexture(float size);
+    friend	void	 OgreCEGUIRenderer::destroyTexture(Texture* texture);
+
+
+    /*************************************************************************
+        Construction & Destruction (by Renderer object only)
+    *************************************************************************/
+    OgreCEGUITexture(Renderer* owner);
+    virtual ~OgreCEGUITexture(void);
+
+public:
+    /*!
+    \brief
+        Returns the current pixel width of the texture
+
+    \return
+        ushort value that is the current width of the texture in pixels
+    */
+    virtual	ushort	getWidth(void) const		{return d_width;}
+
+
+    /*!
+    \brief
+        Returns the current pixel height of the texture
+
+    \return
+        ushort value that is the current height of the texture in pixels
+    */
+    virtual	ushort	getHeight(void) const		{return d_height;}
+
+
+    /*!
+    \brief
+        Loads the specified image file into the texture.  The texture is resized as required to hold the image.
+
+    \param filename
+        The filename of the image file that is to be loaded into the texture
+
+    \return
+        Nothing.
+    */
+    virtual void	loadFromFile(const String& filename, const String& resourceGroup);
+
+
+    /*!
+    \brief
+        Loads (copies) an image in memory into the texture.  The texture is resized as required to hold the image.
+    
+    \param buffPtr
+        Pointer to the buffer containing the image data
+    
+    \param buffWidth
+        Width of the buffer (in pixels as specified by \a pixelFormat )
+    
+    \param buffHeight
+        Height of the buffer (in pixels as specified by \a pixelFormat )
+    
+    \param pixelFormat
+    PixelFormat value describing the format contained in \a buffPtr
+    
+    \return
+        Nothing.
+    */
+    virtual void	loadFromMemory(const void* buffPtr, uint buffWidth, uint buffHeight, PixelFormat pixelFormat);
+
+
+    /*!
+    \brief
+        Return a pointer to the internal Ogre::Texture object
+
+    \return
+        Pointer to the Ogre::Texture object currently being used by this Texture object
+    */
+    Ogre::TexturePtr	getOgreTexture(void) const		{return d_ogre_texture;}
+
+
+    /*!
+    \brief
+        set the size of the internal Ogre texture.  Previous Ogre texture is lost.
+
+    \param size
+        pixel size of the new internal texture.  This will be rounded up to a power of 2.
+
+    \return
+        Nothing.
+    */
+    void	setOgreTextureSize(uint size);
+
+
+    /*!
+    \brief
+        Set the internal Ogre::TexturePtr object.
+
+    \param texture
+        Reference to an Ogre::TexturePtr object that is to be used by this Texture object.
+
+    \return
+        Nothing.
+    */
+    void	setOgreTexture(Ogre::TexturePtr& texture);
+
+
+private:
+    /*************************************************************************
+        Implementation Functions
+    *************************************************************************/
+    // safely free Ogre::Texture texture (can be called multiple times with no ill effect)
+    void	freeOgreTexture(void);
+
+    // return a Ogre::string that contains a unique name.
+    Ogre::String	getUniqueName(void);
+
+
+    /*************************************************************************
+        Implementation Data
+    *************************************************************************/
+    static	uint32          d_texturenumber;	//!< Counter used to provide unique texture names.
+
+    Ogre::TexturePtr		d_ogre_texture;		//!< The 'real' texture.
+
+    ushort					d_width;			//!< cached width of the texture
+    ushort					d_height;			//!< cached height of the texture
+
+    bool	d_isLinked;		//!< True if we are linked to a texture we did not actually create.
+};
+
+
+} // End of  CEGUI namespace section
+
+
+#endif	// end of guard _OgreCEGUITexture_h_
Index: code/branches/gui/src/orxonox/objects/Ambient.cc
===================================================================
--- code/branches/gui/src/orxonox/objects/Ambient.cc	(revision 1636)
+++ code/branches/gui/src/orxonox/objects/Ambient.cc	(revision 1638)
@@ -65,5 +65,5 @@
 
     bool Ambient::create(){
-      GraphicsEngine::getSingleton().getSceneManager()->setAmbientLight(ambientLight_);
+      GraphicsEngine::getSingleton().getLevelSceneManager()->setAmbientLight(ambientLight_);
       return Synchronisable::create();
     }
@@ -76,5 +76,5 @@
     void Ambient::setAmbientLight(const ColourValue& colour)
     {
-	    GraphicsEngine::getSingleton().getSceneManager()->setAmbientLight(colour);
+        GraphicsEngine::getSingleton().getLevelSceneManager()->setAmbientLight(colour);
       ambientLight_=colour;	
     }
Index: code/branches/gui/src/orxonox/objects/Backlight.cc
===================================================================
--- code/branches/gui/src/orxonox/objects/Backlight.cc	(revision 1636)
+++ code/branches/gui/src/orxonox/objects/Backlight.cc	(revision 1638)
@@ -58,6 +58,6 @@
         this->attachObject(this->billboard_.getBillboardSet());
 
-        this->ribbonTrail_ = GraphicsEngine::getSingleton().getSceneManager()->createRibbonTrail(this->getName() + "RibbonTrail");
-        this->ribbonTrailNode_ = GraphicsEngine::getSingleton().getSceneManager()->getRootSceneNode()->createChildSceneNode(this->getName() + "RibbonTrailNode");
+        this->ribbonTrail_ = GraphicsEngine::getSingleton().getLevelSceneManager()->createRibbonTrail(this->getName() + "RibbonTrail");
+        this->ribbonTrailNode_ = GraphicsEngine::getSingleton().getLevelSceneManager()->getRootSceneNode()->createChildSceneNode(this->getName() + "RibbonTrailNode");
         this->ribbonTrailNode_->attachObject(this->ribbonTrail_);
         this->ribbonTrail_->addNode(this->getNode());
@@ -68,5 +68,5 @@
         this->ribbonTrail_->setMaterialName("Trail/backlighttrail");
 
-        this->setTimeFactor(Orxonox::getSingleton()->getTimeFactor());
+        this->setTimeFactor(Orxonox::getSingleton().getTimeFactor());
     }
 
@@ -76,6 +76,6 @@
         {
             this->detachObject(this->billboard_.getBillboardSet());
-            GraphicsEngine::getSingleton().getSceneManager()->destroySceneNode(this->getName() + "RibbonTrailNode");
-            GraphicsEngine::getSingleton().getSceneManager()->destroyRibbonTrail(this->ribbonTrail_);
+            GraphicsEngine::getSingleton().getLevelSceneManager()->destroySceneNode(this->getName() + "RibbonTrailNode");
+            GraphicsEngine::getSingleton().getLevelSceneManager()->destroyRibbonTrail(this->ribbonTrail_);
         }
     }
Index: code/branches/gui/src/orxonox/objects/Camera.cc
===================================================================
--- code/branches/gui/src/orxonox/objects/Camera.cc	(revision 1636)
+++ code/branches/gui/src/orxonox/objects/Camera.cc	(revision 1638)
@@ -52,5 +52,5 @@
   {
     this->bHasFocus_ = false;
-    this->cameraNode_ = GraphicsEngine::getSingleton().getSceneManager()->getRootSceneNode()->createChildSceneNode(node->getName() + "Camera");
+    this->cameraNode_ = GraphicsEngine::getSingleton().getLevelSceneManager()->getRootSceneNode()->createChildSceneNode(node->getName() + "Camera");
     if( node != NULL )
       this->setPositionNode(node);
@@ -60,5 +60,5 @@
   {
     CameraHandler::getInstance()->releaseFocus(this);
-    GraphicsEngine::getSingleton().getSceneManager()->getRootSceneNode()->removeAndDestroyChild(cameraNode_->getName());
+    GraphicsEngine::getSingleton().getLevelSceneManager()->getRootSceneNode()->removeAndDestroyChild(cameraNode_->getName());
   }
 
Index: code/branches/gui/src/orxonox/objects/CameraHandler.cc
===================================================================
--- code/branches/gui/src/orxonox/objects/CameraHandler.cc	(revision 1636)
+++ code/branches/gui/src/orxonox/objects/CameraHandler.cc	(revision 1638)
@@ -44,6 +44,7 @@
   CameraHandler::CameraHandler()
   {
-    this->cam_ = GraphicsEngine::getSingleton().getSceneManager()->createCamera("Cam");
-    GraphicsEngine::getSingleton().getRenderWindow()->addViewport(this->cam_);
+    this->cam_ = GraphicsEngine::getSingleton().getLevelSceneManager()->createCamera("Cam");
+    GraphicsEngine::getSingleton().getLevelViewport()->setCamera(this->cam_);
+    GraphicsEngine::getSingleton().getRenderWindow()->addViewport(this->cam_, 2, 0.4, 0.4, 0.2, 0.2);
     /*this->activeCamera_ = *ObjectList<Camera>::begin();
     this->activeCamera_->cam_ = this->cam_;*/
Index: code/branches/gui/src/orxonox/objects/ParticleSpawner.cc
===================================================================
--- code/branches/gui/src/orxonox/objects/ParticleSpawner.cc	(revision 1636)
+++ code/branches/gui/src/orxonox/objects/ParticleSpawner.cc	(revision 1638)
@@ -79,5 +79,5 @@
         this->setPosition(this->getNode()->getParent()->getPosition());
         this->getNode()->getParent()->removeChild(this->getNode());
-        GraphicsEngine::getSingleton().getSceneManager()->getRootSceneNode()->addChild(this->getNode());
+        GraphicsEngine::getSingleton().getLevelSceneManager()->getRootSceneNode()->addChild(this->getNode());
         if (this->particle_)
             this->particle_->setEnabled(false);
Index: code/branches/gui/src/orxonox/objects/Projectile.cc
===================================================================
--- code/branches/gui/src/orxonox/objects/Projectile.cc	(revision 1636)
+++ code/branches/gui/src/orxonox/objects/Projectile.cc	(revision 1638)
@@ -75,5 +75,5 @@
         SetConfigValue(speed_, 5000.0).description("The speed of a projectile in units per second");
 
-	if(this->owner_)
+    if(this->owner_)
           this->setVelocity(this->owner_->getInitialDir() * this->speed_);
     }
Index: code/branches/gui/src/orxonox/objects/Skybox.cc
===================================================================
--- code/branches/gui/src/orxonox/objects/Skybox.cc	(revision 1636)
+++ code/branches/gui/src/orxonox/objects/Skybox.cc	(revision 1638)
@@ -56,5 +56,5 @@
     void Skybox::setSkybox(const std::string& skyboxname)
     {
-    	GraphicsEngine::getSingleton().getSceneManager()->setSkyBox(true, skyboxname);
+        GraphicsEngine::getSingleton().getLevelSceneManager()->setSkyBox(true, skyboxname);
     }
 
@@ -92,5 +92,5 @@
     {
         BaseObject::changedVisibility();
-        GraphicsEngine::getSingleton().getSceneManager()->setSkyBox(this->isVisible(), this->skyboxSrc_);
+        GraphicsEngine::getSingleton().getLevelSceneManager()->setSkyBox(this->isVisible(), this->skyboxSrc_);
     }
 }
Index: code/branches/gui/src/orxonox/objects/Tickable.h
===================================================================
--- code/branches/gui/src/orxonox/objects/Tickable.h	(revision 1636)
+++ code/branches/gui/src/orxonox/objects/Tickable.h	(revision 1638)
@@ -29,5 +29,5 @@
 /*!
     @file Tickable.h
-    @brief Definition of the Tickable interface.
+    @brief Declaration of the Tickable interface.
 
     The Tickable interface provides a tick(dt) function, that gets called every frame.
Index: code/branches/gui/src/orxonox/objects/WorldEntity.cc
===================================================================
--- code/branches/gui/src/orxonox/objects/WorldEntity.cc	(revision 1636)
+++ code/branches/gui/src/orxonox/objects/WorldEntity.cc	(revision 1638)
@@ -49,10 +49,10 @@
         RegisterObject(WorldEntity);
 
-        if (GraphicsEngine::getSingleton().getSceneManager())
+        if (GraphicsEngine::getSingleton().getLevelSceneManager())
         {
             std::ostringstream name;
             name << (WorldEntity::worldEntityCounter_s++);
             this->setName("WorldEntity" + name.str());
-            this->node_ = GraphicsEngine::getSingleton().getSceneManager()->getRootSceneNode()->createChildSceneNode(this->getName());
+            this->node_ = GraphicsEngine::getSingleton().getLevelSceneManager()->getRootSceneNode()->createChildSceneNode(this->getName());
 
             registerAllVariables();
@@ -77,5 +77,5 @@
         {
             this->getNode()->removeAndDestroyAllChildren();
-            GraphicsEngine::getSingleton().getSceneManager()->destroySceneNode(this->getName());
+            GraphicsEngine::getSingleton().getLevelSceneManager()->destroySceneNode(this->getName());
         }
     }
@@ -178,5 +178,5 @@
     void WorldEntity::attachObject(const WorldEntity& obj) const
     {
-        GraphicsEngine::getSingleton().getSceneManager()->getRootSceneNode()->removeChild(obj.getNode());
+        GraphicsEngine::getSingleton().getLevelSceneManager()->getRootSceneNode()->removeChild(obj.getNode());
         this->getNode()->addChild(obj.getNode());
     }
@@ -184,5 +184,5 @@
     void WorldEntity::attachObject(WorldEntity* obj) const
     {
-        GraphicsEngine::getSingleton().getSceneManager()->getRootSceneNode()->removeChild(obj->getNode());
+        GraphicsEngine::getSingleton().getLevelSceneManager()->getRootSceneNode()->removeChild(obj->getNode());
         this->getNode()->addChild(obj->getNode());
     }
Index: code/branches/gui/src/orxonox/overlays/console/InGameConsole.cc
===================================================================
--- code/branches/gui/src/orxonox/overlays/console/InGameConsole.cc	(revision 1636)
+++ code/branches/gui/src/orxonox/overlays/console/InGameConsole.cc	(revision 1638)
@@ -59,8 +59,14 @@
         @brief Constructor: Creates and initializes the InGameConsole.
     */
-    InGameConsole::InGameConsole() :
-        consoleOverlay_(0), consoleOverlayContainer_(0),
-        consoleOverlayNoise_(0), consoleOverlayCursor_(0), consoleOverlayBorder_(0),
-        consoleOverlayTextAreas_(0)
+    InGameConsole::InGameConsole()
+        : consoleOverlay_(0)
+        , consoleOverlayContainer_(0)
+        , consoleOverlayNoise_(0)
+        , consoleOverlayCursor_(0)
+        , consoleOverlayBorder_(0)
+        , consoleOverlayTextAreas_(0)
+        , emptySceneManager_(0)
+        , emptyCamera_(0)
+        , viewport_(0)
     {
         RegisterObject(InGameConsole);
@@ -188,4 +194,12 @@
 
         Shell::getInstance().addOutputLevel(true);
+
+        // create a sceneManager in order to render in our own viewport
+        this->emptySceneManager_ = Ogre::Root::getSingleton()
+            .createSceneManager(Ogre::ST_GENERIC, "Console/EmptySceneManager");
+        this->emptyCamera_ = this->emptySceneManager_->createCamera("Console/EmptyCamera");
+        this->viewport_ = GraphicsEngine::getSingleton().getRenderWindow()->addViewport(emptyCamera_, 10);
+        this->viewport_->setOverlaysEnabled(true);
+        this->viewport_->setClearEveryFrame(false);
 
         COUT(4) << "Info: InGameConsole initialized" << std::endl;
@@ -476,5 +490,5 @@
         {
             this->bActive_ = true;
-            InputManager::setInputState(InputManager::IS_CONSOLE);
+            InputManager::requestEnterState("console");
             Shell::getInstance().registerListener(this);
 
@@ -498,5 +512,5 @@
         {
             this->bActive_ = false;
-            InputManager::setInputState(InputManager::IS_NORMAL);
+            InputManager::requestLeaveState("console");
             Shell::getInstance().unregisterListener(this);
 
Index: code/branches/gui/src/orxonox/overlays/console/InGameConsole.h
===================================================================
--- code/branches/gui/src/orxonox/overlays/console/InGameConsole.h	(revision 1636)
+++ code/branches/gui/src/orxonox/overlays/console/InGameConsole.h	(revision 1638)
@@ -45,66 +45,70 @@
     class _OrxonoxExport InGameConsole : public TickableReal, public ShellListener, public WindowEventListener
     {
-        public: // functions
-            void initialise();
-            void destroy();
-            void setConfigValues();
+    public: // functions
+        void initialise();
+        void destroy();
+        void setConfigValues();
 
-            void tick(float dt);
+        void tick(float dt);
 
-            static InGameConsole& getInstance();
+        static InGameConsole& getInstance();
 
-            static void openConsole();
-            static void closeConsole();
+        static void openConsole();
+        static void closeConsole();
 
-        private: // functions
-            InGameConsole();
-            InGameConsole(const InGameConsole& other) {}
-            ~InGameConsole();
+    private: // functions
+        InGameConsole();
+        InGameConsole(const InGameConsole& other) {}
+        ~InGameConsole();
 
-            void activate();
-            void deactivate();
+        void activate();
+        void deactivate();
 
-            void linesChanged();
-            void onlyLastLineChanged();
-            void lineAdded();
-            void inputChanged();
-            void cursorChanged();
-            void exit();
+        void linesChanged();
+        void onlyLastLineChanged();
+        void lineAdded();
+        void inputChanged();
+        void cursorChanged();
+        void exit();
 
-            void shiftLines();
-            void colourLine(int colourcode, int index);
-            void setCursorPosition(unsigned int pos);
-            void print(const std::string& text, int index, bool alwaysShift = false);
+        void shiftLines();
+        void colourLine(int colourcode, int index);
+        void setCursorPosition(unsigned int pos);
+        void print(const std::string& text, int index, bool alwaysShift = false);
 
-            void windowResized(int newWidth, int newHeight);
+        void windowResized(int newWidth, int newHeight);
 
-            static Ogre::UTFString convert2UTF(std::string s);
+        static Ogre::UTFString convert2UTF(std::string s);
 
-        private: // variables
-            bool bActive_;
-            int windowW_;
-            int windowH_;
-            int desiredTextWidth_;
-            unsigned int maxCharsPerLine_;
-            unsigned int numLinesShifted_;
-            int scroll_;
-            float cursor_;
-            unsigned int inputWindowStart_;
-            bool bShowCursor_;
-            std::string displayedText_;
-            Ogre::Overlay* consoleOverlay_;
-            Ogre::OverlayContainer* consoleOverlayContainer_;
-            Ogre::PanelOverlayElement* consoleOverlayNoise_;
-            Ogre::TextAreaOverlayElement* consoleOverlayCursor_;
-            Ogre::BorderPanelOverlayElement* consoleOverlayBorder_;
-            Ogre::TextAreaOverlayElement** consoleOverlayTextAreas_;
+    private: // variables
+        bool bActive_;
+        int windowW_;
+        int windowH_;
+        int desiredTextWidth_;
+        unsigned int maxCharsPerLine_;
+        unsigned int numLinesShifted_;
+        int scroll_;
+        float cursor_;
+        unsigned int inputWindowStart_;
+        bool bShowCursor_;
+        std::string displayedText_;
+        Ogre::Overlay* consoleOverlay_;
+        Ogre::OverlayContainer* consoleOverlayContainer_;
+        Ogre::PanelOverlayElement* consoleOverlayNoise_;
+        Ogre::TextAreaOverlayElement* consoleOverlayCursor_;
+        Ogre::BorderPanelOverlayElement* consoleOverlayBorder_;
+        Ogre::TextAreaOverlayElement** consoleOverlayTextAreas_;
 
-            // config values
-            float relativeWidth;
-            float relativeHeight;
-            float blinkTime;
-            float scrollSpeed_;
-            float noiseSize_;
-            char cursorSymbol_;
+        Ogre::SceneManager* emptySceneManager_;     //!< dummy SceneManager to render overlays in empty windows
+        Ogre::Camera*       emptyCamera_;           //!< dummy camera to render overlays in empty windows
+        Ogre::Viewport*     viewport_;
+
+        // config values
+        float relativeWidth;
+        float relativeHeight;
+        float blinkTime;
+        float scrollSpeed_;
+        float noiseSize_;
+        char cursorSymbol_;
     };
 }
Index: code/branches/gui/src/orxonox/overlays/hud/HUDSpeedBar.cc
===================================================================
--- code/branches/gui/src/orxonox/overlays/hud/HUDSpeedBar.cc	(revision 1636)
+++ code/branches/gui/src/orxonox/overlays/hud/HUDSpeedBar.cc	(revision 1638)
@@ -54,5 +54,5 @@
             float v = ship->getVelocity().length();
             float value = v / ship->getMaxSpeed();
-			if (value != this->getValue())
+            if (value != this->getValue())
                 this->setValue(value);
         }
Index: code/branches/gui/src/orxonox/tolua/tolua.pkg
===================================================================
--- code/branches/gui/src/orxonox/tolua/tolua.pkg	(revision 1636)
+++ code/branches/gui/src/orxonox/tolua/tolua.pkg	(revision 1638)
@@ -0,0 +1,1 @@
+$cfile "../../src/orxonox/gui/GUIManager.h"
Index: code/branches/gui/src/orxonox/tools/BillboardSet.cc
===================================================================
--- code/branches/gui/src/orxonox/tools/BillboardSet.cc	(revision 1636)
+++ code/branches/gui/src/orxonox/tools/BillboardSet.cc	(revision 1638)
@@ -50,5 +50,5 @@
         std::ostringstream name;
         name << (BillboardSet::billboardSetCounter_s++);
-        this->billboardSet_ = GraphicsEngine::getSingleton().getSceneManager()->createBillboardSet("Billboard" + name.str(), count);
+        this->billboardSet_ = GraphicsEngine::getSingleton().getLevelSceneManager()->createBillboardSet("Billboard" + name.str(), count);
         this->billboardSet_->createBillboard(Vector3::ZERO);
         this->billboardSet_->setMaterialName(file);
@@ -59,5 +59,5 @@
         std::ostringstream name;
         name << (BillboardSet::billboardSetCounter_s++);
-        this->billboardSet_ = GraphicsEngine::getSingleton().getSceneManager()->createBillboardSet("Billboard" + name.str(), count);
+        this->billboardSet_ = GraphicsEngine::getSingleton().getLevelSceneManager()->createBillboardSet("Billboard" + name.str(), count);
         this->billboardSet_->createBillboard(Vector3::ZERO, colour);
         this->billboardSet_->setMaterialName(file);
@@ -68,5 +68,5 @@
         std::ostringstream name;
         name << (BillboardSet::billboardSetCounter_s++);
-        this->billboardSet_ = GraphicsEngine::getSingleton().getSceneManager()->createBillboardSet("Billboard" + name.str(), count);
+        this->billboardSet_ = GraphicsEngine::getSingleton().getLevelSceneManager()->createBillboardSet("Billboard" + name.str(), count);
         this->billboardSet_->createBillboard(position);
         this->billboardSet_->setMaterialName(file);
@@ -77,5 +77,5 @@
         std::ostringstream name;
         name << (BillboardSet::billboardSetCounter_s++);
-        this->billboardSet_ = GraphicsEngine::getSingleton().getSceneManager()->createBillboardSet("Billboard" + name.str(), count);
+        this->billboardSet_ = GraphicsEngine::getSingleton().getLevelSceneManager()->createBillboardSet("Billboard" + name.str(), count);
         this->billboardSet_->createBillboard(position, colour);
         this->billboardSet_->setMaterialName(file);
@@ -85,5 +85,5 @@
     {
         if (this->billboardSet_)
-            GraphicsEngine::getSingleton().getSceneManager()->destroyBillboardSet(this->billboardSet_);
+            GraphicsEngine::getSingleton().getLevelSceneManager()->destroyBillboardSet(this->billboardSet_);
     }
 }
Index: code/branches/gui/src/orxonox/tools/Light.cc
===================================================================
--- code/branches/gui/src/orxonox/tools/Light.cc	(revision 1636)
+++ code/branches/gui/src/orxonox/tools/Light.cc	(revision 1638)
@@ -49,5 +49,5 @@
         std::ostringstream name;
         name << (Light::lightCounter_s++);
-        this->light_ = GraphicsEngine::getSingleton().getSceneManager()->createLight("Light" + name.str());
+        this->light_ = GraphicsEngine::getSingleton().getLevelSceneManager()->createLight("Light" + name.str());
         this->light_->setType(type);
         this->light_->setDiffuseColour(diffuse);
@@ -58,5 +58,5 @@
     {
         if (this->light_)
-            GraphicsEngine::getSingleton().getSceneManager()->destroyLight(this->light_);
+            GraphicsEngine::getSingleton().getLevelSceneManager()->destroyLight(this->light_);
     }
 }
Index: code/branches/gui/src/orxonox/tools/Mesh.cc
===================================================================
--- code/branches/gui/src/orxonox/tools/Mesh.cc	(revision 1636)
+++ code/branches/gui/src/orxonox/tools/Mesh.cc	(revision 1638)
@@ -49,5 +49,5 @@
         std::ostringstream name;
         name << (Mesh::meshCounter_s++);
-        this->entity_ = GraphicsEngine::getSingleton().getSceneManager()->createEntity("Mesh" + name.str(), file);
+        this->entity_ = GraphicsEngine::getSingleton().getLevelSceneManager()->createEntity("Mesh" + name.str(), file);
     }
 
@@ -55,5 +55,5 @@
     {
         if (this->entity_)
-            GraphicsEngine::getSingleton().getSceneManager()->destroyEntity(this->entity_);
+            GraphicsEngine::getSingleton().getLevelSceneManager()->destroyEntity(this->entity_);
     }
 }
Index: code/branches/gui/src/orxonox/tools/ParticleInterface.cc
===================================================================
--- code/branches/gui/src/orxonox/tools/ParticleInterface.cc	(revision 1636)
+++ code/branches/gui/src/orxonox/tools/ParticleInterface.cc	(revision 1638)
@@ -55,6 +55,6 @@
     this->bEnabled_ = true;
     this->detaillevel_ = (unsigned int)detaillevel;
-    this->particleSystem_ = GraphicsEngine::getSingleton().getSceneManager()->createParticleSystem("particles" + getConvertedValue<unsigned int, std::string>(ParticleInterface::counter_s++), templateName);
-    this->particleSystem_->setSpeedFactor(Orxonox::getSingleton()->getTimeFactor());
+    this->particleSystem_ = GraphicsEngine::getSingleton().getLevelSceneManager()->createParticleSystem("particles" + getConvertedValue<unsigned int, std::string>(ParticleInterface::counter_s++), templateName);
+    this->particleSystem_->setSpeedFactor(Orxonox::getSingleton().getTimeFactor());
 
     if (GraphicsEngine::getSingleton().getDetailLevelParticle() < (unsigned int)this->detaillevel_)
@@ -72,5 +72,5 @@
   {
     this->particleSystem_->removeAllEmitters();
-    GraphicsEngine::getSingleton().getSceneManager()->destroyParticleSystem(particleSystem_);
+    GraphicsEngine::getSingleton().getLevelSceneManager()->destroyParticleSystem(particleSystem_);
   }
 
@@ -171,9 +171,9 @@
   void ParticleInterface::setSpeedFactor(float factor)
   {
-    this->particleSystem_->setSpeedFactor(Orxonox::getSingleton()->getTimeFactor() * factor);
+    this->particleSystem_->setSpeedFactor(Orxonox::getSingleton().getTimeFactor() * factor);
   }
   float ParticleInterface::getSpeedFactor() const
   {
-    return (this->particleSystem_->getSpeedFactor() / Orxonox::getSingleton()->getTimeFactor());
+    return (this->particleSystem_->getSpeedFactor() / Orxonox::getSingleton().getTimeFactor());
   }
 
Index: code/branches/gui/src/orxonox/tools/WindowEventListener.h
===================================================================
--- code/branches/gui/src/orxonox/tools/WindowEventListener.h	(revision 1636)
+++ code/branches/gui/src/orxonox/tools/WindowEventListener.h	(revision 1638)
@@ -45,12 +45,12 @@
         virtual ~WindowEventListener() { }
 
-		    /** Window has moved position */
-		    virtual void windowMoved() { }
+            /** Window has moved position */
+            virtual void windowMoved() { }
 
-		    /** Window has resized */
-		    virtual void windowResized(int newWidth, int newHeight) { }
+            /** Window has resized */
+            virtual void windowResized(int newWidth, int newHeight) { }
 
-		    /** Window has lost/gained focus */
-		    virtual void windowFocusChanged() { }
+            /** Window has lost/gained focus */
+            virtual void windowFocusChanged() { }
     };
 }
Index: code/branches/gui/src/tolua/tolua++.h
===================================================================
--- code/branches/gui/src/tolua/tolua++.h	(revision 1636)
+++ code/branches/gui/src/tolua/tolua++.h	(revision 1638)
@@ -17,7 +17,32 @@
 #define TOLUA_H
 
+/* original code */
+/*
 #ifndef TOLUA_API
 #define TOLUA_API extern
 #endif
+*/
+
+/********************************
+******* ORXONOX CHANGES *********
+********************************/
+
+#if (defined( __WIN32__ ) || defined( _WIN32 )) && !defined( TOLUA_STATIC_BUILD )
+#  ifdef TOLUA_SHARED_BUILD
+#    define TOLUA_API __declspec(dllexport)
+#  else
+#    if defined( __MINGW32__ )
+#      define TOLUA_API
+#    else
+#      define TOLUA_API __declspec(dllimport)
+#    endif
+#  endif
+#else
+#  define TOLUA_API extern
+#endif
+
+/********************************
+****** END ORXONOX CHANGES ******
+********************************/
 
 #define TOLUA_VERSION "tolua++-1.0.92"
Index: code/branches/gui/src/tolua/toluabind.c
===================================================================
--- code/branches/gui/src/tolua/toluabind.c	(revision 1636)
+++ code/branches/gui/src/tolua/toluabind.c	(revision 1638)
@@ -12,5 +12,5 @@
 
 /* Exported function */
-TOLUA_API int  tolua_tolua_open (lua_State* tolua_S);
+int  tolua_tolua_open (lua_State* tolua_S);
 
 
@@ -21,5 +21,5 @@
 
 /* Open function */
-TOLUA_API int tolua_tolua_open (lua_State* tolua_S)
+int tolua_tolua_open (lua_State* tolua_S)
 {
  tolua_open(tolua_S);
@@ -7622,5 +7622,5 @@
 
 #if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 501
- TOLUA_API int luaopen_tolua (lua_State* tolua_S) {
+ int luaopen_tolua (lua_State* tolua_S) {
  return tolua_tolua_open(tolua_S);
 };
Index: code/branches/gui/src/util/ArgReader.cc
===================================================================
--- code/branches/gui/src/util/ArgReader.cc	(revision 1636)
+++ code/branches/gui/src/util/ArgReader.cc	(revision 1638)
@@ -22,6 +22,7 @@
  *   Author:
  *      Reto Grieder
+ *      Benjamin Knecht <beni_at_orxonox.net>
  *   Co-authors:
- *      Benjamin Knecht <beni_at_orxonox.net>
+ *      ...
  *
  */
@@ -35,60 +36,64 @@
 #include "SubString.h"
 
-ArgReader::ArgReader(int argc, char **argv)
+std::string ArgReader::parse(int argc, char **argv)
 {
-  failure_ = false;
-  errorString_ = "";
-  CmdLineArg arg;
+    std::string errorString;
+    CmdLineArg arg;
+    int i = 1;
+    while (i < argc)
+    {
+        if (argv[i][0] == '-' && argv[i][1] == '-') // name
+        {
+            if (argv[i][2] == '\0')
+            {
+                errorString += "Expected word after \"--\".\n";
+            }
+            arg.bChecked_ = false;
+            arg.name_ = argv[i] + 2;
+            arg.value_ = " ";
+            arguments_.push_back(arg);
+        }
+        else // value
+        {
+            if (arguments_.size() == 0)
+            {
+                errorString += "Expected \"--\" in command line arguments.\n";
+                arg.bChecked_ = false;
+                arg.name_ = "";
+                arg.value_ = " ";
+                arguments_.push_back(arg);
+            }
 
-  int i = 1;
-  while (i < argc)
-  {
-    if (argv[i][0] == '-' && argv[i][1] == '-') // name
-    {
-      if (argv[i][2] == '\0')
-      {
-        failure_ = true;
-        errorString_ += "Expected word after \"--\".\n";
-      }
-      arg.bChecked_ = false;
-      arg.name_ = argv[i] + 2;
-      arg.value_ = "";
-      arguments_.push_back(arg);
+            if (arguments_.back().value_ != " ")
+                arguments_.back().value_ += " " + std::string(argv[i]);
+            else
+                arguments_.back().value_ = argv[i];
+        }
+        ++i;
     }
-    else // value
-    {
-      if (arguments_.size() == 0)
-      {
-        failure_ = true;
-        errorString_ += "Expected \"--\" in command line arguments.\n";
-        arg.bChecked_ = false;
-        arg.name_ = "";
-        arg.value_ = "";
-        arguments_.push_back(arg);
-      }
-
-      if (arguments_.back().value_ != "")
-        arguments_.back().value_ += " " + std::string(argv[i]);
-      else
-        arguments_.back().value_ = argv[i];
-    }
-    ++i;
-  }
+    return errorString;
 }
 
-bool ArgReader::errorHandling()
+const std::string& ArgReader::getArgument(const std::string& option)
 {
-  bool argumentsChecked = true;
-  for (unsigned int i = 1; i < arguments_.size(); ++i)
-    argumentsChecked &= arguments_[i].bChecked_;
-
-  if (!argumentsChecked)
-    errorString_ += "Not all arguments could be matched.\n";
-
-  return !argumentsChecked || failure_;
+    unsigned int iArg = 0;
+    while (iArg < arguments_.size())
+    {
+        if (arguments_[iArg].name_ == option)
+        {
+            arguments_[iArg].bChecked_ = true;
+            return arguments_[iArg].value_;
+        }
+        ++iArg;
+    }
+    return blankString;
 }
 
-const std::string& ArgReader::getErrorString()
+bool ArgReader::allChecked()
 {
-  return errorString_;
+    bool argumentsChecked = true;
+    for (unsigned int i = 1; i < arguments_.size(); ++i)
+        argumentsChecked &= arguments_[i].bChecked_;
+
+    return argumentsChecked;
 }
Index: code/branches/gui/src/util/ArgReader.h
===================================================================
--- code/branches/gui/src/util/ArgReader.h	(revision 1636)
+++ code/branches/gui/src/util/ArgReader.h	(revision 1638)
@@ -22,6 +22,7 @@
  *   Author:
  *      Reto Grieder
+ *      Benjamin Knecht <beni_at_orxonox.net>
  *   Co-authors:
- *      Benjamin Knecht <beni_at_orxonox.net>
+ *      ...
  *
  */
@@ -42,75 +43,23 @@
 #include "Convert.h"
 
-struct _UtilExport CmdLineArg
-{
-  std::string name_;
-  std::string value_;
-  bool bChecked_;
-};
 
 class _UtilExport ArgReader
 {
-  public:
-    ArgReader(int argc, char **argv);
-    template <class T>
-    void checkArgument(std::string option, T* value, bool must = false);
-    bool errorHandling();
-    const std::string& getErrorString();
+public:
+    ArgReader() { }
+    std::string parse(int argc, char **argv);
+    const std::string& getArgument(const std::string& option);
+    bool allChecked();
 
-  private:
+private:
+    struct CmdLineArg
+    {
+        std::string name_;
+        std::string value_;
+        bool bChecked_;
+    };
+
     std::vector<CmdLineArg> arguments_;
-    bool failure_;
-    std::string errorString_;
 };
 
-template <class T>
-void ArgReader::checkArgument(std::string option, T* value, bool must)
-{
-  unsigned int iArg = 0;
-  while (iArg < arguments_.size())
-  {
-    if (arguments_[iArg].name_ == option)
-      break;
-    ++iArg;
-  }
-  if (iArg == arguments_.size())
-  {
-    if (must)
-    {
-      failure_ = true;
-      errorString_ += "Cannot find mandatory argument \"" + option + "\"\n";
-      return;
-    }
-    else
-      return;
-  }
-
-  arguments_[iArg].bChecked_ = true;
-
-  if (!convertValue(value, arguments_[iArg].value_))
-  {
-    failure_ = true;
-    errorString_ += "Cannot convert argument value for option \"" + option + "\"\n";
-  }
-}
-
-template <>
-void ArgReader::checkArgument(std::string option, bool* value, bool must)
-{
-  // for type bool, only check whether the option was set or not
-  unsigned int iArg = 0;
-  while (iArg < arguments_.size())
-  {
-    if (arguments_[iArg].name_ == option)
-    {
-      arguments_[iArg].bChecked_ = true;
-      *value = true;
-      break;
-    }
-    ++iArg;
-  }
-  if (iArg == arguments_.size())
-    *value = false;
-}
-
 #endif /* _ArgReader_H__ */
Index: code/branches/gui/src/util/OrxonoxPlatform.h
===================================================================
--- code/branches/gui/src/util/OrxonoxPlatform.h	(revision 1636)
+++ code/branches/gui/src/util/OrxonoxPlatform.h	(revision 1638)
@@ -103,4 +103,17 @@
 #else
 #  define ORXONOX_ARCH_TYPE ORXONOX_ARCHITECTURE_32
+#endif
+
+// try to define function information
+#ifndef __FUNCTIONNAME__
+#  if ORXONOX_COMPILER == ORXONOX_COMPILER_BORL
+#    define __FUNCTIONNAME__ __FUNC__
+#  elif ORXONOX_COMPILER == ORXONOX_COMPILER_GNUC
+#    define __FUNCTIONNAME__ __PRETTY_FUNCTION__
+#  elif ORXONOX_COMPILER == ORXONOX_COMPILER_MSVC
+#    define __FUNCTIONNAME__ __FUNCTION__
+#  else
+#    define __FUNCTIONNAME__
+#  endif
 #endif
 
@@ -265,5 +278,5 @@
 // generated code from nvparse etc). I doubt very much that these calls
 // will ever be actually removed from VC anyway, it would break too much code.
-//#	pragma warning( disable: 4996)
+//# pragma warning( disable: 4996)
 
 // disable: "conditional expression constant", always occurs on
Index: code/branches/gui/src/util/Sleep.h
===================================================================
--- code/branches/gui/src/util/Sleep.h	(revision 1636)
+++ code/branches/gui/src/util/Sleep.h	(revision 1638)
@@ -29,5 +29,5 @@
 /**
  @file  Sleep.h
- @brief Macros for using sleep() and usleep() under windows
+ @brief Functions for using sleep() and usleep() under windows
  */
 
Index: code/branches/gui/visual_studio/base_properties.vsprops
===================================================================
--- code/branches/gui/visual_studio/base_properties.vsprops	(revision 1636)
+++ code/branches/gui/visual_studio/base_properties.vsprops	(revision 1638)
@@ -8,5 +8,6 @@
 	<Tool
 		Name="VCCLCompilerTool"
-		AdditionalIncludeDirectories="&quot;$(RootDir)&quot;;&quot;$(RootDir)src&quot;;&quot;$(RootDir)src\orxonox&quot;;&quot;$(RootDir)src\tolua&quot;;&quot;$(RootDir)src\ois&quot;;&quot;$(LibDir)ogre-1.4.8\OgreMain\include&quot;;&quot;$(LibDir)boost-1.35.0&quot;;&quot;$(LibDir)enet-1.2\include&quot;;&quot;$(LibDir)libogg-1.1.3\include&quot;;&quot;$(LibDir)libvorbis-1.2.0\include&quot;;&quot;$(LibDir)lua-5.1.3\src&quot;;&quot;$(LibDir)openal-1.1\include&quot;;&quot;$(LibDir)openal-1.1\alut\include&quot;;&quot;$(LibDir)tcl-8.5.\generic&quot;;&quot;$(LibDir)zlib-1.2.3&quot;"
+		AdditionalIncludeDirectories="&quot;$(RootDir)&quot;;&quot;$(RootDir)src&quot;;&quot;$(RootDir)src\orxonox&quot;;&quot;$(RootDir)src\tolua&quot;;&quot;$(RootDir)src\ois&quot;;&quot;$(LibDir)ogre-1.4.8\OgreMain\include&quot;;&quot;$(LibDir)boost-1.35.0&quot;;&quot;$(LibDir)cegui-0.6.1\include&quot;;&quot;$(LibDir)cegui-0.6.1\ScriptingModules\CEGUILua\LuaScriptModule\include&quot;;&quot;$(LibDir)enet-1.2\include&quot;;&quot;$(LibDir)libogg-1.1.3\include&quot;;&quot;$(LibDir)libvorbis-1.2.0\include&quot;;&quot;$(LibDir)lua-5.1.3\src&quot;;&quot;$(LibDir)openal-1.1\include&quot;;&quot;$(LibDir)openal-1.1\alut\include&quot;;&quot;$(LibDir)tcl-8.5.\generic&quot;;&quot;$(LibDir)zlib-1.2.3&quot;;&quot;$(LibDir)ogre-1.4.9\Samples\Common\CEGUIRenderer\include&quot;"
+		AdditionalOptions="/MP2"
 		PreprocessorDefinitions="WIN32;__WIN32__;_WIN32;BOOST_ALL_DYN_LINK;OIS_DYNAMIC_LIB; ZLIB_WINAPI"
 		WarningLevel="3"
Index: code/branches/gui/visual_studio/orxonox_properties.vsprops
===================================================================
--- code/branches/gui/visual_studio/orxonox_properties.vsprops	(revision 1636)
+++ code/branches/gui/visual_studio/orxonox_properties.vsprops	(revision 1638)
@@ -8,5 +8,5 @@
 	<Tool
 		Name="VCCLCompilerTool"
-		PreprocessorDefinitions="ORXONOX_NO_EXPORTS;NETWORK_STATIC_BUILD"
+		PreprocessorDefinitions="ORXONOX_NO_EXPORTS;NETWORK_STATIC_BUILD;OGRE_GUIRENDERER_EXPORTS"
 		UsePrecompiledHeader="2"
 		PrecompiledHeaderThrough="OrxonoxStableHeaders.h"
@@ -14,5 +14,5 @@
 	<Tool
 		Name="VCLinkerTool"
-		AdditionalDependencies="OgreMain$(CSS).lib tcl85t.lib enet-1.2$(CS).lib zlib-1.2.3$(CS).lib"
+		AdditionalDependencies="OgreMain$(CSS).lib tcl85t.lib enet-1.2$(CS).lib zlib-1.2.3$(CS).lib CEGUILua$(CS).lib CEGUIBase$(CS).lib lua-5.1.3$(CS).lib"
 		OutputFile="$(OutDir)$(ProjectName)$(CS).exe"
 		IgnoreDefaultLibraryNames="LIBCMT;LIBCMTD"
Index: code/branches/gui/visual_studio/orxonox_vc8.sln
===================================================================
--- code/branches/gui/visual_studio/orxonox_vc8.sln	(revision 1636)
+++ code/branches/gui/visual_studio/orxonox_vc8.sln	(revision 1638)
@@ -18,4 +18,5 @@
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tolua_app", "vc8\tolua_app.vcproj", "{A0724246-CB7C-420B-BCF0-68EF205AFE34}"
 	ProjectSection(ProjectDependencies) = postProject
+		{71FC0211-5EB5-4637-BE8A-A48EC3CC27D0} = {71FC0211-5EB5-4637-BE8A-A48EC3CC27D0}
 		{35E36A06-0A5C-4A0D-9AB6-5A05EAA87626} = {35E36A06-0A5C-4A0D-9AB6-5A05EAA87626}
 	EndProjectSection
@@ -44,9 +45,15 @@
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "orxonox", "vc8\orxonox.vcproj", "{0B6C5CFD-F91B-432A-80A3-2610F61E060B}"
 	ProjectSection(ProjectDependencies) = postProject
-		{4733BD1A-E04C-458D-8BFB-5010250EA497} = {4733BD1A-E04C-458D-8BFB-5010250EA497}
+		{35E36A06-0A5C-4A0D-9AB6-5A05EAA87626} = {35E36A06-0A5C-4A0D-9AB6-5A05EAA87626}
 		{35575B59-E1AE-40E8-89C4-2862B5B09B68} = {35575B59-E1AE-40E8-89C4-2862B5B09B68}
 		{2240ECD7-2F48-4431-8E1B-25466A384CCC} = {2240ECD7-2F48-4431-8E1B-25466A384CCC}
 		{F101C2F0-1CB9-4A57-827B-6C399A99B28F} = {F101C2F0-1CB9-4A57-827B-6C399A99B28F}
 		{271715F3-5B90-4110-A552-70C788084A86} = {271715F3-5B90-4110-A552-70C788084A86}
+		{4733BD1A-E04C-458D-8BFB-5010250EA497} = {4733BD1A-E04C-458D-8BFB-5010250EA497}
+	EndProjectSection
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tolua_gen", "vc8\tolua_gen.vcproj", "{71FC0211-5EB5-4637-BE8A-A48EC3CC27D0}"
+	ProjectSection(ProjectDependencies) = postProject
+		{35E36A06-0A5C-4A0D-9AB6-5A05EAA87626} = {35E36A06-0A5C-4A0D-9AB6-5A05EAA87626}
 	EndProjectSection
 EndProject
@@ -97,4 +104,8 @@
 		{0B6C5CFD-F91B-432A-80A3-2610F61E060B}.Release|Win32.ActiveCfg = Release|Win32
 		{0B6C5CFD-F91B-432A-80A3-2610F61E060B}.Release|Win32.Build.0 = Release|Win32
+		{71FC0211-5EB5-4637-BE8A-A48EC3CC27D0}.Debug|Win32.ActiveCfg = Debug|Win32
+		{71FC0211-5EB5-4637-BE8A-A48EC3CC27D0}.Debug|Win32.Build.0 = Debug|Win32
+		{71FC0211-5EB5-4637-BE8A-A48EC3CC27D0}.Release|Win32.ActiveCfg = Release|Win32
+		{71FC0211-5EB5-4637-BE8A-A48EC3CC27D0}.Release|Win32.Build.0 = Release|Win32
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
Index: code/branches/gui/visual_studio/tolua_app_properties.vsprops
===================================================================
--- code/branches/gui/visual_studio/tolua_app_properties.vsprops	(revision 1636)
+++ code/branches/gui/visual_studio/tolua_app_properties.vsprops	(revision 1638)
@@ -8,5 +8,6 @@
 	<Tool
 		Name="VCCLCompilerTool"
-		DisableSpecificWarnings="4996"
+		PreprocessorDefinitions="TOLUA_STATIC_BUILD"
+		CompileAs="1"
 	/>
 	<Tool
Index: code/branches/gui/visual_studio/tolua_gen_properties.vsprops
===================================================================
--- code/branches/gui/visual_studio/tolua_gen_properties.vsprops	(revision 1638)
+++ code/branches/gui/visual_studio/tolua_gen_properties.vsprops	(revision 1638)
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioPropertySheet
+	ProjectType="Visual C++"
+	Version="8.00"
+	Name="tolua_gen_properties"
+	InheritedPropertySheets=".\directory_properties.vsprops"
+	>
+	<Tool
+		Name="VCCLCompilerTool"
+		CompileAs="1"
+	/>
+	<Tool
+		Name="VCLinkerTool"
+		AdditionalDependencies="lua-5.1.3$(CS).lib"
+		OutputFile="$(OutDir)$(ProjectName)$(CS).exe"
+	/>
+</VisualStudioPropertySheet>
Index: code/branches/gui/visual_studio/tolua_properties.vsprops
===================================================================
--- code/branches/gui/visual_studio/tolua_properties.vsprops	(revision 1636)
+++ code/branches/gui/visual_studio/tolua_properties.vsprops	(revision 1638)
@@ -8,5 +8,11 @@
 	<Tool
 		Name="VCCLCompilerTool"
+		PreprocessorDefinitions="TOLUA_SHARED_BUILD"
+		CompileAs="2"
 		DisableSpecificWarnings="4996"
 	/>
+	<Tool
+		Name="VCLinkerTool"
+		AdditionalDependencies="lua-5.1.3$(CS).lib"
+	/>
 </VisualStudioPropertySheet>
Index: code/branches/gui/visual_studio/vc8/core.vcproj
===================================================================
--- code/branches/gui/visual_studio/vc8/core.vcproj	(revision 1636)
+++ code/branches/gui/visual_studio/vc8/core.vcproj	(revision 1638)
@@ -165,4 +165,8 @@
 			</File>
 			<File
+				RelativePath="..\..\src\core\Exception.cc"
+				>
+			</File>
+			<File
 				RelativePath="..\..\src\core\Language.cc"
 				>
@@ -194,4 +198,14 @@
 					RelativePath="..\..\src\core\tolua\tolua.pkg"
 					>
+					<FileConfiguration
+						Name="Debug|Win32"
+						>
+						<Tool
+							Name="VCCustomBuildTool"
+							Description="Generating tolua bind files..."
+							CommandLine="&quot;$(OutDir)\tolua_app_d.exe&quot; -n Core -o ../../src/core/tolua/tolua_bind.cc -H ../../src/core/tolua/tolua_bind.h ../../src/core/tolua/tolua.pkg&#x0D;&#x0A;"
+							Outputs="$(RootDir)\src\core\tolua\tolua_bind.cc; $(RootDir)\src\core\tolua\tolua_bind.h"
+						/>
+					</FileConfiguration>
 					<FileConfiguration
 						Name="Release|Win32"
@@ -200,5 +214,5 @@
 							Name="VCCustomBuildTool"
 							Description="Generating tolua bind files..."
-							CommandLine="&quot;$(OutDir)\tolua_app.exe&quot; -n core -o ../../src/core/tolua/tolua_bind.cc -H ../../src/core/tolua/tolua_bind.h ../../src/core/tolua/tolua.pkg"
+							CommandLine="&quot;$(OutDir)\tolua_app.exe&quot; -n Core -o ../../src/core/tolua/tolua_bind.cc -H ../../src/core/tolua/tolua_bind.h ../../src/core/tolua/tolua.pkg&#x0D;&#x0A;"
 							Outputs="$(RootDir)\src\core\tolua\tolua_bind.cc; $(RootDir)\src\core\tolua\tolua_bind.h"
 						/>
@@ -294,4 +308,8 @@
 				</File>
 				<File
+					RelativePath="..\..\src\core\input\ExtendedInputState.cc"
+					>
+				</File>
+				<File
 					RelativePath="..\..\src\core\input\HalfAxis.cc"
 					>
@@ -315,4 +333,8 @@
 				<File
 					RelativePath="..\..\src\core\input\KeyDetector.cc"
+					>
+				</File>
+				<File
+					RelativePath="..\..\src\core\input\SimpleInputState.cc"
 					>
 				</File>
@@ -373,4 +395,8 @@
 			</File>
 			<File
+				RelativePath="..\..\src\core\Exception.h"
+				>
+			</File>
+			<File
 				RelativePath="..\..\src\core\Language.h"
 				>
@@ -412,4 +438,8 @@
 				</File>
 				<File
+					RelativePath="..\..\src\core\input\ExtendedInputState.h"
+					>
+				</File>
+				<File
 					RelativePath="..\..\src\core\input\HalfAxis.h"
 					>
@@ -432,4 +462,8 @@
 				</File>
 				<File
+					RelativePath="..\..\src\core\input\InputState.h"
+					>
+				</File>
+				<File
 					RelativePath="..\..\src\core\input\KeyBinder.h"
 					>
@@ -437,4 +471,8 @@
 				<File
 					RelativePath="..\..\src\core\input\KeyDetector.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\src\core\input\SimpleInputState.h"
 					>
 				</File>
Index: code/branches/gui/visual_studio/vc8/ois.vcproj
===================================================================
--- code/branches/gui/visual_studio/vc8/ois.vcproj	(revision 1636)
+++ code/branches/gui/visual_studio/vc8/ois.vcproj	(revision 1638)
@@ -43,4 +43,5 @@
 			<Tool
 				Name="VCCLCompilerTool"
+				AdditionalOptions="/MP2"
 				Optimization="2"
 				InlineFunctionExpansion="1"
@@ -128,4 +129,5 @@
 			<Tool
 				Name="VCCLCompilerTool"
+				AdditionalOptions="/MP2"
 				Optimization="0"
 				AdditionalIncludeDirectories="$(RootDir)\src\ois"
Index: code/branches/gui/visual_studio/vc8/orxonox.vcproj
===================================================================
--- code/branches/gui/visual_studio/vc8/orxonox.vcproj	(revision 1636)
+++ code/branches/gui/visual_studio/vc8/orxonox.vcproj	(revision 1638)
@@ -285,128 +285,4 @@
 					>
 				</File>
-				<Filter
-					Name="weapon"
-					>
-					<File
-						RelativePath="..\..\src\orxonox\objects\weapon\AmmunitionDump.cc"
-						>
-						<FileConfiguration
-							Name="Debug|Win32"
-							ExcludedFromBuild="true"
-							>
-							<Tool
-								Name="VCCLCompilerTool"
-							/>
-						</FileConfiguration>
-						<FileConfiguration
-							Name="Release|Win32"
-							ExcludedFromBuild="true"
-							>
-							<Tool
-								Name="VCCLCompilerTool"
-							/>
-						</FileConfiguration>
-					</File>
-					<File
-						RelativePath="..\..\src\orxonox\objects\weapon\BarrelGun.cc"
-						>
-						<FileConfiguration
-							Name="Debug|Win32"
-							ExcludedFromBuild="true"
-							>
-							<Tool
-								Name="VCCLCompilerTool"
-							/>
-						</FileConfiguration>
-						<FileConfiguration
-							Name="Release|Win32"
-							ExcludedFromBuild="true"
-							>
-							<Tool
-								Name="VCCLCompilerTool"
-							/>
-						</FileConfiguration>
-					</File>
-					<File
-						RelativePath="..\..\src\orxonox\objects\weapon\BaseWeapon.cc"
-						>
-						<FileConfiguration
-							Name="Debug|Win32"
-							ExcludedFromBuild="true"
-							>
-							<Tool
-								Name="VCCLCompilerTool"
-							/>
-						</FileConfiguration>
-						<FileConfiguration
-							Name="Release|Win32"
-							ExcludedFromBuild="true"
-							>
-							<Tool
-								Name="VCCLCompilerTool"
-							/>
-						</FileConfiguration>
-					</File>
-					<File
-						RelativePath="..\..\src\orxonox\objects\weapon\Bullet.cc"
-						>
-						<FileConfiguration
-							Name="Debug|Win32"
-							ExcludedFromBuild="true"
-							>
-							<Tool
-								Name="VCCLCompilerTool"
-							/>
-						</FileConfiguration>
-						<FileConfiguration
-							Name="Release|Win32"
-							ExcludedFromBuild="true"
-							>
-							<Tool
-								Name="VCCLCompilerTool"
-							/>
-						</FileConfiguration>
-					</File>
-					<File
-						RelativePath="..\..\src\orxonox\objects\weapon\BulletManager.cc"
-						>
-						<FileConfiguration
-							Name="Debug|Win32"
-							ExcludedFromBuild="true"
-							>
-							<Tool
-								Name="VCCLCompilerTool"
-							/>
-						</FileConfiguration>
-						<FileConfiguration
-							Name="Release|Win32"
-							ExcludedFromBuild="true"
-							>
-							<Tool
-								Name="VCCLCompilerTool"
-							/>
-						</FileConfiguration>
-					</File>
-					<File
-						RelativePath="..\..\src\orxonox\objects\weapon\WeaponStation.cc"
-						>
-						<FileConfiguration
-							Name="Debug|Win32"
-							ExcludedFromBuild="true"
-							>
-							<Tool
-								Name="VCCLCompilerTool"
-							/>
-						</FileConfiguration>
-						<FileConfiguration
-							Name="Release|Win32"
-							ExcludedFromBuild="true"
-							>
-							<Tool
-								Name="VCCLCompilerTool"
-							/>
-						</FileConfiguration>
-					</File>
-				</Filter>
 			</Filter>
 			<Filter
@@ -445,4 +321,30 @@
 				Name="tolua"
 				>
+				<File
+					RelativePath="..\..\src\orxonox\tolua\tolua.pkg"
+					>
+					<FileConfiguration
+						Name="Debug|Win32"
+						>
+						<Tool
+							Name="VCCustomBuildTool"
+							Description="Generating tolua bind files..."
+							CommandLine="&quot;$(OutDir)\tolua_app_d.exe&quot; -n Orxonox -o ../../src/orxonox/tolua/tolua_bind.cc -H ../../src/orxonox/tolua/tolua_bind.h ../../src/orxonox/tolua/tolua.pkg&#x0D;&#x0A;"
+							AdditionalDependencies="$(RootDir)\src\orxonox\gui\GUIManager.h"
+							Outputs="$(RootDir)\src\orxonox\tolua\tolua_bind.cc; $(RootDir)\src\orxonox\tolua\tolua_bind.h"
+						/>
+					</FileConfiguration>
+					<FileConfiguration
+						Name="Release|Win32"
+						>
+						<Tool
+							Name="VCCustomBuildTool"
+							Description="Generating tolua bind files..."
+							CommandLine="&quot;$(OutDir)\tolua_app.exe&quot; -n Orxonox -o ../../src/orxonox/tolua/tolua_bind.cc -H ../../src/orxonox/tolua/tolua_bind.h ../../src/orxonox/tolua/tolua.pkg&#x0D;&#x0A;"
+							AdditionalDependencies="$(RootDir)\src\orxonox\gui\GUIManager.h"
+							Outputs="$(RootDir)\src\orxonox\tolua\tolua_bind.cc; $(RootDir)\src\orxonox\tolua\tolua_bind.h"
+						/>
+					</FileConfiguration>
+				</File>
 				<File
 					RelativePath="..\..\src\orxonox\tolua\tolua_bind.cc"
@@ -521,4 +423,72 @@
 					</File>
 				</Filter>
+			</Filter>
+			<Filter
+				Name="gui"
+				>
+				<File
+					RelativePath="..\..\src\orxonox\gui\GUIManager.cc"
+					>
+				</File>
+				<File
+					RelativePath="..\..\src\orxonox\gui\OgreCEGUIRenderer.cpp"
+					>
+					<FileConfiguration
+						Name="Debug|Win32"
+						>
+						<Tool
+							Name="VCCLCompilerTool"
+							UsePrecompiledHeader="0"
+						/>
+					</FileConfiguration>
+					<FileConfiguration
+						Name="Release|Win32"
+						>
+						<Tool
+							Name="VCCLCompilerTool"
+							UsePrecompiledHeader="0"
+						/>
+					</FileConfiguration>
+				</File>
+				<File
+					RelativePath="..\..\src\orxonox\gui\OgreCEGUIResourceProvider.cpp"
+					>
+					<FileConfiguration
+						Name="Debug|Win32"
+						>
+						<Tool
+							Name="VCCLCompilerTool"
+							UsePrecompiledHeader="0"
+						/>
+					</FileConfiguration>
+					<FileConfiguration
+						Name="Release|Win32"
+						>
+						<Tool
+							Name="VCCLCompilerTool"
+							UsePrecompiledHeader="0"
+						/>
+					</FileConfiguration>
+				</File>
+				<File
+					RelativePath="..\..\src\orxonox\gui\OgreCEGUITexture.cpp"
+					>
+					<FileConfiguration
+						Name="Debug|Win32"
+						>
+						<Tool
+							Name="VCCLCompilerTool"
+							UsePrecompiledHeader="0"
+						/>
+					</FileConfiguration>
+					<FileConfiguration
+						Name="Release|Win32"
+						>
+						<Tool
+							Name="VCCLCompilerTool"
+							UsePrecompiledHeader="0"
+						/>
+					</FileConfiguration>
+				</File>
 			</Filter>
 		</Filter>
@@ -627,32 +597,4 @@
 					>
 				</File>
-				<Filter
-					Name="weapon"
-					>
-					<File
-						RelativePath="..\..\src\orxonox\objects\weapon\AmmunitionDump.h"
-						>
-					</File>
-					<File
-						RelativePath="..\..\src\orxonox\objects\weapon\BarrelGun.h"
-						>
-					</File>
-					<File
-						RelativePath="..\..\src\orxonox\objects\weapon\BaseWeapon.h"
-						>
-					</File>
-					<File
-						RelativePath="..\..\src\orxonox\objects\weapon\Bullet.h"
-						>
-					</File>
-					<File
-						RelativePath="..\..\src\orxonox\objects\weapon\BulletManager.h"
-						>
-					</File>
-					<File
-						RelativePath="..\..\src\orxonox\objects\weapon\WeaponStation.h"
-						>
-					</File>
-				</Filter>
 			</Filter>
 			<Filter
@@ -751,4 +693,24 @@
 					</File>
 				</Filter>
+			</Filter>
+			<Filter
+				Name="gui"
+				>
+				<File
+					RelativePath="..\..\src\orxonox\gui\GUIManager.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\src\orxonox\gui\OgreCEGUIRenderer.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\src\orxonox\gui\OgreCEGUIResourceProvider.h"
+					>
+				</File>
+				<File
+					RelativePath="..\..\src\orxonox\gui\OgreCEGUITexture.h"
+					>
+				</File>
 			</Filter>
 		</Filter>
Index: code/branches/gui/visual_studio/vc8/tolua.vcproj
===================================================================
--- code/branches/gui/visual_studio/vc8/tolua.vcproj	(revision 1636)
+++ code/branches/gui/visual_studio/vc8/tolua.vcproj	(revision 1638)
@@ -18,5 +18,5 @@
 		<Configuration
 			Name="Debug|Win32"
-			ConfigurationType="4"
+			ConfigurationType="2"
 			InheritedPropertySheets="$(SolutionDir)base_properties_debug.vsprops;..\tolua_properties.vsprops"
 			CharacterSet="1"
@@ -50,8 +50,11 @@
 			/>
 			<Tool
-				Name="VCLibrarianTool"
+				Name="VCLinkerTool"
 			/>
 			<Tool
 				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
 			/>
 			<Tool
@@ -65,4 +68,10 @@
 			/>
 			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
 				Name="VCPostBuildEventTool"
 			/>
@@ -70,5 +79,5 @@
 		<Configuration
 			Name="Release|Win32"
-			ConfigurationType="4"
+			ConfigurationType="2"
 			InheritedPropertySheets="$(SolutionDir)base_properties_release.vsprops;..\tolua_properties.vsprops"
 			CharacterSet="1"
@@ -103,8 +112,11 @@
 			/>
 			<Tool
-				Name="VCLibrarianTool"
+				Name="VCLinkerTool"
 			/>
 			<Tool
 				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
 			/>
 			<Tool
@@ -116,4 +128,10 @@
 			<Tool
 				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
 			/>
 			<Tool
Index: code/branches/gui/visual_studio/vc8/tolua_app.vcproj
===================================================================
--- code/branches/gui/visual_studio/vc8/tolua_app.vcproj	(revision 1636)
+++ code/branches/gui/visual_studio/vc8/tolua_app.vcproj	(revision 1638)
@@ -153,5 +153,29 @@
 			</File>
 			<File
-				RelativePath="..\..\src\tolua\toluabind.c"
+				RelativePath="..\..\src\tolua\tolua.pkg"
+				>
+				<FileConfiguration
+					Name="Debug|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						Description="Generating tolua bind files..."
+						CommandLine="&quot;$(OutDir)\tolua_gen_d.exe&quot; -n tolua -o ../../src/tolua/toluabind_orxonox.cc -H ../../src/tolua/toluabind_orxonox.h ../../src/tolua/tolua.pkg"
+						Outputs="$(RootDir)\src\tolua\toluabind_orxonox.cc; $(RootDir)\src\tolua\toluabind_orxonox.h"
+					/>
+				</FileConfiguration>
+				<FileConfiguration
+					Name="Release|Win32"
+					>
+					<Tool
+						Name="VCCustomBuildTool"
+						Description="Generating tolua bind files..."
+						CommandLine="&quot;$(OutDir)\tolua_gen.exe&quot; -n tolua -o ../../src/tolua/toluabind_orxonox.cc -H ../../src/tolua/toluabind_orxonox.h ../../src/tolua/tolua.pkg"
+						Outputs="$(RootDir)\src\tolua\toluabind_orxonox.cc; $(RootDir)\src\tolua\toluabind_orxonox.h"
+					/>
+				</FileConfiguration>
+			</File>
+			<File
+				RelativePath="..\..\src\tolua\toluabind_orxonox.cc"
 				>
 			</File>
@@ -162,4 +186,12 @@
 			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
 			>
+			<File
+				RelativePath="..\..\src\tolua\tolua++.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\tolua\toluabind_orxonox.h"
+				>
+			</File>
 		</Filter>
 	</Files>
Index: code/branches/gui/visual_studio/vc8/tolua_gen.vcproj
===================================================================
--- code/branches/gui/visual_studio/vc8/tolua_gen.vcproj	(revision 1638)
+++ code/branches/gui/visual_studio/vc8/tolua_gen.vcproj	(revision 1638)
@@ -0,0 +1,176 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="8.00"
+	Name="tolua_gen"
+	ProjectGUID="{71FC0211-5EB5-4637-BE8A-A48EC3CC27D0}"
+	RootNamespace="FICN"
+	Keyword="Win32Proj"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			ConfigurationType="1"
+			InheritedPropertySheets="$(SolutionDir)base_properties_debug.vsprops;..\tolua_gen_properties.vsprops"
+			CharacterSet="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			ConfigurationType="1"
+			InheritedPropertySheets="$(SolutionDir)base_properties_release.vsprops;..\tolua_gen_properties.vsprops"
+			CharacterSet="1"
+			WholeProgramOptimization="0"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCWebDeploymentTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath="..\..\src\tolua\tolua.c"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\tolua\toluabind.c"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath="..\..\src\tolua\tolua++.h"
+				>
+			</File>
+			<File
+				RelativePath="..\..\src\tolua\toluabind.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>
