Index: code/trunk/src/libraries/core/ArgumentCompletionFunctions.cc
===================================================================
--- code/trunk/src/libraries/core/ArgumentCompletionFunctions.cc	(revision 5781)
+++ code/trunk/src/libraries/core/ArgumentCompletionFunctions.cc	(revision 5929)
@@ -100,5 +100,5 @@
             ArgumentCompletionList classlist;
 
-            for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getIdentifierMapBegin(); it != Identifier::getIdentifierMapEnd(); ++it)
+            for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getStringIdentifierMapBegin(); it != Identifier::getStringIdentifierMapEnd(); ++it)
                 if ((*it).second->hasConfigValues())
                     classlist.push_back(ArgumentCompletionListElement((*it).second->getName(), getLowercase((*it).first)));
@@ -110,7 +110,7 @@
         {
             ArgumentCompletionList configvalues;
-            std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getIdentifierMap().find(classname);
+            std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getStringIdentifierMap().find(classname);
 
-            if (identifier != Identifier::getIdentifierMapEnd() && (*identifier).second->hasConfigValues())
+            if (identifier != Identifier::getStringIdentifierMapEnd() && (*identifier).second->hasConfigValues())
             {
                 for (std::map<std::string, ConfigValueContainer*>::const_iterator it = (*identifier).second->getConfigValueMapBegin(); it != (*identifier).second->getConfigValueMapEnd(); ++it)
@@ -124,6 +124,6 @@
         {
             ArgumentCompletionList oldvalue;
-            std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseIdentifierMap().find(getLowercase(classname));
-            if (identifier != Identifier::getLowercaseIdentifierMapEnd())
+            std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseStringIdentifierMap().find(getLowercase(classname));
+            if (identifier != Identifier::getLowercaseStringIdentifierMapEnd())
             {
                 std::map<std::string, ConfigValueContainer*>::const_iterator variable = (*identifier).second->getLowercaseConfigValueMap().find(getLowercase(varname));
Index: code/trunk/src/libraries/core/BaseObject.cc
===================================================================
--- code/trunk/src/libraries/core/BaseObject.cc	(revision 5781)
+++ code/trunk/src/libraries/core/BaseObject.cc	(revision 5929)
@@ -63,9 +63,9 @@
         this->bVisible_ = true;
         this->oldGametype_ = 0;
+        this->bRegisteredEventStates_ = false;
 
         this->lastLoadedXMLElement_ = 0;
 
-        this->functorSetMainState_ = 0;
-        this->functorGetMainState_ = 0;
+        this->mainStateFunctor_ = 0;
 
         this->setCreator(creator);
@@ -74,5 +74,5 @@
             this->setFile(this->creator_->getFile());
             this->setNamespace(this->creator_->getNamespace());
-            this->setScene(this->creator_->getScene());
+            this->setScene(this->creator_->getScene(), this->creator_->getSceneID());
             this->setGametype(this->creator_->getGametype());
         }
@@ -82,4 +82,5 @@
             this->namespace_ = 0;
             this->scene_ = 0;
+            this->sceneID_ = OBJECTID_UNKNOWN;
             this->gametype_ = 0;
         }
@@ -93,14 +94,12 @@
         if (this->isInitialized())
         {
-            for (std::list<BaseObject*>::const_iterator it = this->events_.begin(); it != this->events_.end(); ++it)
-                (*it)->unregisterEventListener(this);
-
-            for (std::map<BaseObject*, std::string>::const_iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); ++it)
-                it->first->removeEvent(this);
-
-            if (this->functorSetMainState_)
-                delete this->functorSetMainState_;
-            if (this->functorGetMainState_)
-                delete this->functorGetMainState_;
+            for (std::map<BaseObject*, std::string>::const_iterator it = this->eventSources_.begin(); it != this->eventSources_.end(); )
+                this->removeEventSource((it++)->first);
+
+            for (std::set<BaseObject*>::const_iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); )
+                (*(it++))->removeEventSource(this);
+
+            for (std::map<std::string, EventState*>::const_iterator it = this->eventStates_.begin(); it != this->eventStates_.end(); ++it)
+                delete it->second;
         }
     }
@@ -110,5 +109,4 @@
         @param xmlelement The XML-element
         @param loading Loading (true) or saving (false)
-        @return The XML-element
     */
     void BaseObject::XMLPort(Element& xmlelement, XMLPort::Mode mode)
@@ -120,39 +118,27 @@
 
         XMLPortObjectTemplate(BaseObject, Template, "templates", addTemplate, getTemplate, xmlelement, mode, Template*);
-
-        Element* events = xmlelement.FirstChildElement("events", false);
-
+        XMLPortObject(BaseObject, BaseObject, "eventlisteners", addEventListener, getEventListener, xmlelement, mode);
+        
+        Element* events = 0;
+        if (mode == XMLPort::LoadObject || mode == XMLPort::ExpandObject)
+            events = xmlelement.FirstChildElement("events", false);
+        else if (mode == XMLPort::SaveObject)
+            {}
         if (events)
-        {
-            std::list<std::string> eventnames;
-
-            if (mode == XMLPort::LoadObject || mode == XMLPort::ExpandObject)
-            {
-                for (ticpp::Iterator<ticpp::Element> child = events->FirstChildElement(false); child != child.end(); child++)
-                    eventnames.push_back(child->Value());
-            }
-            else if (mode == XMLPort::SaveObject)
-            {
-                for (std::map<std::string, XMLPortObjectContainer*>::const_iterator it = this->getIdentifier()->getXMLPortEventMapBegin(); it != this->getIdentifier()->getXMLPortEventMapEnd(); ++it)
-                    eventnames.push_back(it->first);
-            }
-
-            for (std::list<std::string>::iterator it = eventnames.begin(); it != eventnames.end(); ++it)
-            {
-                std::string sectionname = (*it);
-                ExecutorMember<BaseObject>* loadexecutor = createExecutor(createFunctor(&BaseObject::addEvent), std::string( "BaseObject" ) + "::" + "addEvent");
-                ExecutorMember<BaseObject>* saveexecutor = createExecutor(createFunctor(&BaseObject::getEvent), std::string( "BaseObject" ) + "::" + "getEvent");
-                loadexecutor->setDefaultValue(1, sectionname);
-
-                XMLPortClassObjectContainer<BaseObject, BaseObject>* container = 0;
-                container = (XMLPortClassObjectContainer<BaseObject, BaseObject>*)(this->getIdentifier()->getXMLPortEventContainer(sectionname));
-                if (!container)
-                {
-                    container = new XMLPortClassObjectContainer<BaseObject, BaseObject>(sectionname, this->getIdentifier(), loadexecutor, saveexecutor, false, true);
-                    this->getIdentifier()->addXMLPortEventContainer(sectionname, container);
-                }
-                container->port(this, *events, mode);
-            }
-        }
+            this->XMLEventPort(*events, mode);
+    }
+
+    /**
+        @brief Defines the possible event states of this object and parses eventsources from an XML file.
+        @param xmlelement The XML-element
+        @param loading Loading (true) or saving (false)
+    */
+    void BaseObject::XMLEventPort(Element& xmlelement, XMLPort::Mode mode)
+    {
+        XMLPortEventState(BaseObject, BaseObject, "activity", setActive, xmlelement, mode);
+        XMLPortEventState(BaseObject, BaseObject, "visibility", setVisible, xmlelement, mode);
+        XMLPortEventState(BaseObject, BaseObject, "mainstate", setMainState, xmlelement, mode);
+        
+        this->bRegisteredEventStates_ = true;
     }
 
@@ -220,22 +206,37 @@
     }
 
-    void BaseObject::addEvent(BaseObject* event, const std::string& sectionname)
-    {
-        event->registerEventListener(this, sectionname);
-        this->events_.push_back(event);
-    }
-
-    void BaseObject::removeEvent(BaseObject* event)
-    {
-        this->events_.remove(event);
-    }
-
-    BaseObject* BaseObject::getEvent(unsigned int index) const
+    /**
+        @brief Adds a new event source for a specific state.
+        @param source The object which sends events to this object
+        @param state The state of this object which will be affected by the events
+    */
+    void BaseObject::addEventSource(BaseObject* source, const std::string& state)
+    {
+        this->eventSources_[source] = state;
+        source->registerEventListener(this);
+    }
+
+    /**
+        @brief Removes an eventsource (but doesn't unregister itself at the source).
+    */
+    void BaseObject::removeEventSource(BaseObject* source)
+    {
+        this->eventSources_.erase(source);
+        source->unregisterEventListener(this);
+    }
+
+    /**
+        @brief Returns an eventsource with a given index.
+    */
+    BaseObject* BaseObject::getEventSource(unsigned int index, const std::string& state) const
     {
         unsigned int i = 0;
-        for (std::list<BaseObject*>::const_iterator it = this->events_.begin(); it != this->events_.end(); ++it)
-        {
+        for (std::map<BaseObject*, std::string>::const_iterator it = this->eventSources_.begin(); it != this->eventSources_.end(); ++it)
+        {
+            if (it->second != state)
+                continue;
+            
             if (i == index)
-                return (*it);
+                return it->first;
             ++i;
         }
@@ -243,20 +244,52 @@
     }
 
-    void BaseObject::addEventContainer(const std::string& sectionname, EventContainer* container)
-    {
-        std::map<std::string, EventContainer*>::const_iterator it = this->eventContainers_.find(sectionname);
-        if (it != this->eventContainers_.end())
-        {
-            COUT(2) << "Warning: Overwriting EventContainer in class " << this->getIdentifier()->getName() << "." << std::endl;
+    /**
+        @brief Adds an object which listens to the events of this object. The events are sent to the other objects mainstate.
+    */
+    void BaseObject::addEventListener(BaseObject* listener)
+    {
+        this->eventListenersXML_.insert(listener);
+        listener->addEventSource(this, "mainstate");
+    }
+    
+    /**
+        @brief Returns an event listener with a given index.
+    */
+    BaseObject* BaseObject::getEventListener(unsigned int index) const
+    {
+        unsigned int i = 0;
+        for (std::set<BaseObject*>::const_iterator it = this->eventListenersXML_.begin(); it != this->eventListenersXML_.end(); ++it)
+        {
+            if (i == index)
+                return *it;
+            ++i;
+        }
+        return 0;
+    }
+
+    /**
+        @brief Adds a new event-state to the object. Event-states are states which can be changed by events.
+        @param name  The name of the event
+        @param state The object containing information about the event-state
+    */
+    void BaseObject::addEventState(const std::string& name, EventState* state)
+    {
+        std::map<std::string, EventState*>::const_iterator it = this->eventStates_.find(name);
+        if (it != this->eventStates_.end())
+        {
+            COUT(2) << "Warning: Overwriting EventState in class " << this->getIdentifier()->getName() << "." << std::endl;
             delete (it->second);
         }
 
-        this->eventContainers_[sectionname] = container;
-    }
-
-    EventContainer* BaseObject::getEventContainer(const std::string& sectionname) const
-    {
-        std::map<std::string, EventContainer*>::const_iterator it = this->eventContainers_.find(sectionname);
-        if (it != this->eventContainers_.end())
+        this->eventStates_[name] = state;
+    }
+
+    /**
+        @brief Returns the event-state with the given name.
+    */
+    EventState* BaseObject::getEventState(const std::string& name) const
+    {
+        std::map<std::string, EventState*>::const_iterator it = this->eventStates_.find(name);
+        if (it != this->eventStates_.end())
             return ((*it).second);
         else
@@ -264,79 +297,165 @@
     }
 
-    void BaseObject::fireEvent()
-    {
-        this->fireEvent(true);
-        this->fireEvent(false);
-    }
-
-    void BaseObject::fireEvent(bool activate)
-    {
-        this->fireEvent(activate, this);
-    }
-
-    void BaseObject::fireEvent(bool activate, BaseObject* originator)
-    {
-        Event event(activate, originator);
-
-        for (std::map<BaseObject*, std::string>::iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); ++it)
-        {
-            event.sectionname_ = it->second;
-            it->first->processEvent(event);
-        }
-    }
-
+    /**
+        @brief Fires an event (without a state).
+    */
+    void BaseObject::fireEvent(const std::string& name)
+    {
+        this->fireEvent(true, name);
+        this->fireEvent(false, name);
+    }
+
+    /**
+        @brief Fires an event which activates or deactivates a state.
+    */
+    void BaseObject::fireEvent(bool activate, const std::string& name)
+    {
+        this->fireEvent(activate, this, name);
+    }
+
+    /**
+        @brief Fires an event which activates or deactivates a state with agiven originator (the object which triggered the event).
+    */
+    void BaseObject::fireEvent(bool activate, BaseObject* originator, const std::string& name)
+    {
+        Event event(activate, originator, name);
+
+        for (std::set<BaseObject*>::iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); ++it)
+        {
+            event.statename_ = (*it)->eventSources_[this];
+            (*it)->processEvent(event);
+        }
+    }
+
+    /**
+        @brief Fires an event, using the Event struct.
+    */
     void BaseObject::fireEvent(Event& event)
     {
-        for (std::map<BaseObject*, std::string>::iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); ++it)
-            it->first->processEvent(event);
-    }
-
+        for (std::set<BaseObject*>::iterator it = this->eventListeners_.begin(); it != this->eventListeners_.end(); ++it)
+            (*it)->processEvent(event);
+    }
+
+    /**
+        @brief Processing an event by calling the right main state.
+        @param event The event struct which contains the information about the event
+    */
     void BaseObject::processEvent(Event& event)
     {
-        ORXONOX_SET_EVENT(BaseObject, "activity", setActive, event);
-        ORXONOX_SET_EVENT(BaseObject, "visibility", setVisible, event);
-    }
-
-    void BaseObject::setMainStateName(const std::string& name)
-    {
-        if (this->mainStateName_ != name)
-        {
-            this->mainStateName_ = name;
-            if (this->functorSetMainState_)
-                delete this->functorSetMainState_;
-            if (this->functorGetMainState_)
-                delete this->functorGetMainState_;
-            this->changedMainState();
-            if (!this->functorSetMainState_)
-                COUT(2) << "Warning: \"" << name << "\" is not a valid MainState." << std::endl;
-        }
-    }
-
+        this->registerEventStates();
+        
+        std::map<std::string, EventState*>::const_iterator it = this->eventStates_.find(event.statename_);
+        if (it != this->eventStates_.end())
+            it->second->process(event, this);
+        else if (event.statename_ != "")
+            COUT(2) << "Warning: \"" << event.statename_ << "\" is not a valid state in object \"" << this->getName() << "\" of class " << this->getIdentifier()->getName() << "." << std::endl;
+        else
+            COUT(2) << "Warning: Event with invalid source sent to object \"" << this->getName() << "\" of class " << this->getIdentifier()->getName() << "." << std::endl;
+    }
+
+    /**
+        @brief Sets the main state of the object to a given boolean value.
+        
+        Note: The main state of an object can be set with the @ref setMainStateName function.
+        It's part of the eventsystem and used for event forwarding (when the target object can't specify a specific state,
+        the main state is used by default).
+    */
     void BaseObject::setMainState(bool state)
     {
-        if (this->functorSetMainState_)
-            (*this->functorSetMainState_)(state);
+        if (this->mainStateFunctor_)
+        {
+            if (this->mainStateFunctor_->getParamCount() == 0)
+            {
+                if (state)
+                    (*this->mainStateFunctor_)();
+            }
+            else
+            {
+                (*this->mainStateFunctor_)(state);
+            }
+        }
         else
             COUT(2) << "Warning: No MainState defined in object \"" << this->getName() << "\" (" << this->getIdentifier()->getName() << ")" << std::endl;
     }
 
-    bool BaseObject::getMainState() const
-    {
-        if (this->functorGetMainState_)
-        {
-            (*this->functorGetMainState_)();
-            return this->functorGetMainState_->getReturnvalue();
-        }
-        else
-        {
-            COUT(2) << "Warning: No MainState defined in object \"" << this->getName() << "\" (" << this->getIdentifier()->getName() << ")" << std::endl;
-            return false;
-        }
-    }
-
-    void BaseObject::changedMainState()
-    {
-        SetMainState(BaseObject, "activity",   setActive,  isActive);
-        SetMainState(BaseObject, "visibility", setVisible, isVisible);
+    /**
+        @brief This function gets called if the main state name of the object changes.
+    */
+    void BaseObject::changedMainStateName()
+    {
+        this->mainStateFunctor_ = 0;
+
+        if (this->mainStateName_ != "")
+        {
+            this->registerEventStates();
+            
+            std::map<std::string, EventState*>::const_iterator it = this->eventStates_.find(this->mainStateName_);
+            if (it != this->eventStates_.end() && it->second->getFunctor())
+            {
+                if (it->second->getFunctor()->getParamCount() <= 1)
+                    this->mainStateFunctor_ = it->second->getFunctor();
+                else
+                    COUT(2) << "Warning: Can't use \"" << this->mainStateName_ << "\" as MainState because it needs a second argument." << std::endl;
+            }
+            else
+                COUT(2) << "Warning: \"" << this->mainStateName_ << "\" is not a valid MainState." << std::endl;
+        }
+    }
+    
+    /**
+        @brief Calls XMLEventPort with an empty XML-element to register the event states if necessary.
+    */
+    void BaseObject::registerEventStates()
+    {
+        if (!this->bRegisteredEventStates_)
+        {
+            Element xmlelement;
+            this->XMLEventPort(xmlelement, XMLPort::NOP);
+        }
+    }
+    
+    /**
+        @brief Manually loads all event states, even if the class doesn't officially support them. This is needed by some classes like @ref EventDispatcher or @ref EventTarget.
+    */
+    void BaseObject::loadAllEventStates(Element& xmlelement, XMLPort::Mode mode, BaseObject* object, Identifier* identifier)
+    {
+        Element* events = xmlelement.FirstChildElement("events", false);
+        if (events)
+        {
+            // get the list of all states present
+            std::list<std::string> eventnames;
+            if (mode == XMLPort::LoadObject || mode == XMLPort::ExpandObject)
+            {
+                for (ticpp::Iterator<ticpp::Element> child = events->FirstChildElement(false); child != child.end(); child++)
+                    eventnames.push_back(child->Value());
+            }
+            else if (mode == XMLPort::SaveObject)
+            {
+            }
+
+            // iterate through all states and get the event sources
+            for (std::list<std::string>::iterator it = eventnames.begin(); it != eventnames.end(); ++it)
+            {
+                std::string statename = (*it);
+
+                // if the event state is already known, continue with the next state
+                orxonox::EventState* eventstate = object->getEventState(statename);
+                if (eventstate)
+                    continue;
+
+                XMLPortClassObjectContainer<BaseObject, BaseObject>* container = (XMLPortClassObjectContainer<BaseObject, BaseObject>*)(identifier->getXMLPortObjectContainer(statename));
+                if (!container)
+                {
+                    ExecutorMember<BaseObject>* setfunctor = createExecutor(createFunctor(&BaseObject::addEventSource), std::string( "BaseObject" ) + "::" + "addEventSource" + "(" + statename + ")");
+                    ExecutorMember<BaseObject>* getfunctor = createExecutor(createFunctor(&BaseObject::getEventSource), std::string( "BaseObject" ) + "::" + "getEventSource" + "(" + statename + ")");
+                    setfunctor->setDefaultValue(1, statename);
+                    getfunctor->setDefaultValue(1, statename);
+
+                    container = new XMLPortClassObjectContainer<BaseObject, BaseObject>(statename, identifier, setfunctor, getfunctor, false, true);
+                    identifier->addXMLPortObjectContainer(statename, container);
+                }
+                container->port(object, *events, mode);
+            }
+        }
     }
 }
Index: code/trunk/src/libraries/core/BaseObject.h
===================================================================
--- code/trunk/src/libraries/core/BaseObject.h	(revision 5781)
+++ code/trunk/src/libraries/core/BaseObject.h	(revision 5929)
@@ -37,12 +37,4 @@
 #define _BaseObject_H__
 
-#define SetMainState(classname, statename, setfunction, getfunction) \
-    if (this->getMainStateName() == statename) \
-    { \
-        this->functorSetMainState_ = createFunctor(&classname::setfunction)->setObject(this); \
-        this->functorGetMainState_ = createFunctor(&classname::getfunction)->setObject(this); \
-    }
-
-
 #include "CorePrereqs.h"
 
@@ -53,4 +45,5 @@
 #include "OrxonoxClass.h"
 #include "Super.h"
+#include "SmartPtr.h"
 
 namespace orxonox
@@ -68,4 +61,5 @@
             virtual ~BaseObject();
             virtual void XMLPort(Element& xmlelement, XMLPort::Mode mode);
+            virtual void XMLEventPort(Element& xmlelement, XMLPort::Mode mode);
 
             /** @brief Returns if the object was initialized (passed the object registration). @return True was the object is initialized */
@@ -110,9 +104,18 @@
 
             void setMainState(bool state);
-            bool getMainState() const;
-
-            void setMainStateName(const std::string& name);
+
+            /** @brief Sets the name of the main state (used for event reactions). */
+            void setMainStateName(const std::string& name)
+            {
+                if (this->mainStateName_ != name)
+                {
+                    this->mainStateName_ = name;
+                    this->changedMainStateName();
+                }
+            }
+            /** @brief Returns the name of the main state. */
             inline const std::string& getMainStateName() const { return this->mainStateName_; }
-            virtual void changedMainState();
+            /** @brief This function gets called if the main state name of the object changes. */
+            virtual void changedMainStateName();
 
             /** @brief Sets a pointer to the xml file that loaded this object. @param file The pointer to the XMLFile */
@@ -134,8 +137,9 @@
             inline BaseObject* getCreator() const { return this->creator_; }
 
-            inline void setScene(Scene* scene) { this->scene_ = scene; }
-            inline Scene* getScene() const { return this->scene_; }
-
-            inline void setGametype(Gametype* gametype)
+            inline void setScene(const SmartPtr<Scene>& scene, uint32_t sceneID) { this->scene_ = scene; this->sceneID_=sceneID; }
+            inline const SmartPtr<Scene>& getScene() const { return this->scene_; }
+            inline virtual uint32_t getSceneID() const { return this->sceneID_; }
+
+            inline void setGametype(const SmartPtr<Gametype>& gametype)
             {
                 if (gametype != this->gametype_)
@@ -146,26 +150,21 @@
                 }
             }
-            inline Gametype* getGametype() const { return this->gametype_; }
+            inline const SmartPtr<Gametype>& getGametype() const { return this->gametype_; }
             inline Gametype* getOldGametype() const { return this->oldGametype_; }
             virtual void changedGametype() {}
 
-            void fireEvent();
-            void fireEvent(bool activate);
-            void fireEvent(bool activate, BaseObject* originator);
+            void addEventSource(BaseObject* source, const std::string& state);
+            void removeEventSource(BaseObject* source);
+            BaseObject* getEventSource(unsigned int index, const std::string& state) const;
+            
+            void addEventListener(BaseObject* listener);
+            BaseObject* getEventListener(unsigned int index) const;
+
+            void fireEvent(const std::string& name = "");
+            void fireEvent(bool activate, const std::string& name = "");
+            void fireEvent(bool activate, BaseObject* originator, const std::string& name = "");
             void fireEvent(Event& event);
 
             virtual void processEvent(Event& event);
-
-            inline void registerEventListener(BaseObject* object, const std::string& sectionname)
-                { this->eventListeners_[object] = sectionname; }
-            inline void unregisterEventListener(BaseObject* object)
-                { this->eventListeners_.erase(object); }
-
-            void addEvent(BaseObject* event, const std::string& sectionname);
-            void removeEvent(BaseObject* event);
-            BaseObject* getEvent(unsigned int index) const;
-
-            void addEventContainer(const std::string& sectionname, EventContainer* container);
-            EventContainer* getEventContainer(const std::string& sectionname) const;
 
             /** @brief Sets the indentation of the debug output in the Loader. @param indentation The indentation */
@@ -173,6 +172,11 @@
             /** @brief Returns the indentation of the debug output in the Loader. @return The indentation */
             inline const std::string& getLoaderIndentation() const { return this->loaderIndentation_; }
+            
+            static void loadAllEventStates(Element& xmlelement, XMLPort::Mode mode, BaseObject* object, Identifier* identifier);
 
         protected:
+            void addEventState(const std::string& name, EventState* container);
+            EventState* getEventState(const std::string& name) const;
+
             std::string name_;                                 //!< The name of the object
             std::string oldName_;                              //!< The old name of the object
@@ -180,10 +184,17 @@
             mbool       bVisible_;                             //!< True = the object is visible
             std::string mainStateName_;
-            Functor*    functorSetMainState_;
-            Functor*    functorGetMainState_;
+            Functor*    mainStateFunctor_;
 
         private:
+            /** @brief Adds an object which listens to the events of this object. */
+            inline void registerEventListener(BaseObject* object)
+                { this->eventListeners_.insert(object); }
+            /** @brief Removes an event listener from this object. */
+            inline void unregisterEventListener(BaseObject* object)
+                { this->eventListeners_.erase(object); }
+
             void setXMLName(const std::string& name);
             Template* getTemplate(unsigned int index) const;
+            void registerEventStates();
 
             bool                   bInitialized_;              //!< True if the object was initialized (passed the object registration)
@@ -194,11 +205,15 @@
             Namespace*             namespace_;
             BaseObject*            creator_;
-            Scene*                 scene_;
-            Gametype*              gametype_;
+            SmartPtr<Scene>        scene_;
+            uint32_t               sceneID_;
+            SmartPtr<Gametype>     gametype_;
             Gametype*              oldGametype_;
             std::set<Template*>    templates_;
-            std::map<BaseObject*,  std::string> eventListeners_;
-            std::list<BaseObject*> events_;
-            std::map<std::string, EventContainer*> eventContainers_;
+            
+            std::map<BaseObject*, std::string>  eventSources_;           //!< List of objects which send events to this object, mapped to the state which they affect
+            std::set<BaseObject*>               eventListeners_;         //!< List of objects which listen to the events of this object
+            std::set<BaseObject*>               eventListenersXML_;      //!< List of objects which listen to the events of this object through the "eventlisteners" subsection in XML
+            std::map<std::string, EventState*>  eventStates_;            //!< Maps the name of the event states to their helper objects
+            bool                                bRegisteredEventStates_; //!< Becomes true after the object registered its event states (with XMLEventPort)
     };
 
@@ -206,8 +221,7 @@
     SUPER_FUNCTION(2, BaseObject, changedActivity, false);
     SUPER_FUNCTION(3, BaseObject, changedVisibility, false);
-    SUPER_FUNCTION(4, BaseObject, processEvent, false);
-    SUPER_FUNCTION(6, BaseObject, changedMainState, false);
-    SUPER_FUNCTION(9, BaseObject, changedName, false);
-    SUPER_FUNCTION(10, BaseObject, changedGametype, false);
+    SUPER_FUNCTION(4, BaseObject, XMLEventPort, false);
+    SUPER_FUNCTION(8, BaseObject, changedName, false);
+    SUPER_FUNCTION(9, BaseObject, changedGametype, false);
 }
 
Index: code/trunk/src/libraries/core/CMakeLists.txt
===================================================================
--- code/trunk/src/libraries/core/CMakeLists.txt	(revision 5781)
+++ code/trunk/src/libraries/core/CMakeLists.txt	(revision 5929)
@@ -19,6 +19,4 @@
 
 SET_SOURCE_FILES(CORE_SRC_FILES
-  Clock.cc
-  ConfigFileManager.cc
   ConfigValueContainer.cc
   Core.cc
@@ -33,12 +31,11 @@
   Language.cc
   LuaState.cc
-  MemoryArchive.cc
   ObjectListBase.cc
   OrxonoxClass.cc
   Resource.cc
+  ScopedSingletonManager.cc
   WindowEventListener.cc
 
   # command
-  ArgumentCompletionFunctions.cc
   CommandEvaluation.cc
   CommandExecutor.cc
@@ -49,5 +46,4 @@
 
   # hierarchy
-  Factory.cc
   Identifier.cc
   MetaObjectList.cc
@@ -67,10 +63,20 @@
   Shell.cc
   TclBind.cc
+
+COMPILATION_BEGIN FilesystemCompilation.cc
+  ArgumentCompletionFunctions.cc
+  ConfigFileManager.cc
+  MemoryArchive.cc
+  PathConfig.cc
+COMPILATION_END
+
+  # multithreading
+  ThreadPool.cc
+COMPILATION_BEGIN ThreadCompilation.cc
   TclThreadManager.cc
-  
-  # multithreading
   Thread.cc
-  ThreadPool.cc
+COMPILATION_END
 )
+
 ADD_SUBDIRECTORY(input)
 
Index: code/trunk/src/libraries/core/ClassFactory.h
===================================================================
--- code/trunk/src/libraries/core/ClassFactory.h	(revision 5781)
+++ code/trunk/src/libraries/core/ClassFactory.h	(revision 5929)
@@ -42,9 +42,19 @@
 
 #include "util/Debug.h"
-#include "Factory.h"
 #include "Identifier.h"
 
 namespace orxonox
 {
+    // ###########################
+    // ###       Factory       ###
+    // ###########################
+    //! Base-class of ClassFactory.
+    class _CoreExport Factory
+    {
+        public:
+            virtual ~Factory() {};
+            virtual BaseObject* fabricate(BaseObject* creator) = 0;
+    };
+
     // ###############################
     // ###      ClassFactory       ###
@@ -52,54 +62,28 @@
     //! The ClassFactory is able to create new objects of a specific class.
     template <class T>
-    class ClassFactory : public BaseFactory
+    class ClassFactory : public Factory
     {
         public:
-            static bool create(const std::string& name, bool bLoadable = true);
-            BaseObject* fabricate(BaseObject* creator);
+            /**
+                @brief Constructor: Adds the ClassFactory to the Identifier of the same type.
+                @param name The name of the class
+                @param bLoadable True if the class can be loaded through XML
+            */
+            ClassFactory(const std::string& name, bool bLoadable = true)
+            {
+                COUT(4) << "*** ClassFactory: Create entry for " << name << " in Factory." << std::endl;
+                ClassIdentifier<T>::getIdentifier(name)->addFactory(this);
+                ClassIdentifier<T>::getIdentifier()->setLoadable(bLoadable);
+            }
 
-        private:
-            ClassFactory() {}                               // Don't create
-            ClassFactory(const ClassFactory& factory) {}    // Don't copy
-            virtual ~ClassFactory() {}                      // Don't delete
-
-            static T* createNewObject(BaseObject* creator);
+            /**
+                @brief Creates and returns a new object of class T.
+                @return The new object
+            */
+            inline BaseObject* fabricate(BaseObject* creator)
+            {
+                return static_cast<BaseObject*>(new T(creator));
+            }
     };
-
-    /**
-        @brief Adds the ClassFactory to the Identifier of the same type and the Identifier to the Factory.
-        @param name The name of the class
-        @param bLoadable True if the class can be loaded through XML
-        @return Always true (this is needed because the compiler only allows assignments before main())
-    */
-    template <class T>
-    bool ClassFactory<T>::create(const std::string& name, bool bLoadable)
-    {
-        COUT(4) << "*** ClassFactory: Create entry for " << name << " in Factory." << std::endl;
-        ClassIdentifier<T>::getIdentifier(name)->addFactory(new ClassFactory<T>);
-        ClassIdentifier<T>::getIdentifier()->setLoadable(bLoadable);
-        Factory::add(name, ClassIdentifier<T>::getIdentifier());
-
-        return true;
-    }
-
-    /**
-        @brief Creates and returns a new object of class T.
-        @return The new object
-    */
-    template <class T>
-    inline BaseObject* ClassFactory<T>::fabricate(BaseObject* creator)
-    {
-        return ClassFactory<T>::createNewObject(creator);
-    }
-
-    /**
-        @brief Creates and returns a new object of class T; this is a wrapper for the new operator.
-        @return The new object
-    */
-    template <class T>
-    inline T* ClassFactory<T>::createNewObject(BaseObject* creator)
-    {
-        return new T(creator);
-    }
 }
 
Index: code/trunk/src/libraries/core/ClassTreeMask.cc
===================================================================
--- code/trunk/src/libraries/core/ClassTreeMask.cc	(revision 5781)
+++ code/trunk/src/libraries/core/ClassTreeMask.cc	(revision 5929)
@@ -488,4 +488,5 @@
 
                 // Remove the redundant subnode from the current node
+                delete (*it);
                 node->subnodes_.erase(it++);
             }
Index: code/trunk/src/libraries/core/ClassTreeMask.h
===================================================================
--- code/trunk/src/libraries/core/ClassTreeMask.h	(revision 5781)
+++ code/trunk/src/libraries/core/ClassTreeMask.h	(revision 5929)
@@ -265,7 +265,7 @@
 
             /** @brief Returns true if the ClassTreeMaskObjectIterator points at the given object. @param pointer The pointer of the object */
-            inline bool operator==(BaseObject* pointer) const { return ((*this->objectIterator_) == pointer); }
+            inline bool operator==(BaseObject* pointer) const { return (this->objectIterator_ && (*this->objectIterator_) == pointer) || (!this->objectIterator_ && pointer == 0); }
             /** @brief Returns true if the ClassTreeMaskObjectIterator doesn't point at the given object. @param pointer The pointer of the object */
-            inline bool operator!=(BaseObject* pointer) const { return ((*this->objectIterator_) != pointer); }
+            inline bool operator!=(BaseObject* pointer) const { return (this->objectIterator_ && (*this->objectIterator_) != pointer) || (!this->objectIterator_ && pointer != 0); }
             /** @brief Returns true if the ClassTreeMaskObjectIterator hasn't already reached the end. */
             inline operator bool() const { return (this->objectIterator_); }
Index: code/trunk/src/libraries/core/Clock.cc
===================================================================
--- code/trunk/src/libraries/core/Clock.cc	(revision 5781)
+++ 	(revision )
@@ -1,78 +1,0 @@
-/*
- *   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
-*/
-
-#include "Clock.h"
-#include <OgreTimer.h>
-
-namespace orxonox
-{
-    Clock::Clock()
-        : timer_(new Ogre::Timer())
-        , storedTime_(0)
-        , tickTime_(0)
-        , tickDt_(0)
-        , tickDtFloat_(0.0f)
-        , lastTimersTime_(0)
-    {
-    }
-
-    Clock::~Clock()
-    {
-        delete timer_;
-    }
-    
-    void Clock::capture()
-    {
-        unsigned long timersTime = timer_->getMicroseconds();
-        tickTime_ = storedTime_ + timersTime;
-        tickDt_ = timersTime - lastTimersTime_;
-        tickDtFloat_ = static_cast<float>(tickDt_) / 1000000.0f;
-
-        if (timersTime > 0xFFFFFFFF/4)
-        {
-            // Ogre timer will overflow at 2^32 microseconds if unsigned long is 32 bit
-            storedTime_ += timersTime;
-            lastTimersTime_ = 0;
-            timer_->reset();
-        }
-        else
-        {
-            lastTimersTime_ = timersTime;
-        }
-    }
-
-    unsigned long long Clock::getRealMicroseconds() const
-    {
-        return this->timer_->getMicroseconds() + this->storedTime_;
-    }
-}
Index: code/trunk/src/libraries/core/Clock.h
===================================================================
--- code/trunk/src/libraries/core/Clock.h	(revision 5781)
+++ 	(revision )
@@ -1,67 +1,0 @@
-/*
- *   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:
- *      ...
- *
- */
-
-#ifndef _Clock_H__
-#define _Clock_H__
-
-#include "CorePrereqs.h"
-#include "util/OgreForwardRefs.h"
-
-namespace orxonox
-{
-    class _CoreExport Clock
-    {
-    public:
-        Clock();
-        ~Clock();
-
-        void capture();
-
-        unsigned long long getMicroseconds()   const { return tickTime_; }
-        unsigned long long getMilliseconds()   const { return tickTime_ / 1000; }
-        unsigned long      getSeconds()        const { return static_cast<long> (tickTime_ / 1000000); }
-        float              getSecondsPrecise() const { return static_cast<float>(tickTime_ / 1000000.0f); }
-
-        float              getDeltaTime()      const { return tickDtFloat_; }
-        long               getDeltaTimeMicroseconds() const { return tickDt_; }
-
-        unsigned long long getRealMicroseconds() const;
-
-    private:
-        Clock(const Clock& instance);
-
-        Ogre::Timer*       timer_;
-        unsigned long long storedTime_;
-        unsigned long long tickTime_;
-        long               tickDt_;
-        float              tickDtFloat_;
-        unsigned long      lastTimersTime_;
-    };
-}
-
-#endif /* _Clock_H__ */
Index: code/trunk/src/libraries/core/CommandExecutor.cc
===================================================================
--- code/trunk/src/libraries/core/CommandExecutor.cc	(revision 5781)
+++ code/trunk/src/libraries/core/CommandExecutor.cc	(revision 5929)
@@ -468,5 +468,5 @@
         CommandExecutor::getEvaluation().listOfPossibleIdentifiers_.clear();
         std::string lowercase = getLowercase(fragment);
-        for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getLowercaseIdentifierMapBegin(); it != Identifier::getLowercaseIdentifierMapEnd(); ++it)
+        for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getLowercaseStringIdentifierMapBegin(); it != Identifier::getLowercaseStringIdentifierMapEnd(); ++it)
             if ((*it).second->hasConsoleCommands())
                 if ((*it).first.find(lowercase) == 0 || fragment == "")
@@ -516,6 +516,6 @@
     {
         std::string lowercase = getLowercase(name);
-        std::map<std::string, Identifier*>::const_iterator it = Identifier::getLowercaseIdentifierMap().find(lowercase);
-        if ((it != Identifier::getLowercaseIdentifierMapEnd()) && (*it).second->hasConsoleCommands())
+        std::map<std::string, Identifier*>::const_iterator it = Identifier::getLowercaseStringIdentifierMap().find(lowercase);
+        if ((it != Identifier::getLowercaseStringIdentifierMapEnd()) && (*it).second->hasConsoleCommands())
             return (*it).second;
 
Index: code/trunk/src/libraries/core/CommandLine.cc
===================================================================
--- code/trunk/src/libraries/core/CommandLine.cc	(revision 5781)
+++ code/trunk/src/libraries/core/CommandLine.cc	(revision 5929)
@@ -31,5 +31,4 @@
 #include <algorithm>
 #include <sstream>
-#include <boost/filesystem.hpp>
 
 #include "util/Convert.h"
@@ -38,5 +37,5 @@
 #include "util/StringUtils.h"
 #include "util/SubString.h"
-#include "Core.h"
+#include "PathConfig.h"
 
 namespace orxonox
@@ -285,4 +284,5 @@
         }
 
+        infoStr << std::endl;
         infoStr << "Usage: orxonox [options]" << std::endl;
         infoStr << "Available options:" << std::endl;
@@ -348,10 +348,9 @@
     {
         std::string filename = CommandLine::getValue("optionsFile").getString();
-        boost::filesystem::path filepath(Core::getConfigPath() / filename);
 
         // look for additional arguments in given file or start.ini as default
         // They will not overwrite the arguments given directly
         std::ifstream file;
-        file.open(filepath.string().c_str());
+        file.open((PathConfig::getConfigPathString() + filename).c_str());
         std::vector<std::string> args;
         if (file)
Index: code/trunk/src/libraries/core/ConfigFileManager.cc
===================================================================
--- code/trunk/src/libraries/core/ConfigFileManager.cc	(revision 5781)
+++ code/trunk/src/libraries/core/ConfigFileManager.cc	(revision 5929)
@@ -36,5 +36,5 @@
 #include "ConsoleCommand.h"
 #include "ConfigValueContainer.h"
-#include "Core.h"
+#include "PathConfig.h"
 
 namespace orxonox
@@ -48,6 +48,6 @@
     bool config(const std::string& classname, const std::string& varname, const std::string& value)
     {
-        std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseIdentifierMap().find(getLowercase(classname));
-        if (identifier != Identifier::getLowercaseIdentifierMapEnd())
+        std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseStringIdentifierMap().find(getLowercase(classname));
+        if (identifier != Identifier::getLowercaseStringIdentifierMapEnd())
         {
             std::map<std::string, ConfigValueContainer*>::const_iterator variable = (*identifier).second->getLowercaseConfigValueMap().find(getLowercase(varname));
@@ -60,6 +60,6 @@
     bool tconfig(const std::string& classname, const std::string& varname, const std::string& value)
     {
-        std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseIdentifierMap().find(getLowercase(classname));
-        if (identifier != Identifier::getLowercaseIdentifierMapEnd())
+        std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseStringIdentifierMap().find(getLowercase(classname));
+        if (identifier != Identifier::getLowercaseStringIdentifierMapEnd())
         {
             std::map<std::string, ConfigValueContainer*>::const_iterator variable = (*identifier).second->getLowercaseConfigValueMap().find(getLowercase(varname));
@@ -222,9 +222,9 @@
 
         // Get default file if necessary and available
-        boost::filesystem::path filepath(Core::getConfigPath() / this->filename_);
+        boost::filesystem::path filepath(PathConfig::getConfigPath() / this->filename_);
         if (!boost::filesystem::exists(filepath))
         {
             // Try to get default one from the data folder
-            boost::filesystem::path defaultFilepath(Core::getDataPath() / "defaultConfig" / this->filename_);
+            boost::filesystem::path defaultFilepath(PathConfig::getDataPath() / "defaultConfig" / this->filename_);
             if (boost::filesystem::exists(defaultFilepath))
             {
@@ -336,5 +336,5 @@
     {
         std::ofstream file;
-        file.open((Core::getConfigPathString() + filename_).c_str(), std::fstream::out);
+        file.open((PathConfig::getConfigPathString() + filename_).c_str(), std::fstream::out);
         file.setf(std::ios::fixed, std::ios::floatfield);
         file.precision(6);
@@ -376,6 +376,6 @@
         for (std::list<ConfigFileSection*>::iterator it1 = this->sections_.begin(); it1 != this->sections_.end(); )
         {
-            std::map<std::string, Identifier*>::const_iterator it2 = Identifier::getIdentifierMap().find((*it1)->getName());
-            if (it2 != Identifier::getIdentifierMapEnd() && (*it2).second->hasConfigValues())
+            std::map<std::string, Identifier*>::const_iterator it2 = Identifier::getStringIdentifierMap().find((*it1)->getName());
+            if (it2 != Identifier::getStringIdentifierMapEnd() && (*it2).second->hasConfigValues())
             {
                 // The section exists, delete comment
@@ -455,5 +455,5 @@
         if (this->type_ == ConfigFileType::Settings)
         {
-            for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getIdentifierMapBegin(); it != Identifier::getIdentifierMapEnd(); ++it)
+            for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getStringIdentifierMapBegin(); it != Identifier::getStringIdentifierMapEnd(); ++it)
             {
                 if (it->second->hasConfigValues())
Index: code/trunk/src/libraries/core/Core.cc
===================================================================
--- code/trunk/src/libraries/core/Core.cc	(revision 5781)
+++ code/trunk/src/libraries/core/Core.cc	(revision 5929)
@@ -37,9 +37,5 @@
 
 #include <cassert>
-#include <fstream>
-#include <cstdlib>
-#include <cstdio>
-#include <boost/version.hpp>
-#include <boost/filesystem.hpp>
+#include <vector>
 
 #ifdef ORXONOX_PLATFORM_WINDOWS
@@ -50,17 +46,11 @@
 #  undef min
 #  undef max
-#elif defined(ORXONOX_PLATFORM_APPLE)
-#  include <sys/param.h>
-#  include <mach-o/dyld.h>
-#else /* Linux */
-#  include <sys/types.h>
-#  include <unistd.h>
 #endif
 
-#include "SpecialConfig.h"
+#include "util/Clock.h"
 #include "util/Debug.h"
 #include "util/Exception.h"
 #include "util/SignalHandler.h"
-#include "Clock.h"
+#include "PathConfig.h"
 #include "CommandExecutor.h"
 #include "CommandLine.h"
@@ -69,5 +59,4 @@
 #include "CoreIncludes.h"
 #include "DynLibManager.h"
-#include "Factory.h"
 #include "GameMode.h"
 #include "GraphicsManager.h"
@@ -76,4 +65,5 @@
 #include "Language.h"
 #include "LuaState.h"
+#include "ScopedSingletonManager.h"
 #include "Shell.h"
 #include "TclBind.h"
@@ -81,11 +71,4 @@
 #include "input/InputManager.h"
 
-// Boost 1.36 has some issues with deprecated functions that have been omitted
-#if (BOOST_VERSION == 103600)
-#  define BOOST_LEAF_FUNCTION filename
-#else
-#  define BOOST_LEAF_FUNCTION leaf
-#endif
-
 namespace orxonox
 {
@@ -93,6 +76,4 @@
     Core* Core::singletonPtr_s  = 0;
 
-    SetCommandLineArgument(externalDataPath, "").information("Path to the external data files");
-    SetCommandLineOnlyArgument(writingPathSuffix, "").information("Additional subfolder for config and log files");
     SetCommandLineArgument(settingsFile, "orxonox.ini").information("THE configuration file");
 #ifdef ORXONOX_PLATFORM_WINDOWS
@@ -117,12 +98,4 @@
             RegisterRootObject(CoreConfiguration);
             this->setConfigValues();
-
-            // External data directory only exists for dev runs
-            if (Core::isDevelopmentRun())
-            {
-                // Possible data path override by the command line
-                if (!CommandLine::getArgument("externalDataPath")->hasDefaultValue())
-                    tsetExternalDataPath(CommandLine::getValue("externalDataPath"));
-            }
         }
 
@@ -194,15 +167,4 @@
         }
 
-        /**
-        @brief
-            Temporary sets the external data path
-        @param path
-            The new data path
-        */
-        void tsetExternalDataPath(const std::string& path)
-        {
-            externalDataPath_ = boost::filesystem::path(path);
-        }
-
         void initializeRandomNumberGenerator()
         {
@@ -222,13 +184,4 @@
         std::string language_;                          //!< The language
         bool bInitializeRandomNumberGenerator_;         //!< If true, srand(time(0)) is called
-
-        //! Path to the parent directory of the ones above if program was installed with relativ pahts
-        boost::filesystem::path rootPath_;
-        boost::filesystem::path executablePath_;        //!< Path to the executable
-        boost::filesystem::path modulePath_;            //!< Path to the modules
-        boost::filesystem::path dataPath_;              //!< Path to the data file folder
-        boost::filesystem::path externalDataPath_;      //!< Path to the external data file folder
-        boost::filesystem::path configPath_;            //!< Path to the config file folder
-        boost::filesystem::path logPath_;               //!< Path to the log file folder
     };
 
@@ -240,9 +193,8 @@
         , consoleCommandDestroyer_(CommandExecutor::destroyExternalCommands)
         , configuration_(new CoreConfiguration()) // Don't yet create config values!
-        , bDevRun_(false)
         , bGraphicsLoaded_(false)
     {
         // Set the hard coded fixed paths
-        this->setFixedPaths();
+        this->pathConfig_.reset(new PathConfig());
 
         // Create a new dynamic library manager
@@ -250,51 +202,15 @@
 
         // Load modules
-        try
-        {
-            // We search for helper files with the following extension
-            std::string moduleextension = specialConfig::moduleExtension;
-            size_t moduleextensionlength = moduleextension.size();
-
-            // Search in the directory of our executable
-            boost::filesystem::path searchpath = this->configuration_->modulePath_;
-
-            // Add that path to the PATH variable in case a module depends on another one
-            std::string pathVariable = getenv("PATH");
-            putenv(const_cast<char*>(("PATH=" + pathVariable + ";" + configuration_->modulePath_.string()).c_str()));
-
-            boost::filesystem::directory_iterator file(searchpath);
-            boost::filesystem::directory_iterator end;
-
-            // Iterate through all files
-            while (file != end)
+        const std::vector<std::string>& modulePaths = this->pathConfig_->getModulePaths();
+        for (std::vector<std::string>::const_iterator it = modulePaths.begin(); it != modulePaths.end(); ++it)
+        {
+            try
             {
-                std::string filename = file->BOOST_LEAF_FUNCTION();
-
-                // Check if the file ends with the exension in question
-                if (filename.size() > moduleextensionlength)
-                {
-                    if (filename.substr(filename.size() - moduleextensionlength) == moduleextension)
-                    {
-                        // We've found a helper file - now load the library with the same name
-                        std::string library = filename.substr(0, filename.size() - moduleextensionlength);
-                        boost::filesystem::path librarypath = searchpath / library;
-
-                        try
-                        {
-                            DynLibManager::getInstance().load(librarypath.string());
-                        }
-                        catch (...)
-                        {
-                            COUT(1) << "Couldn't load module \"" << librarypath.string() << "\": " << Exception::handleMessage() << std::endl;
-                        }
-                    }
-                }
-
-                ++file;
+                this->dynLibManager_->load(*it);
             }
-        }
-        catch (...)
-        {
-            COUT(1) << "An error occurred while loading modules: " << Exception::handleMessage() << std::endl;
+            catch (...)
+            {
+                COUT(1) << "Couldn't load module \"" << *it << "\": " << Exception::handleMessage() << std::endl;
+            }
         }
 
@@ -303,13 +219,13 @@
 
         // Set configurable paths like log, config and media
-        this->setConfigurablePaths();
+        this->pathConfig_->setConfigurablePaths();
 
         // create a signal handler (only active for linux)
         // This call is placed as soon as possible, but after the directories are set
         this->signalHandler_.reset(new SignalHandler());
-        this->signalHandler_->doCatch(configuration_->executablePath_.string(), Core::getLogPathString() + "orxonox_crash.log");
+        this->signalHandler_->doCatch(PathConfig::getExecutablePathString(), PathConfig::getLogPathString() + "orxonox_crash.log");
 
         // Set the correct log path. Before this call, /tmp (Unix) or %TEMP% was used
-        OutputHandler::getOutStream().setLogPath(Core::getLogPathString());
+        OutputHandler::getOutStream().setLogPath(PathConfig::getLogPathString());
 
         // Parse additional options file now that we know its path
@@ -334,5 +250,5 @@
 
         // creates the class hierarchy for all classes with factories
-        Factory::createClassHierarchy();
+        Identifier::createClassHierarchy();
 
         // Do this soon after the ConfigFileManager has been created to open up the
@@ -344,9 +260,12 @@
 
         // initialise Tcl
-        this->tclBind_.reset(new TclBind(Core::getDataPathString()));
+        this->tclBind_.reset(new TclBind(PathConfig::getDataPathString()));
         this->tclThreadManager_.reset(new TclThreadManager(tclBind_->getTclInterpreter()));
 
         // create a shell
         this->shell_.reset(new Shell());
+
+        // Create singletons that always exist (in other libraries)
+        this->rootScope_.reset(new Scope<ScopeID::Root>());
     }
 
@@ -370,17 +289,25 @@
         inputManager_.reset(new InputManager());
 
-        // load the CEGUI interface
+        // Load the CEGUI interface
         guiManager_.reset(new GUIManager(graphicsManager_->getRenderWindow(),
             inputManager_->getMousePosition(), graphicsManager_->isFullScreen()));
 
+        bGraphicsLoaded_ = true;
+        GameMode::bShowsGraphics_s = true;
+
+        // Load some sort of a debug overlay (only denoted by its name, "debug.oxo")
+        graphicsManager_->loadDebugOverlay();
+
+        // Create singletons associated with graphics (in other libraries)
+        graphicsScope_.reset(new Scope<ScopeID::Graphics>());
+
         unloader.Dismiss();
-
-        bGraphicsLoaded_ = true;
     }
 
     void Core::unloadGraphics()
     {
-        this->guiManager_.reset();;
-        this->inputManager_.reset();;
+        this->graphicsScope_.reset();
+        this->guiManager_.reset();
+        this->inputManager_.reset();
         this->graphicsManager_.reset();
 
@@ -397,4 +324,5 @@
 
         bGraphicsLoaded_ = false;
+        GameMode::bShowsGraphics_s = false;
     }
 
@@ -457,54 +385,4 @@
     }
 
-    /*static*/ void Core::tsetExternalDataPath(const std::string& path)
-    {
-        getInstance().configuration_->tsetExternalDataPath(path);
-    }
-
-    /*static*/ const boost::filesystem::path& Core::getDataPath()
-    {
-        return getInstance().configuration_->dataPath_;
-    }
-    /*static*/ std::string Core::getDataPathString()
-    {
-        return getInstance().configuration_->dataPath_.string() + '/';
-    }
-
-    /*static*/ const boost::filesystem::path& Core::getExternalDataPath()
-    {
-        return getInstance().configuration_->externalDataPath_;
-    }
-    /*static*/ std::string Core::getExternalDataPathString()
-    {
-        return getInstance().configuration_->externalDataPath_.string() + '/';
-    }
-
-    /*static*/ const boost::filesystem::path& Core::getConfigPath()
-    {
-        return getInstance().configuration_->configPath_;
-    }
-    /*static*/ std::string Core::getConfigPathString()
-    {
-        return getInstance().configuration_->configPath_.string() + '/';
-    }
-
-    /*static*/ const boost::filesystem::path& Core::getLogPath()
-    {
-        return getInstance().configuration_->logPath_;
-    }
-    /*static*/ std::string Core::getLogPathString()
-    {
-        return getInstance().configuration_->logPath_.string() + '/';
-    }
-
-    /*static*/ const boost::filesystem::path& Core::getRootPath()
-    {
-        return getInstance().configuration_->rootPath_;
-    }
-    /*static*/ std::string Core::getRootPathString()
-    {
-        return getInstance().configuration_->rootPath_.string() + '/';
-    }
-
     /**
     @note
@@ -553,176 +431,8 @@
     }
 
-    /**
-    @brief
-        Retrievs the executable path and sets all hard coded fixed path (currently only the module path)
-        Also checks for "orxonox_dev_build.keep_me" in the executable diretory.
-        If found it means that this is not an installed run, hence we
-        don't write the logs and config files to ~/.orxonox
-    @throw
-        GeneralException
-    */
-    void Core::setFixedPaths()
-    {
-        //////////////////////////
-        // FIND EXECUTABLE PATH //
-        //////////////////////////
-
-#ifdef ORXONOX_PLATFORM_WINDOWS
-        // get executable module
-        TCHAR buffer[1024];
-        if (GetModuleFileName(NULL, buffer, 1024) == 0)
-            ThrowException(General, "Could not retrieve executable path.");
-
-#elif defined(ORXONOX_PLATFORM_APPLE)
-        char buffer[1024];
-        unsigned long path_len = 1023;
-        if (_NSGetExecutablePath(buffer, &path_len))
-            ThrowException(General, "Could not retrieve executable path.");
-
-#else /* Linux */
-        /* written by Nicolai Haehnle <prefect_@gmx.net> */
-
-        /* Get our PID and build the name of the link in /proc */
-        char linkname[64]; /* /proc/<pid>/exe */
-        if (snprintf(linkname, sizeof(linkname), "/proc/%i/exe", getpid()) < 0)
-        {
-            /* This should only happen on large word systems. I'm not sure
-               what the proper response is here.
-               Since it really is an assert-like condition, aborting the
-               program seems to be in order. */
-            assert(false);
-        }
-
-        /* Now read the symbolic link */
-        char buffer[1024];
-        int ret;
-        ret = readlink(linkname, buffer, 1024);
-        /* In case of an error, leave the handling up to the caller */
-        if (ret == -1)
-            ThrowException(General, "Could not retrieve executable path.");
-
-        /* Ensure proper NUL termination */
-        buffer[ret] = 0;
-#endif
-
-        configuration_->executablePath_ = boost::filesystem::path(buffer);
-#ifndef ORXONOX_PLATFORM_APPLE
-        configuration_->executablePath_ = configuration_->executablePath_.branch_path(); // remove executable name
-#endif
-
-        /////////////////////
-        // SET MODULE PATH //
-        /////////////////////
-
-        if (boost::filesystem::exists(configuration_->executablePath_ / "orxonox_dev_build.keep_me"))
-        {
-            COUT(1) << "Running from the build tree." << std::endl;
-            Core::bDevRun_ = true;
-            configuration_->modulePath_ = specialConfig::moduleDevDirectory;
-        }
-        else
-        {
-
-#ifdef INSTALL_COPYABLE // --> relative paths
-
-            // Also set the root path
-            boost::filesystem::path relativeExecutablePath(specialConfig::defaultRuntimePath);
-            configuration_->rootPath_ = configuration_->executablePath_;
-            while (!boost::filesystem::equivalent(configuration_->rootPath_ / relativeExecutablePath, configuration_->executablePath_)
-                   && !configuration_->rootPath_.empty())
-                configuration_->rootPath_ = configuration_->rootPath_.branch_path();
-            if (configuration_->rootPath_.empty())
-                ThrowException(General, "Could not derive a root directory. Might the binary installation directory contain '..' when taken relative to the installation prefix path?");
-
-            // Module path is fixed as well
-            configuration_->modulePath_ = configuration_->rootPath_ / specialConfig::defaultModulePath;
-
-#else
-
-            // There is no root path, so don't set it at all
-            // Module path is fixed as well
-            configuration_->modulePath_ = specialConfig::moduleInstallDirectory;
-
-#endif
-        }
-    }
-
-    /**
-    @brief
-        Sets config, log and media path and creates folders if necessary.
-    @throws
-        GeneralException
-    */
-    void Core::setConfigurablePaths()
-    {
-        if (Core::isDevelopmentRun())
-        {
-            configuration_->dataPath_  = specialConfig::dataDevDirectory;
-            configuration_->externalDataPath_ = specialConfig::externalDataDevDirectory;
-            configuration_->configPath_ = specialConfig::configDevDirectory;
-            configuration_->logPath_    = specialConfig::logDevDirectory;
-        }
-        else
-        {
-
-#ifdef INSTALL_COPYABLE // --> relative paths
-
-            // Using paths relative to the install prefix, complete them
-            configuration_->dataPath_   = configuration_->rootPath_ / specialConfig::defaultDataPath;
-            configuration_->configPath_ = configuration_->rootPath_ / specialConfig::defaultConfigPath;
-            configuration_->logPath_    = configuration_->rootPath_ / specialConfig::defaultLogPath;
-
-#else
-
-            configuration_->dataPath_  = specialConfig::dataInstallDirectory;
-
-            // Get user directory
-#  ifdef ORXONOX_PLATFORM_UNIX /* Apple? */
-            char* userDataPathPtr(getenv("HOME"));
-#  else
-            char* userDataPathPtr(getenv("APPDATA"));
-#  endif
-            if (userDataPathPtr == NULL)
-                ThrowException(General, "Could not retrieve user data path.");
-            boost::filesystem::path userDataPath(userDataPathPtr);
-            userDataPath /= ".orxonox";
-
-            configuration_->configPath_ = userDataPath / specialConfig::defaultConfigPath;
-            configuration_->logPath_    = userDataPath / specialConfig::defaultLogPath;
-
-#endif
-
-        }
-
-        // Option to put all the config and log files in a separate folder
-        if (!CommandLine::getArgument("writingPathSuffix")->hasDefaultValue())
-        {
-            std::string directory(CommandLine::getValue("writingPathSuffix").getString());
-            configuration_->configPath_ = configuration_->configPath_ / directory;
-            configuration_->logPath_    = configuration_->logPath_    / directory;
-        }
-
-        // Create directories to avoid problems when opening files in non existent folders.
-        std::vector<std::pair<boost::filesystem::path, std::string> > directories;
-        directories.push_back(std::make_pair(boost::filesystem::path(configuration_->configPath_), "config"));
-        directories.push_back(std::make_pair(boost::filesystem::path(configuration_->logPath_), "log"));
-
-        for (std::vector<std::pair<boost::filesystem::path, std::string> >::iterator it = directories.begin();
-            it != directories.end(); ++it)
-        {
-            if (boost::filesystem::exists(it->first) && !boost::filesystem::is_directory(it->first))
-            {
-                ThrowException(General, std::string("The ") + it->second + " directory has been preoccupied by a file! \
-                                         Please remove " + it->first.string());
-            }
-            if (boost::filesystem::create_directories(it->first)) // function may not return true at all (bug?)
-            {
-                COUT(4) << "Created " << it->second << " directory" << std::endl;
-            }
-        }
-    }
-
     void Core::preUpdate(const Clock& time)
     {
+        // singletons from other libraries
+        ScopedSingletonManager::update<ScopeID::Root>(time);
         if (this->bGraphicsLoaded_)
         {
@@ -731,4 +441,6 @@
             // process gui events
             this->guiManager_->update(time);
+            // graphics singletons from other libraries
+            ScopedSingletonManager::update<ScopeID::Graphics>(time);
         }
         // process thread commands
Index: code/trunk/src/libraries/core/Core.h
===================================================================
--- code/trunk/src/libraries/core/Core.h	(revision 5781)
+++ code/trunk/src/libraries/core/Core.h	(revision 5929)
@@ -28,13 +28,4 @@
  */
 
-/**
-@file
-@brief
-    Declaration of the Core class.
-@details
-    The Core class is a singleton, only used to configure some variables
-    in the core through the config-file.
-*/
-
 #ifndef _Core_H__
 #define _Core_H__
@@ -45,4 +36,5 @@
 #include <boost/scoped_ptr.hpp>
 #include "util/OutputHandler.h"
+#include "util/Scope.h"
 #include "util/ScopeGuard.h"
 #include "util/Singleton.h"
@@ -55,7 +47,4 @@
     @brief
         The Core class is a singleton used to configure the program basics.
-    @details
-        The class provides information about the data, config and log path.
-        It determines those by the use of platform specific functions.
     @remark
         You should only create this singleton once because it destroys the identifiers!
@@ -85,28 +74,4 @@
             static void  resetLanguage();
 
-            static void tsetExternalDataPath(const std::string& path);
-            //! Returns the path to the data files as boost::filesystem::path
-            static const boost::filesystem::path& getDataPath();
-            //! Returns the path to the external data files as boost::filesystem::path
-            static const boost::filesystem::path& getExternalDataPath();
-            //! Returns the path to the config files as boost::filesystem::path
-            static const boost::filesystem::path& getConfigPath();
-            //! Returns the path to the log files as boost::filesystem::path
-            static const boost::filesystem::path& getLogPath();
-            //! Returns the path to the root folder as boost::filesystem::path
-            static const boost::filesystem::path& getRootPath();
-            //! Returns the path to the data files as std::string
-            static std::string getDataPathString();
-            //! Returns the path to the external data files as std::string
-            static std::string getExternalDataPathString();
-            //! Returns the path to the config files as std::string
-            static std::string getConfigPathString();
-            //! Returns the path to the log files as std::string
-            static std::string getLogPathString();
-            //! Returns the path to the root folder as std::string
-            static std::string getRootPathString();
-
-            static bool isDevelopmentRun() { return getInstance().bDevRun_; }
-
         private:
             Core(const Core&); //!< Don't use (undefined symbol)
@@ -118,9 +83,8 @@
             void unloadGraphics();
 
-            void setFixedPaths();
-            void setConfigurablePaths();
             void setThreadAffinity(int limitToCPU);
 
             // Mind the order for the destruction!
+            scoped_ptr<PathConfig>        pathConfig_;
             scoped_ptr<DynLibManager>     dynLibManager_;
             scoped_ptr<SignalHandler>     signalHandler_;
@@ -137,8 +101,8 @@
             scoped_ptr<InputManager>      inputManager_;        //!< Interface to OIS
             scoped_ptr<GUIManager>        guiManager_;          //!< Interface to GUI
+            scoped_ptr<Scope<ScopeID::Root> >     rootScope_;
+            scoped_ptr<Scope<ScopeID::Graphics> > graphicsScope_;
 
-            bool                          bDevRun_;             //!< True for runs in the build directory (not installed)
             bool                          bGraphicsLoaded_;
-
             static Core* singletonPtr_s;
     };
Index: code/trunk/src/libraries/core/CoreIncludes.h
===================================================================
--- code/trunk/src/libraries/core/CoreIncludes.h	(revision 5781)
+++ code/trunk/src/libraries/core/CoreIncludes.h	(revision 5929)
@@ -29,5 +29,5 @@
 /**
     @file
-    @brief Definition of macros for Identifier and Factory.
+    @brief Definition of macros for Identifiers
 
     Every class needs the RegisterObject(class) macro in its constructor. If the class is an interface
@@ -45,5 +45,5 @@
 #include "util/Debug.h"
 #include "Identifier.h"
-#include "Factory.h"
+#include "SubclassIdentifier.h"
 #include "ClassFactory.h"
 #include "ObjectList.h"
@@ -76,16 +76,16 @@
 
 /**
-    @brief Creates the entry in the Factory.
+    @brief Creates the Factory.
     @param ClassName The name of the class
 */
 #define CreateFactory(ClassName) \
-    bool bCreated##ClassName##Factory = orxonox::ClassFactory<ClassName>::create(#ClassName, true)
+    Factory* _##ClassName##Factory = new orxonox::ClassFactory<ClassName>(#ClassName, true)
 
 /**
-    @brief Creates the entry in the Factory for classes which should not be loaded through XML.
+    @brief Creates the Factory for classes which should not be loaded through XML.
     @param ClassName The name of the class
 */
 #define CreateUnloadableFactory(ClassName) \
-    bool bCreated##ClassName##Factory = orxonox::ClassFactory<ClassName>::create(#ClassName, false)
+    Factory* _##ClassName##Factory = new orxonox::ClassFactory<ClassName>(#ClassName, false)
 
 /**
@@ -100,19 +100,28 @@
 {
     /**
-        @brief Returns the Identifier with a given name through the factory.
+        @brief Returns the Identifier with a given name.
         @param String The name of the class
     */
     inline Identifier* ClassByString(const std::string& name)
     {
-        return Factory::getIdentifier(name);
+        return Identifier::getIdentifierByString(name);
     }
 
     /**
-        @brief Returns the Identifier with a given network ID through the factory.
+        @brief Returns the Identifier with a given lowercase name.
+        @param String The lowercase name of the class
+    */
+    inline Identifier* ClassByLowercaseString(const std::string& name)
+    {
+        return Identifier::getIdentifierByLowercaseString(name);
+    }
+
+    /**
+        @brief Returns the Identifier with a given network ID.
         @param networkID The network ID of the class
     */
     inline Identifier* ClassByID(uint32_t id)
     {
-        return Factory::getIdentifier(id);
+        return Identifier::getIdentifierByID(id);
     }
 }
Index: code/trunk/src/libraries/core/CorePrereqs.h
===================================================================
--- code/trunk/src/libraries/core/CorePrereqs.h	(revision 5781)
+++ code/trunk/src/libraries/core/CorePrereqs.h	(revision 5929)
@@ -28,6 +28,7 @@
 
 /**
-  @file
-  @brief Contains all the necessary forward declarations for all classes and structs.
+@file
+@brief
+    Shared library macros, enums, constants and forward declarations for the core library
 */
 
@@ -40,4 +41,5 @@
 // Shared library settings
 //-----------------------------------------------------------------------
+
 #if defined(ORXONOX_PLATFORM_WINDOWS) && !defined( CORE_STATIC_BUILD )
 #  ifdef CORE_SHARED_BUILD
@@ -56,8 +58,17 @@
 #endif
 
-
-//-----------------------------------------------------------------------
-// Forward declarations
-//-----------------------------------------------------------------------
+//-----------------------------------------------------------------------
+// Constants
+//-----------------------------------------------------------------------
+
+namespace orxonox
+{
+    static const uint32_t OBJECTID_UNKNOWN = static_cast<uint32_t>(-1);
+}
+
+//-----------------------------------------------------------------------
+// Enums
+//-----------------------------------------------------------------------
+
 namespace orxonox
 {
@@ -66,4 +77,5 @@
         enum Mode
         {
+            NOP,
             LoadObject,
             SaveObject,
@@ -82,11 +94,16 @@
         };
     };
-
+}
+
+//-----------------------------------------------------------------------
+// Forward declarations
+//-----------------------------------------------------------------------
+
+namespace orxonox
+{
     typedef std::string LanguageEntryLabel;
 
     class ArgumentCompleter;
     class ArgumentCompletionListElement;
-    class BaseFactory;
-    class BaseMetaObjectListElement;
     class BaseObject;
     template <class T>
@@ -98,7 +115,5 @@
     class ClassTreeMaskNode;
     class ClassTreeMaskObjectIterator;
-    class Clock;
     class CommandEvaluation;
-    class CommandExecutor;
     class CommandLine;
     class CommandLineArgument;
@@ -109,4 +124,5 @@
     class ConfigFileManager;
     class ConfigFileSection;
+    struct ConfigFileType;
     class ConfigValueContainer;
     class ConsoleCommand;
@@ -115,5 +131,5 @@
     class DynLibManager;
     struct Event;
-    class EventContainer;
+    class EventState;
     class Executor;
     template <class T>
@@ -125,4 +141,8 @@
     class FunctorMember;
     class FunctorStatic;
+    class Game;
+    class GameState;
+    struct GameStateInfo;
+    struct GameStateTreeNode;
     class GraphicsManager;
     class GUIManager;
@@ -131,8 +151,5 @@
     template <class T>
     class Iterator;
-    class IteratorBase;
     class Language;
-    class LanguageEntry;
-    class Loader;
     class LuaState;
     class MemoryArchive;
@@ -152,8 +169,11 @@
     class OgreWindowEventListener;
     class OrxonoxClass;
+    class PathConfig;
     struct ResourceInfo;
     class Shell;
     class ShellListener;
     template <class T>
+    class SmartPtr;
+    template <class T>
     class SubclassIdentifier;
     class TclBind;
@@ -163,4 +183,8 @@
     class TclThreadManager;
     class Template;
+    class Thread;
+    class ThreadPool;
+    template <class T>
+    class WeakPtr;
     class WindowEventListener;
     class XMLFile;
@@ -173,15 +197,8 @@
     class XMLPortParamContainer;
 
-    // game states
-    class Game;
-    class GameState;
-    struct GameStateInfo;
-    struct GameStateTreeNode;
-
-    // input
+    // Input
     class BaseCommand;
     class BufferedParamCommand;
     class Button;
-    class CalibratorCallback;
     class HalfAxis;
     class InputBuffer;
@@ -192,16 +209,15 @@
     class InputManager;
     class InputState;
+    struct InputStatePriority;
+    class JoyStickQuantityListener;
     class JoyStick;
+    class KeyBinder;
+    class KeyBinderManager;
+    class Keyboard;
+    class KeyDetector;
+    class KeyEvent;
     class Mouse;
-    class Keyboard;
-    class KeyBinder;
-    class KeyDetector;
     class ParamCommand;
     class SimpleCommand;
-
-
-    // multithreading
-    class Thread;
-    class ThreadPool;
 }
 
@@ -282,13 +298,6 @@
 namespace orxonox
 {
-    using ticpp::Document;
     using ticpp::Element;
-    using ticpp::Declaration;
-    using ticpp::StylesheetReference;
-    using ticpp::Text;
-    using ticpp::Comment;
-    using ticpp::Attribute;
-}
-
+}
 
 #endif /* _CorePrereqs_H__ */
Index: code/trunk/src/libraries/core/Event.cc
===================================================================
--- code/trunk/src/libraries/core/Event.cc	(revision 5781)
+++ code/trunk/src/libraries/core/Event.cc	(revision 5929)
@@ -30,50 +30,79 @@
 
 #include "BaseObject.h"
-#include "Executor.h"
+#include "Identifier.h"
 
 namespace orxonox
 {
-    EventContainer::~EventContainer()
+    /**
+        @brief Destructor: Deletes the functor of the event state.
+    */
+    EventState::~EventState()
     {
-        delete this->eventfunction_;
+        if (this->statefunction_)
+            delete this->statefunction_;
     }
 
-    void EventContainer::process(BaseObject* object, const Event& event)
+    /**
+        @brief Processes an event (calls the set-function if the necessary conditions are met).
+        
+        @param event     The fired event
+        @param object    The object whose state is affected by the event (only needed for debug output)
+    */
+    void EventState::process(const Event& event, BaseObject* object)
     {
-        if (this->bActive_)
+        if (this->bProcessingEvent_)
         {
-            COUT(2) << "Warning: Detected Event loop in section \"" << this->eventname_ << "\" of object \"" << object->getName() << "\" and fired by \"" << event.originator_->getName() << "\"" << std::endl;
+            COUT(2) << "Warning: Detected Event loop in section \"" << event.statename_ << "\" of object \"" << object->getName() << "\" and fired by \"" << event.originator_->getName() << "\"" << std::endl;
             return;
         }
 
-        this->bActive_ = true;
+        this->bProcessingEvent_ = true;
 
-        if (this->eventname_ == event.sectionname_)
+        // check if the originator is an instance of the requested class
+        if (event.originator_->isA(this->subclass_))
         {
-            if (event.originator_->isA(this->subclass_))
+            // actualize the activationcounter
+            if (event.activate_)
+                ++this->activeEvents_;
+            else
             {
-                if (event.activate_)
-                    ++this->activeEvents_;
-                else
+                --this->activeEvents_;
+
+                if (this->activeEvents_ < 0)
+                    this->activeEvents_ = 0;
+            }
+
+            if (this->statefunction_->getParamCount() == 0 && event.activate_)
+            {
+                // if the eventfunction doesn't have a state, just call it whenever an activation-event comes in
+                (*this->statefunction_)();
+            }
+            else if ((this->activeEvents_ == 1 && event.activate_) || (this->activeEvents_ == 0 && !event.activate_))
+            {
+                // if the eventfunction needs a state, we just call the function if the state changed from 0 to 1 (state = true) or from 1 to 0 (state = false) [but not if activeEvents_ is > 1]
+                if (this->statefunction_->getParamCount() == 1)
                 {
-                    --this->activeEvents_;
-
-                    if (this->activeEvents_ < 0)
-                        this->activeEvents_ = 0;
+                    // one argument: just the eventstate
+                    (*this->statefunction_)(this->activeEvents_);
                 }
-
-                if (this->eventfunction_->getParamCount() == 0 && event.activate_)
-                    (*this->eventfunction_)();
-                else if ((this->activeEvents_ == 1 && event.activate_) || (this->activeEvents_ == 0 && !event.activate_))
+                else if (this->statefunction_->getParamCount() >= 2)
                 {
-                    if (this->eventfunction_->getParamCount() == 1)
-                        (*this->eventfunction_)(this->activeEvents_);
-                    else if (this->eventfunction_->getParamCount() >= 2 && event.castedOriginator_)
-                        (*this->eventfunction_)(this->activeEvents_, event.castedOriginator_);
+                    // two arguments: the eventstate and the originator
+                    if (this->subclass_->isExactlyA(ClassIdentifier<BaseObject>::getIdentifier()))
+                    {
+                        // if the subclass is BaseObject, we don't have to cast the pointer
+                        (*this->statefunction_)(this->activeEvents_, event.originator_);
+                    }
+                    else
+                    {
+                        // else cast the pointer to the desired class
+                        void* castedOriginator = event.originator_->getDerivedPointer(this->subclass_->getClassID());
+                        (*this->statefunction_)(this->activeEvents_, castedOriginator);
+                    }
                 }
             }
         }
 
-        this->bActive_ = false;
+        this->bProcessingEvent_ = false;
     }
 }
Index: code/trunk/src/libraries/core/Event.h
===================================================================
--- code/trunk/src/libraries/core/Event.h	(revision 5781)
+++ code/trunk/src/libraries/core/Event.h	(revision 5929)
@@ -35,29 +35,48 @@
 namespace orxonox
 {
+    /**
+        @brief The Event struct contains information about a fired Event.
+    */
     struct _CoreExport Event
     {
-            Event(bool activate, BaseObject* originator) : activate_(activate), originator_(originator), castedOriginator_(0) {}
+        Event(bool activate, BaseObject* originator, const std::string& name) : activate_(activate), originator_(originator), name_(name) {}
 
-            bool        activate_;
-            BaseObject* originator_;
-            void*       castedOriginator_;
-            std::string sectionname_;
+        bool        activate_;   //!< True if this is an activating event (the event source was inactive before and just triggered the event) - false otherwise
+        std::string statename_;  //!< The name of the state this event affects
+        BaseObject* originator_; //!< The object which triggered this event
+        std::string name_;       //!< The name of this event
     };
 
-    class _CoreExport EventContainer
+    /**
+        @brief The EventState contains information about an event state.
+        
+        An event state is a state of an object, which can be changed by events.
+        Event states are changed through functions. Possible functions headers for set event states are:
+         - memoryless state: function()
+         - boolean state:    function(bool state)
+         - individual state: function(bool state, SomeClass originator)
+         
+        Note that SomeClass may be any class deriving from BaseObject. You will not receive events from originators of other classes.
+        The actual class for SomeClass must be specified as the second argument of the XMLPortEventState macro.
+        
+        The this pointer of the affected object is hidden in the functors, because the events are processed in the BaseObject, but some
+        statefunctions may be from child-classes.
+    */
+    class _CoreExport EventState
     {
         public:
-            EventContainer(const std::string& eventname, Executor* eventfunction, Identifier* subclass) : bActive_(false), eventname_(eventname), eventfunction_(eventfunction), subclass_(subclass), activeEvents_(0) {}
-            virtual ~EventContainer();
+            EventState(Functor* statefunction, Identifier* subclass) : bProcessingEvent_(false), activeEvents_(0), statefunction_(statefunction), subclass_(subclass) {}
+            virtual ~EventState();
 
-            void process(BaseObject* object, const Event& event);
+            void process(const Event& event, BaseObject* object);
+            
+            Functor* getFunctor() const
+                { return this->statefunction_; }
 
         private:
-            bool bActive_;
-            std::string eventname_;
-            Executor* eventfunction_;
-            Identifier* subclass_;
-
-            int activeEvents_;
+            bool        bProcessingEvent_;  //!< This becomes true while the container processes an event (used to prevent loops)
+            int         activeEvents_;      //!< The number of events which affect this state and are currently active
+            Functor*    statefunction_;     //!< A functor to set the state
+            Identifier* subclass_;          //!< Originators must be an instance of this class (usually BaseObject, but some statefunctions allow a second argument with an originator of a specific class)
     };
 }
Index: code/trunk/src/libraries/core/EventIncludes.h
===================================================================
--- code/trunk/src/libraries/core/EventIncludes.h	(revision 5781)
+++ code/trunk/src/libraries/core/EventIncludes.h	(revision 5929)
@@ -32,40 +32,57 @@
 #include "CorePrereqs.h"
 #include "Executor.h"
+#include "XMLPort.h"
 
-#define ORXONOX_SET_EVENT(classname, eventname, functionname, event) \
-    ORXONOX_SET_EVENT_GENERIC(eventcontainer##classname##functionname, classname, eventname, functionname, event, BaseObject)
+/**
+    @brief Defines a new event state (a state of the object which can be changed by events).
+    
+    @param classname    The name of this class
+    @param subclassname Usually BaseObject - if different, only instances of this class can send events to this object
+    @param statename    The name (string) of this state
+    @param function     The function which should be used to set the state
+    @param xmlelement   Argument for XMLPort
+    @param mode         Argument for XMLPort
+*/
+#define XMLPortEventState(classname, subclassname, statename, function, xmlelement, mode) \
+    orxonox::EventState* containername##function = this->getEventState(statename); \
+    if (!containername##function) \
+    { \
+        containername##function = new orxonox::EventState(orxonox::createFunctor(&classname::function, this), orxonox::ClassIdentifier<subclassname>::getIdentifier()); \
+        this->addEventState(statename, containername##function); \
+    } \
+    XMLPortEventStateIntern(xmlportevent##function, classname, statename, xmlelement, mode)
 
-#define ORXONOX_SET_EVENT_TEMPLATE(classname, eventname, functionname, event, ...) \
-    ORXONOX_SET_EVENT_GENERIC_TEMPLATE(eventcontainer##classname##functionname, classname, eventname, functionname, event, BaseObject, __VA_ARGS__)
+/**
+    @brief Like XMLPortEventState but with additional template arguments to identify the function of the state (if ambiguous).
+*/
+#define XMLPortEventStateTemplate(classname, subclassname, statename, function, xmlelement, mode, ...) \
+    orxonox::EventState* containername##function = this->getEventState(statename); \
+    if (!containername##function) \
+    { \
+        containername##function = new orxonox::EventState(orxonox::createFunctor<classname, __VA_ARGS__ >(&classname::function, this), orxonox::ClassIdentifier<subclassname>::getIdentifier()); \
+        this->addEventState(statename, containername##function); \
+    } \
+    XMLPortEventStateIntern(xmlportevent##function, classname, statename, xmlelement, mode)
 
-#define ORXONOX_SET_SUBCLASS_EVENT(classname, eventname, functionname, event, subclassname) \
-    ORXONOX_SET_EVENT_GENERIC(eventcontainer##classname##functionname, classname, eventname, functionname, event, subclassname)
+#define XMLPortEventStateIntern(name, classname, statename, xmlelement, mode) \
+    static orxonox::ExecutorMember<classname>* xmlsetfunctor##name = (orxonox::ExecutorMember<classname>*)&orxonox::createExecutor(orxonox::createFunctor(&classname::addEventSource), std::string( #classname ) + "::" + "addEventSource" + "(" + statename + ")")->setDefaultValue(1, statename); \
+    static orxonox::ExecutorMember<classname>* xmlgetfunctor##name = (orxonox::ExecutorMember<classname>*)&orxonox::createExecutor(orxonox::createFunctor(&classname::getEventSource), std::string( #classname ) + "::" + "getEventSource" + "(" + statename + ")")->setDefaultValue(1, statename); \
+    XMLPortObjectGeneric(xmlport##name, classname, orxonox::BaseObject, statename, xmlsetfunctor##name, xmlgetfunctor##name, xmlelement, mode, false, true)
+    
 
-#define ORXONOX_SET_SUBCLASS_EVENT_TEMPLATE(classname, eventname, functionname, event, subclassname, ...) \
-    ORXONOX_SET_EVENT_GENERIC_TEMPLATE(eventcontainer##classname##functionname, classname, eventname, functionname, event, subclassname, __VA_ARGS__)
+/**
+    @brief Defines a new event name for a class. Named events can only have names which were defined with this macro.
+    
+    @param classname The name of the class
+    @param name      The name of the event
+*/
+#define CreateEventName(classname, name) \
+    static std::string eventname##classname##name = #name
 
-#define ORXONOX_SET_EVENT_GENERIC(containername, classname, eventname, functionname, event, subclassname) \
-    orxonox::EventContainer* containername = this->getEventContainer(eventname); \
-    if (!containername) \
-    { \
-        ExecutorMember<classname>* executor = orxonox::createExecutor(orxonox::createFunctor(&classname::functionname), std::string( #classname ) + "::" + #functionname); \
-        executor->setObject(this); \
-        containername = new orxonox::EventContainer(std::string(eventname), executor, orxonox::ClassIdentifier<subclassname>::getIdentifier()); \
-        this->addEventContainer(eventname, containername); \
-    } \
-    event.castedOriginator_ = orxonox::orxonox_cast<subclassname*>(event.originator_); \
-    containername->process(this, event)
-
-#define ORXONOX_SET_EVENT_GENERIC_TEMPLATE(containername, classname, eventname, functionname, event, subclassname, ...) \
-    orxonox::EventContainer* containername = this->getEventContainer(eventname); \
-    if (!containername) \
-    { \
-        ExecutorMember<classname>* executor = orxonox::createExecutor(orxonox::createFunctor<classname, __VA_ARGS__ >(&classname::functionname), std::string( #classname ) + "::" + #functionname); \
-        executor->setObject(this); \
-        containername = new orxonox::EventContainer(std::string(eventname), executor, orxonox::ClassIdentifier<subclassname>::getIdentifier()); \
-        this->addEventContainer(eventname, containername); \
-    } \
-    event.castedOriginator_ = orxonox::orxonox_cast<subclassname*>(event.originator_); \
-    containername->process(this, event)
-
+/**
+    @brief This macro is needed to fire an event with this name. The event name must previously be declared with @ref CreateEventName.
+*/    
+#define FireEventName(classname, name) \
+    eventname##classname##name
+ 
 #endif /* _EventIncludes_H__ */
Index: code/trunk/src/libraries/core/Factory.cc
===================================================================
--- code/trunk/src/libraries/core/Factory.cc	(revision 5781)
+++ 	(revision )
@@ -1,129 +1,0 @@
-/*
- *   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:
- *      Fabian 'x3n' Landau
- *   Co-authors:
- *      ...
- *
- */
-
-/**
-    @file
-    @brief Implementation of the Factory class.
-*/
-
-#include "Factory.h"
-
-#include "util/Debug.h"
-#include "Identifier.h"
-#include "BaseObject.h"
-
-namespace orxonox
-{
-    /**
-        @brief Returns the Identifier with a given name.
-        @param name The name of the wanted Identifier
-        @return The Identifier
-    */
-    Identifier* Factory::getIdentifier(const std::string& name)
-    {
-        std::map<std::string, Identifier*>::const_iterator it = getFactoryPointer()->identifierStringMap_.find(name);
-        if (it != getFactoryPointer()->identifierStringMap_.end())
-            return it->second;
-        else
-            return 0;
-    }
-
-    /**
-        @brief Returns the Identifier with a given network ID.
-        @param id The network ID of the wanted Identifier
-        @return The Identifier
-    */
-    Identifier* Factory::getIdentifier(const uint32_t id)
-    {
-        std::map<uint32_t, Identifier*>::const_iterator it = getFactoryPointer()->identifierNetworkIDMap_.find(id);
-        if (it != getFactoryPointer()->identifierNetworkIDMap_.end())
-            return it->second;
-        else
-            return 0;
-    }
-
-    /**
-        @brief Adds a new Identifier to both maps.
-        @param name The name of the identifier
-        @param identifier The identifier to add
-    */
-    void Factory::add(const std::string& name, Identifier* identifier)
-    {
-        getFactoryPointer()->identifierStringMap_[name] = identifier;
-        getFactoryPointer()->identifierNetworkIDMap_[identifier->getNetworkID()] = identifier;
-    }
-
-    /**
-        @brief Removes the entry with the old network ID and adds a new one.
-        @param identifier The identifier to change
-        @param oldID The old networkID
-        @param newID The new networkID
-    */
-    void Factory::changeNetworkID(Identifier* identifier, const uint32_t oldID, const uint32_t newID)
-    {
-//        getFactoryPointer()->identifierNetworkIDMap_.erase(oldID);
-        getFactoryPointer()->identifierNetworkIDMap_[newID] = identifier;
-    }
-
-    /**
-        @brief Cleans the NetworkID map (needed on clients for correct initialization)
-    */
-    void Factory::cleanNetworkIDs()
-    {
-        getFactoryPointer()->identifierNetworkIDMap_.clear();
-    }
-
-    /**
-        @brief Creates the class-hierarchy by creating and destroying one object of each type.
-    */
-    void Factory::createClassHierarchy()
-    {
-        COUT(3) << "*** Factory: Create class-hierarchy" << std::endl;
-        std::map<std::string, Identifier*>::iterator it;
-        it = getFactoryPointer()->identifierStringMap_.begin();
-        (*getFactoryPointer()->identifierStringMap_.begin()).second->startCreatingHierarchy();
-        for (it = getFactoryPointer()->identifierStringMap_.begin(); it != getFactoryPointer()->identifierStringMap_.end(); ++it)
-        {
-            // To create the new branch of the class-hierarchy, we create a new object and delete it afterwards.
-            BaseObject* temp = (*it).second->fabricate(0);
-            delete temp;
-        }
-        (*getFactoryPointer()->identifierStringMap_.begin()).second->stopCreatingHierarchy();
-        COUT(3) << "*** Factory: Finished class-hierarchy creation" << std::endl;
-    }
-
-    /**
-        @brief Ensures the Factory gets created in the right moment.
-        @return The Factory.
-    */
-    Factory* Factory::getFactoryPointer()
-    {
-      static Factory theOneAndOnlyFactoryInstance = Factory();
-      return &theOneAndOnlyFactoryInstance;
-    }
-}
Index: code/trunk/src/libraries/core/Factory.h
===================================================================
--- code/trunk/src/libraries/core/Factory.h	(revision 5781)
+++ 	(revision )
@@ -1,101 +1,0 @@
-/*
- *   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:
- *      Fabian 'x3n' Landau
- *   Co-authors:
- *      ...
- *
- */
-
-/**
-    @file
-    @brief Definition of the Factory and the BaseFactory class.
-
-    The Factory is a singleton, containing two maps to map either the name or the network ID
-    of a class with the corresponding Identifier.
-
-    Usage:
-    ID(classname) or ID(networkID) returns the corresponding Identifier.
-
-
-    BaseObject is the parent of ClassFactory which is defined in ClassFactory.h.
-    It can't be defined in ClassFactory.h, because of circular dependencies.
-*/
-
-#ifndef _Factory_H__
-#define _Factory_H__
-
-#include "CorePrereqs.h"
-
-#include <map>
-#include <string>
-
-namespace orxonox
-{
-    // ###############################
-    // ###         Factory         ###
-    // ###############################
-    //! The Factory is used to map the name or the network ID of a class with its Identifier.
-    class _CoreExport Factory
-    {
-        public:
-            static Identifier* getIdentifier(const std::string& name);
-            static Identifier* getIdentifier(const uint32_t id);
-            static void add(const std::string& name, Identifier* identifier);
-            static void changeNetworkID(Identifier* identifier, const uint32_t oldID, const uint32_t newID);
-            static void cleanNetworkIDs();
-            static void createClassHierarchy();
-
-            static Factory* getFactoryPointer();    // avoid overriding order problem in the static intialisation process
-
-            /** @brief Returns the factory-map. */
-            static const std::map<std::string, Identifier*>& getFacbtoryMap()
-                { return Factory::getFactoryPointer()->identifierStringMap_; }
-            /** @brief Returns the begin-iterator of the factory-map. */
-            static std::map<std::string, Identifier*>::const_iterator getFactoryMapBegin()
-                { return Factory::getFactoryPointer()->identifierStringMap_.begin(); }
-            /** @brief Returns the end-iterator of the factory-map. */
-            static std::map<std::string, Identifier*>::const_iterator getFactoryMapEnd()
-                { return Factory::getFactoryPointer()->identifierStringMap_.end(); }
-
-        private:
-            Factory() {}                            // don't create
-            Factory(const Factory& factory);        // don't copy
-            ~Factory() {}                           // don't delete
-
-            std::map<std::string, Identifier*> identifierStringMap_;            //!< The map, mapping the name with the Identifier
-            std::map<uint32_t, Identifier*> identifierNetworkIDMap_;        //!< The map, mapping the network ID with the Identifier
-    };
-
-    // ###############################
-    // ###       BaseFactory       ###
-    // ###############################
-    //! Base-class of ClassFactory. Has to be defined separate because of circular dependencies.
-    class _CoreExport BaseFactory
-    {
-        public:
-            virtual BaseObject* fabricate(BaseObject* creator) = 0;
-            virtual ~BaseFactory() {};
-    };
-}
-
-#endif /* _Factory_H__ */
Index: code/trunk/src/libraries/core/Functor.h
===================================================================
--- code/trunk/src/libraries/core/Functor.h	(revision 5781)
+++ code/trunk/src/libraries/core/Functor.h	(revision 5929)
@@ -191,29 +191,35 @@
 
 
-#define FUNCTOR_TEMPLATE(ismember, returnvalue, numparams) FUNCTOR_TEMPLATE##ismember##returnvalue##numparams
-#define FUNCTOR_TEMPLATE000
-#define FUNCTOR_TEMPLATE001 template <class P1>
-#define FUNCTOR_TEMPLATE002 template <class P1, class P2>
-#define FUNCTOR_TEMPLATE003 template <class P1, class P2, class P3>
-#define FUNCTOR_TEMPLATE004 template <class P1, class P2, class P3, class P4>
-#define FUNCTOR_TEMPLATE005 template <class P1, class P2, class P3, class P4, class P5>
-#define FUNCTOR_TEMPLATE010 template <class R>
-#define FUNCTOR_TEMPLATE011 template <class R, class P1>
-#define FUNCTOR_TEMPLATE012 template <class R, class P1, class P2>
-#define FUNCTOR_TEMPLATE013 template <class R, class P1, class P2, class P3>
-#define FUNCTOR_TEMPLATE014 template <class R, class P1, class P2, class P3, class P4>
-#define FUNCTOR_TEMPLATE015 template <class R, class P1, class P2, class P3, class P4, class P5>
-#define FUNCTOR_TEMPLATE100 template <class T>
-#define FUNCTOR_TEMPLATE101 template <class T, class P1>
-#define FUNCTOR_TEMPLATE102 template <class T, class P1, class P2>
-#define FUNCTOR_TEMPLATE103 template <class T, class P1, class P2, class P3>
-#define FUNCTOR_TEMPLATE104 template <class T, class P1, class P2, class P3, class P4>
-#define FUNCTOR_TEMPLATE105 template <class T, class P1, class P2, class P3, class P4, class P5>
-#define FUNCTOR_TEMPLATE110 template <class T, class R>
-#define FUNCTOR_TEMPLATE111 template <class T, class R, class P1>
-#define FUNCTOR_TEMPLATE112 template <class T, class R, class P1, class P2>
-#define FUNCTOR_TEMPLATE113 template <class T, class R, class P1, class P2, class P3>
-#define FUNCTOR_TEMPLATE114 template <class T, class R, class P1, class P2, class P3, class P4>
-#define FUNCTOR_TEMPLATE115 template <class T, class R, class P1, class P2, class P3, class P4, class P5>
+#define FUNCTOR_TEMPLATE(ismember, returnvalue, numparams, additionalobject) FUNCTOR_TEMPLATE##ismember##returnvalue##numparams(additionalobject)
+#define FUNCTOR_TEMPLATE000(additionalobject)
+#define FUNCTOR_TEMPLATE001(additionalobject) template <class P1>
+#define FUNCTOR_TEMPLATE002(additionalobject) template <class P1, class P2>
+#define FUNCTOR_TEMPLATE003(additionalobject) template <class P1, class P2, class P3>
+#define FUNCTOR_TEMPLATE004(additionalobject) template <class P1, class P2, class P3, class P4>
+#define FUNCTOR_TEMPLATE005(additionalobject) template <class P1, class P2, class P3, class P4, class P5>
+#define FUNCTOR_TEMPLATE010(additionalobject) template <class R>
+#define FUNCTOR_TEMPLATE011(additionalobject) template <class R, class P1>
+#define FUNCTOR_TEMPLATE012(additionalobject) template <class R, class P1, class P2>
+#define FUNCTOR_TEMPLATE013(additionalobject) template <class R, class P1, class P2, class P3>
+#define FUNCTOR_TEMPLATE014(additionalobject) template <class R, class P1, class P2, class P3, class P4>
+#define FUNCTOR_TEMPLATE015(additionalobject) template <class R, class P1, class P2, class P3, class P4, class P5>
+#define FUNCTOR_TEMPLATE100(additionalobject) template <class T FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+#define FUNCTOR_TEMPLATE101(additionalobject) template <class T, class P1 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+#define FUNCTOR_TEMPLATE102(additionalobject) template <class T, class P1, class P2 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+#define FUNCTOR_TEMPLATE103(additionalobject) template <class T, class P1, class P2, class P3 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+#define FUNCTOR_TEMPLATE104(additionalobject) template <class T, class P1, class P2, class P3, class P4 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+#define FUNCTOR_TEMPLATE105(additionalobject) template <class T, class P1, class P2, class P3, class P4, class P5 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+#define FUNCTOR_TEMPLATE110(additionalobject) template <class T, class R FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+#define FUNCTOR_TEMPLATE111(additionalobject) template <class T, class R, class P1 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+#define FUNCTOR_TEMPLATE112(additionalobject) template <class T, class R, class P1, class P2 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+#define FUNCTOR_TEMPLATE113(additionalobject) template <class T, class R, class P1, class P2, class P3 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+#define FUNCTOR_TEMPLATE114(additionalobject) template <class T, class R, class P1, class P2, class P3, class P4 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+#define FUNCTOR_TEMPLATE115(additionalobject) template <class T, class R, class P1, class P2, class P3, class P4, class P5 FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) >
+
+
+
+#define FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT(additionalobject) FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT##additionalobject
+#define FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT0
+#define FUNCTOR_TEMPLATE_ADDITIONAL_OBJECT1 , class O
 
 
@@ -317,5 +323,5 @@
 
 #define CREATE_STATIC_FUNCTOR(returnvalue, numparams) \
-    FUNCTOR_TEMPLATE(0, returnvalue, numparams) \
+    FUNCTOR_TEMPLATE(0, returnvalue, numparams, 0) \
     class FunctorStatic##returnvalue##numparams : public FunctorStatic \
     { \
@@ -347,5 +353,5 @@
     \
     \
-    FUNCTOR_TEMPLATE(0, returnvalue, numparams) \
+    FUNCTOR_TEMPLATE(0, returnvalue, numparams, 0) \
     inline FunctorStatic##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(0, returnvalue, numparams)* createFunctor(FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (*functionPointer)(FUNCTOR_FUNCTION_PARAMS(numparams))) \
     { \
@@ -358,5 +364,5 @@
 
 #define CREATE_MEMBER_FUNCTOR(returnvalue, numparams) \
-    FUNCTOR_TEMPLATE(1, returnvalue, numparams) \
+    FUNCTOR_TEMPLATE(1, returnvalue, numparams, 0) \
     class FunctorMember##returnvalue##numparams : public FunctorMember<T> \
     { \
@@ -391,5 +397,5 @@
     \
     \
-    FUNCTOR_TEMPLATE(1, returnvalue, numparams) \
+    FUNCTOR_TEMPLATE(1, returnvalue, numparams, 0) \
     class FunctorConstMember##returnvalue##numparams : public FunctorMember<T> \
     { \
@@ -423,5 +429,5 @@
     \
     \
-    FUNCTOR_TEMPLATE(1, returnvalue, numparams) \
+    FUNCTOR_TEMPLATE(1, returnvalue, numparams, 0) \
     inline FunctorMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams)* createFunctor(FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (T::*functionPointer)(FUNCTOR_FUNCTION_PARAMS(numparams))) \
     { \
@@ -430,8 +436,25 @@
     \
     \
-    FUNCTOR_TEMPLATE(1, returnvalue, numparams) \
+    FUNCTOR_TEMPLATE(1, returnvalue, numparams, 0) \
     inline FunctorConstMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams)* createFunctor(FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (T::*functionPointer)(FUNCTOR_FUNCTION_PARAMS(numparams)) const) \
     { \
         return new FunctorConstMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams) (functionPointer); \
+    } \
+    \
+    FUNCTOR_TEMPLATE(1, returnvalue, numparams, 1) \
+    inline FunctorMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams)* createFunctor(FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (T::*functionPointer)(FUNCTOR_FUNCTION_PARAMS(numparams)), O* object) \
+    { \
+        FunctorMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams)* functor = new FunctorMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams) (functionPointer); \
+        functor->setObject(object); \
+        return functor; \
+    } \
+    \
+    \
+    FUNCTOR_TEMPLATE(1, returnvalue, numparams, 1) \
+    inline FunctorConstMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams)* createFunctor(FUNCTOR_FUNCTION_RETURNVALUE(returnvalue) (T::*functionPointer)(FUNCTOR_FUNCTION_PARAMS(numparams)) const, O* object) \
+    { \
+        FunctorConstMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams)* functor = new FunctorConstMember##returnvalue##numparams FUNCTOR_TEMPLATE_CLASSES(1, returnvalue, numparams) (functionPointer); \
+        functor->setObject(object); \
+        return functor; \
     }
 
Index: code/trunk/src/libraries/core/GUIManager.cc
===================================================================
--- code/trunk/src/libraries/core/GUIManager.cc	(revision 5781)
+++ code/trunk/src/libraries/core/GUIManager.cc	(revision 5929)
@@ -49,10 +49,11 @@
 #endif
 
+#include "util/Clock.h"
 #include "util/Debug.h"
 #include "util/Exception.h"
 #include "util/OrxAssert.h"
 #include "Core.h"
-#include "Clock.h"
 #include "LuaState.h"
+#include "PathConfig.h"
 #include "Resource.h"
 
@@ -62,5 +63,5 @@
     {
     public:
-	    void logEvent(const CEGUI::String& message, CEGUI::LoggingLevel level = CEGUI::Standard)
+        void logEvent(const CEGUI::String& message, CEGUI::LoggingLevel level = CEGUI::Standard)
         {
             int orxonoxLevel = CEGUI::Standard;
@@ -100,4 +101,5 @@
         : renderWindow_(renderWindow)
         , resourceProvider_(0)
+        , camera_(NULL)
     {
         using namespace CEGUI;
@@ -116,5 +118,5 @@
         // Create our own logger to specify the filepath
         std::auto_ptr<CEGUILogger> ceguiLogger(new CEGUILogger());
-        ceguiLogger->setLogFilename(Core::getLogPathString() + "cegui.log");
+        ceguiLogger->setLogFilename(PathConfig::getLogPathString() + "cegui.log");
         // set the log level according to ours (translate by subtracting 1)
         ceguiLogger->setLoggingLevel(
@@ -173,4 +175,5 @@
     void GUIManager::setCamera(Ogre::Camera* camera)
     {
+        this->camera_ = camera;
         if (camera == NULL)
             this->guiRenderer_->setTargetSceneManager(0);
Index: code/trunk/src/libraries/core/GUIManager.h
===================================================================
--- code/trunk/src/libraries/core/GUIManager.h	(revision 5781)
+++ code/trunk/src/libraries/core/GUIManager.h	(revision 5929)
@@ -71,4 +71,5 @@
 
         void setCamera(Ogre::Camera* camera);
+        Ogre::Camera* getCamera() { return this->camera_; }
 
         static GUIManager* getInstancePtr() { return singletonPtr_s; }
@@ -101,4 +102,5 @@
         CEGUI::Logger*                       ceguiLogger_;      //!< CEGUI's logger to be able to log CEGUI errors in our log
         std::map<std::string, PlayerInfo*>   players_;          //!< Stores the player (owner) for each gui
+        Ogre::Camera*                        camera_;           //!< Camera used to render the scene with the GUI
 
         static GUIManager*                   singletonPtr_s;    //!< Singleton reference to GUIManager
Index: code/trunk/src/libraries/core/Game.cc
===================================================================
--- code/trunk/src/libraries/core/Game.cc	(revision 5781)
+++ code/trunk/src/libraries/core/Game.cc	(revision 5929)
@@ -38,4 +38,5 @@
 #include <boost/weak_ptr.hpp>
 
+#include "util/Clock.h"
 #include "util/Debug.h"
 #include "util/Exception.h"
@@ -43,5 +44,4 @@
 #include "util/Sleep.h"
 #include "util/SubString.h"
-#include "Clock.h"
 #include "CommandLine.h"
 #include "ConsoleCommand.h"
@@ -57,4 +57,10 @@
         { Game::getInstance().stop(); }
     SetConsoleCommandShortcutExternAlias(stop_game, "exit");
+    static void printFPS()
+        { COUT(0) << Game::getInstance().getAvgFPS() << std::endl; }
+    SetConsoleCommandShortcutExternAlias(printFPS, "printFPS");
+    static void printTickTime()
+        { COUT(0) << Game::getInstance().getAvgTickTime() << std::endl; }
+    SetConsoleCommandShortcutExternAlias(printTickTime, "printTickTime");
 
     std::map<std::string, GameStateInfo> Game::gameStateDeclarations_s;
@@ -111,5 +117,5 @@
     Game::Game(const std::string& cmdLine)
         // Destroy factories before the Core!
-        : gsFactoryDestroyer_(Game::GameStateFactory::factories_s, &std::map<std::string, shared_ptr<GameStateFactory> >::clear)
+        : gsFactoryDestroyer_(Game::GameStateFactory::getFactories(), &std::map<std::string, shared_ptr<GameStateFactory> >::clear)
     {
         this->bAbort_ = false;
@@ -410,4 +416,6 @@
                 requestedNodes.push_back(currentNode);
             }
+            if (currentNode == NULL)
+                requestedNodes.clear();
         }
 
@@ -457,10 +465,10 @@
     {
         // Split string into pieces of the form whitespacesText
-        std::vector<std::pair<std::string, unsigned> > stateStrings;
+        std::vector<std::pair<std::string, int> > stateStrings;
         size_t pos = 0;
         size_t startPos = 0;
         while (pos < str.size())
         {
-            unsigned indentation = 0;
+            int indentation = 0;
             while(pos < str.size() && str[pos] == ' ')
                 ++indentation, ++pos;
@@ -470,45 +478,53 @@
             stateStrings.push_back(std::make_pair(str.substr(startPos, pos - startPos), indentation));
         }
-        unsigned int currentLevel = 0;
-        shared_ptr<GameStateTreeNode> currentNode = this->rootStateNode_;
-        for (std::vector<std::pair<std::string, unsigned> >::const_iterator it = stateStrings.begin(); it != stateStrings.end(); ++it)
-        {
-            std::string newStateName = it->first;
-            unsigned newLevel = it->second + 1; // empty root is 0
-            if (!this->checkState(newStateName))
-                ThrowException(GameState, "GameState with name '" << newStateName << "' not found!");
-            if (newStateName == this->rootStateNode_->name_)
+        if (stateStrings.empty())
+            ThrowException(GameState, "Emtpy GameState hierarchy provided, terminating.");
+        // Add element with large identation to detect the last with just an iterator
+        stateStrings.push_back(std::make_pair("", -1));
+
+        // Parse elements recursively
+        std::vector<std::pair<std::string, int> >::const_iterator begin = stateStrings.begin();
+        parseStates(begin, this->rootStateNode_);
+    }
+
+    /*** Internal ***/
+
+    void Game::parseStates(std::vector<std::pair<std::string, int> >::const_iterator& it, shared_ptr<GameStateTreeNode> currentNode)
+    {
+        SubString tokens(it->first, ",");
+        std::vector<std::pair<std::string, int> >::const_iterator startIt = it;
+
+        for (unsigned int i = 0; i < tokens.size(); ++i)
+        {
+            it = startIt; // Reset iterator to the beginning of the sub tree
+            if (!this->checkState(tokens[i]))
+                ThrowException(GameState, "GameState with name '" << tokens[i] << "' not found!");
+            if (tokens[i] == this->rootStateNode_->name_)
                 ThrowException(GameState, "You shouldn't use 'emptyRootGameState' in the hierarchy...");
-            shared_ptr<GameStateTreeNode> newNode(new GameStateTreeNode);
-            newNode->name_ = newStateName;
-
-            if (newLevel <= currentLevel)
-            {
-                do
-                    currentNode = currentNode->parent_.lock();
-                while (newLevel <= --currentLevel);
-            }
-            if (newLevel == currentLevel + 1)
-            {
-                // Add the child
-                newNode->parent_ = currentNode;
-                currentNode->children_.push_back(newNode);
-            }
-            else
-                ThrowException(GameState, "Indentation error while parsing the hierarchy.");
-            currentNode = newNode;
-            currentLevel = newLevel;
-        }
-    }
-
-    /*** Internal ***/
+            shared_ptr<GameStateTreeNode> node(new GameStateTreeNode());
+            node->name_ = tokens[i];
+            node->parent_ = currentNode;
+            currentNode->children_.push_back(node);
+
+            int currentLevel = it->second;
+            ++it;
+            while (it->second != -1)
+            {
+                if (it->second <= currentLevel)
+                    break;
+                else if (it->second == currentLevel + 1)
+                    parseStates(it, node);
+                else
+                    ThrowException(GameState, "Indentation error while parsing the hierarchy.");
+            }
+        }
+    }
 
     void Game::loadGraphics()
     {
-        if (!GameMode::bShowsGraphics_s)
+        if (!GameMode::showsGraphics())
         {
             core_->loadGraphics();
             Loki::ScopeGuard graphicsUnloader = Loki::MakeObjGuard(*this, &Game::unloadGraphics);
-            GameMode::bShowsGraphics_s = true;
 
             // Construct all the GameStates that require graphics
@@ -531,5 +547,5 @@
     void Game::unloadGraphics()
     {
-        if (GameMode::bShowsGraphics_s)
+        if (GameMode::showsGraphics())
         {
             // Destroy all the GameStates that require graphics
@@ -543,5 +559,4 @@
 
             core_->unloadGraphics();
-            GameMode::bShowsGraphics_s = false;
         }
     }
@@ -607,10 +622,14 @@
     }
 
-    std::map<std::string, shared_ptr<Game::GameStateFactory> > Game::GameStateFactory::factories_s;
+    /*static*/ std::map<std::string, shared_ptr<Game::GameStateFactory> >& Game::GameStateFactory::getFactories()
+    {
+        static std::map<std::string, shared_ptr<GameStateFactory> > factories;
+        return factories;
+    }
 
     /*static*/ shared_ptr<GameState> Game::GameStateFactory::fabricate(const GameStateInfo& info)
     {
-        std::map<std::string, shared_ptr<Game::GameStateFactory> >::const_iterator it = factories_s.find(info.className);
-        assert(it != factories_s.end());
+        std::map<std::string, shared_ptr<Game::GameStateFactory> >::const_iterator it = getFactories().find(info.className);
+        assert(it != getFactories().end());
         return it->second->fabricateInternal(info);
     }
Index: code/trunk/src/libraries/core/Game.h
===================================================================
--- code/trunk/src/libraries/core/Game.h	(revision 5781)
+++ code/trunk/src/libraries/core/Game.h	(revision 5929)
@@ -117,8 +117,8 @@
             template <class T>
             static void createFactory(const std::string& className)
-                { factories_s[className].reset(new TemplateGameStateFactory<T>()); }
+                { getFactories()[className].reset(new TemplateGameStateFactory<T>()); }
 
             virtual shared_ptr<GameState> fabricateInternal(const GameStateInfo& info) = 0;
-            static std::map<std::string, shared_ptr<GameStateFactory> > factories_s;
+            static std::map<std::string, shared_ptr<GameStateFactory> >& getFactories();
         };
         template <class T>
@@ -143,4 +143,5 @@
         void unloadGraphics();
 
+        void parseStates(std::vector<std::pair<std::string, int> >::const_iterator& it, shared_ptr<GameStateTreeNode> currentNode);
         bool checkState(const std::string& name) const;
         void loadState(const std::string& name);
Index: code/trunk/src/libraries/core/GameMode.cc
===================================================================
--- code/trunk/src/libraries/core/GameMode.cc	(revision 5781)
+++ code/trunk/src/libraries/core/GameMode.cc	(revision 5929)
@@ -27,9 +27,4 @@
  */
 
-/**
-    @file
-    @brief Implementation of the GameMode class.
-*/
-
 #include "GameMode.h"
 
@@ -37,4 +32,5 @@
 {
     bool GameMode::bShowsGraphics_s = false;
+    bool GameMode::bPlaysSound_s    = false;
     bool GameMode::bHasServer_s     = false;
     bool GameMode::bIsClient_s      = false;
Index: code/trunk/src/libraries/core/GameMode.h
===================================================================
--- code/trunk/src/libraries/core/GameMode.h	(revision 5781)
+++ code/trunk/src/libraries/core/GameMode.h	(revision 5929)
@@ -41,8 +41,9 @@
     class _CoreExport GameMode
     {
-        friend class Game;
+        friend class Core;
 
         public:
             static bool showsGraphics() { return bShowsGraphics_s; }
+            static bool playsSound()    { return bPlaysSound_s; }
             static bool hasServer()     { return bHasServer_s; }
             static bool isClient()      { return bIsClient_s; }
@@ -50,4 +51,5 @@
             static bool isMaster()      { return bIsMaster_s; }
 
+            static void setPlaysSound   (bool val) { bPlaysSound_s    = val; }
             static void setHasServer    (bool val) { bHasServer_s     = val; updateIsMaster(); }
             static void setIsClient     (bool val) { bIsClient_s      = val; updateIsMaster(); }
@@ -65,4 +67,5 @@
 
             static bool bShowsGraphics_s;                   //!< global variable that tells whether to show graphics
+            static bool bPlaysSound_s;                      //!< global variable that tells whether to sound works
             static bool bHasServer_s;                       //!< global variable that tells whether this is a server
             static bool bIsClient_s;
Index: code/trunk/src/libraries/core/GameState.h
===================================================================
--- code/trunk/src/libraries/core/GameState.h	(revision 5781)
+++ code/trunk/src/libraries/core/GameState.h	(revision 5929)
@@ -40,4 +40,5 @@
 #include <map>
 #include <string>
+#include "util/UtilPrereqs.h"
 
 namespace orxonox
Index: code/trunk/src/libraries/core/GraphicsManager.cc
===================================================================
--- code/trunk/src/libraries/core/GraphicsManager.cc	(revision 5781)
+++ code/trunk/src/libraries/core/GraphicsManager.cc	(revision 5929)
@@ -48,16 +48,16 @@
 
 #include "SpecialConfig.h"
+#include "util/Clock.h"
 #include "util/Exception.h"
 #include "util/StringUtils.h"
 #include "util/SubString.h"
-#include "Clock.h"
 #include "ConsoleCommand.h"
 #include "ConfigValueIncludes.h"
 #include "CoreIncludes.h"
-#include "Core.h"
 #include "Game.h"
 #include "GameMode.h"
 #include "Loader.h"
 #include "MemoryArchive.h"
+#include "PathConfig.h"
 #include "WindowEventListener.h"
 #include "XMLFile.h"
@@ -102,5 +102,5 @@
 
         // At first, add the root paths of the data directories as resource locations
-        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(Core::getDataPathString(), "FileSystem", "dataRoot", false);
+        Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getDataPathString(), "FileSystem", "dataRoot", false);
         // Load resources
         resources_.reset(new XMLFile("resources.oxr", "dataRoot"));
@@ -109,7 +109,7 @@
 
         // Only for development runs
-        if (Core::isDevelopmentRun())
-        {
-            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(Core::getExternalDataPathString(), "FileSystem", "externalDataRoot", false);
+        if (PathConfig::isDevelopmentRun())
+        {
+            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(PathConfig::getExternalDataPathString(), "FileSystem", "externalDataRoot", false);
             extResources_.reset(new XMLFile("resources.oxr", "externalDataRoot"));
             extResources_->setLuaSupport(false);
@@ -130,6 +130,13 @@
     GraphicsManager::~GraphicsManager()
     {
+        Loader::unload(debugOverlay_.get());
+
         Ogre::WindowEventUtilities::removeWindowEventListener(renderWindow_, ogreWindowEventListener_.get());
         // TODO: Destroy the console command
+
+        // Undeclare the resources
+        Loader::unload(resources_.get());
+        if (PathConfig::isDevelopmentRun())
+            Loader::unload(extResources_.get());
     }
 
@@ -241,6 +248,6 @@
         }
 
-        boost::filesystem::path ogreConfigFilepath(Core::getConfigPath() / this->ogreConfigFile_);
-        boost::filesystem::path ogreLogFilepath(Core::getLogPath() / this->ogreLogFile_);
+        boost::filesystem::path ogreConfigFilepath(PathConfig::getConfigPath() / this->ogreConfigFile_);
+        boost::filesystem::path ogreLogFilepath(PathConfig::getLogPath() / this->ogreLogFile_);
 
         // create a new logManager
@@ -313,9 +320,24 @@
 
         // add console commands
-        FunctorMember<GraphicsManager>* functor1 = createFunctor(&GraphicsManager::printScreen);
-        ccPrintScreen_ = createConsoleCommand(functor1->setObject(this), "printScreen");
+        ccPrintScreen_ = createConsoleCommand(createFunctor(&GraphicsManager::printScreen, this), "printScreen");
         CommandExecutor::addConsoleCommandShortcut(ccPrintScreen_);
     }
 
+    void GraphicsManager::loadDebugOverlay()
+    {
+        // Load debug overlay to show info about fps and tick time
+        COUT(4) << "Loading Debug Overlay..." << std::endl;
+        debugOverlay_.reset(new XMLFile("debug.oxo"));
+        Loader::open(debugOverlay_.get());
+    }
+
+    /**
+    @note
+        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.
+    */
     void GraphicsManager::update(const Clock& time)
     {
@@ -418,5 +440,5 @@
         assert(this->renderWindow_);
        
-        this->renderWindow_->writeContentsToTimestampedFile(Core::getLogPathString() + "screenShot_", ".jpg");
+        this->renderWindow_->writeContentsToTimestampedFile(PathConfig::getLogPathString() + "screenShot_", ".jpg");
     }
 }
Index: code/trunk/src/libraries/core/GraphicsManager.h
===================================================================
--- code/trunk/src/libraries/core/GraphicsManager.h	(revision 5781)
+++ code/trunk/src/libraries/core/GraphicsManager.h	(revision 5929)
@@ -71,4 +71,5 @@
 
         void upgradeToGraphics();
+        void loadDebugOverlay();
         bool rendererLoaded() const { return renderWindow_ != NULL; }
 
@@ -99,7 +100,8 @@
         Ogre::Viewport*     viewport_;                 //!< default full size viewport
 
-        // XML files for the resources
+        // XML files for the resources and the debug overlay
         shared_ptr<XMLFile> resources_;                //!< XML with resource locations
         shared_ptr<XMLFile> extResources_;             //!< XML with resource locations in the external path (only for dev runs)
+        shared_ptr<XMLFile> debugOverlay_;             //!< XML with various debug overlays
 
         // config values
Index: code/trunk/src/libraries/core/Identifier.cc
===================================================================
--- code/trunk/src/libraries/core/Identifier.cc	(revision 5781)
+++ code/trunk/src/libraries/core/Identifier.cc	(revision 5929)
@@ -39,5 +39,5 @@
 #include "ConfigValueContainer.h"
 #include "ConsoleCommand.h"
-#include "Factory.h"
+#include "ClassFactory.h"
 #include "XMLPort.h"
 
@@ -61,12 +61,9 @@
         this->bSetName_ = false;
         this->factory_ = 0;
-        this->bLoadable_ = true;
+        this->bLoadable_ = false;
 
         this->bHasConfigValues_ = false;
         this->bHasConsoleCommands_ = false;
 
-        this->children_ = new std::set<const Identifier*>();
-        this->directChildren_ = new std::set<const Identifier*>();
-
         // Default network ID is the class ID
         this->networkID_ = this->classID_;
@@ -78,6 +75,4 @@
     Identifier::~Identifier()
     {
-        delete this->children_;
-        delete this->directChildren_;
         delete this->objects_;
 
@@ -118,5 +113,5 @@
             // There is already an entry: return it and delete the proposal
             delete proposal;
-            return (*it).second;
+            return it->second;
         }
         else
@@ -165,5 +160,5 @@
             {
                 // Tell the parent we're one of it's children
-                (*it)->getChildrenIntern().insert((*it)->getChildrenIntern().end(), this);
+                (*it)->children_.insert((*it)->children_.end(), this);
 
                 // Erase all parents of our parent from our direct-parent-list
@@ -187,5 +182,5 @@
             {
                 // Tell the parent we're one of it's direct children
-                (*it)->getDirectChildrenIntern().insert((*it)->getDirectChildrenIntern().end(), this);
+                (*it)->directChildren_.insert((*it)->directChildren_.end(), this);
 
                 // Create the super-function dependencies
@@ -196,4 +191,24 @@
 
     /**
+        @brief Creates the class-hierarchy by creating and destroying one object of each type.
+    */
+    void Identifier::createClassHierarchy()
+    {
+        COUT(3) << "*** Identifier: Create class-hierarchy" << std::endl;
+        Identifier::startCreatingHierarchy();
+        for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getStringIdentifierMap().begin(); it != Identifier::getStringIdentifierMap().end(); ++it)
+        {
+            // To create the new branch of the class-hierarchy, we create a new object and delete it afterwards.
+            if (it->second->hasFactory())
+            {
+                BaseObject* temp = it->second->fabricate(0);
+                temp->destroy();
+            }
+        }
+        Identifier::stopCreatingHierarchy();
+        COUT(3) << "*** Identifier: Finished class-hierarchy creation" << std::endl;
+    }
+
+    /**
         @brief Destroys all Identifiers. Called when exiting the program.
     */
@@ -214,6 +229,7 @@
             this->name_ = name;
             this->bSetName_ = true;
-            Identifier::getIdentifierMapIntern()[name] = this;
-            Identifier::getLowercaseIdentifierMapIntern()[getLowercase(name)] = this;
+            Identifier::getStringIdentifierMapIntern()[name] = this;
+            Identifier::getLowercaseStringIdentifierMapIntern()[getLowercase(name)] = this;
+            Identifier::getIDIdentifierMapIntern()[this->networkID_] = this;
         }
     }
@@ -235,15 +251,16 @@
             COUT(1) << "Aborting..." << std::endl;
             abort();
-            return NULL;
-        }
-    }
-
-    /**
-        @brief Sets the network ID to a new value and changes the entry in the Factory.
+            return 0;
+        }
+    }
+
+    /**
+        @brief Sets the network ID to a new value and changes the entry in the ID-Identifier-map.
         @param id The new network ID
     */
     void Identifier::setNetworkID(uint32_t id)
     {
-        Factory::changeNetworkID(this, this->networkID_, id);
+//        Identifier::getIDIdentifierMapIntern().erase(this->networkID_);
+        Identifier::getIDIdentifierMapIntern()[id] = this;
         this->networkID_ = id;
     }
@@ -291,5 +308,5 @@
     bool Identifier::isParentOf(const Identifier* identifier) const
     {
-        return (this->children_->find(identifier) != this->children_->end());
+        return (this->children_.find(identifier) != this->children_.end());
     }
 
@@ -300,12 +317,12 @@
     bool Identifier::isDirectParentOf(const Identifier* identifier) const
     {
-        return (this->directChildren_->find(identifier) != this->directChildren_->end());
-    }
-
-    /**
-        @brief Returns the map that stores all Identifiers.
+        return (this->directChildren_.find(identifier) != this->directChildren_.end());
+    }
+
+    /**
+        @brief Returns the map that stores all Identifiers with their names.
         @return The map
     */
-    std::map<std::string, Identifier*>& Identifier::getIdentifierMapIntern()
+    std::map<std::string, Identifier*>& Identifier::getStringIdentifierMapIntern()
     {
         static std::map<std::string, Identifier*> identifierMap;
@@ -314,11 +331,71 @@
 
     /**
-        @brief Returns the map that stores all Identifiers.
+        @brief Returns the map that stores all Identifiers with their names in lowercase.
         @return The map
     */
-    std::map<std::string, Identifier*>& Identifier::getLowercaseIdentifierMapIntern()
+    std::map<std::string, Identifier*>& Identifier::getLowercaseStringIdentifierMapIntern()
     {
         static std::map<std::string, Identifier*> lowercaseIdentifierMap;
         return lowercaseIdentifierMap;
+    }
+
+    /**
+        @brief Returns the map that stores all Identifiers with their network IDs.
+        @return The map
+    */
+    std::map<uint32_t, Identifier*>& Identifier::getIDIdentifierMapIntern()
+    {
+        static std::map<uint32_t, Identifier*> identifierMap;
+        return identifierMap;
+    }
+
+    /**
+        @brief Returns the Identifier with a given name.
+        @param name The name of the wanted Identifier
+        @return The Identifier
+    */
+    Identifier* Identifier::getIdentifierByString(const std::string& name)
+    {
+        std::map<std::string, Identifier*>::const_iterator it = Identifier::getStringIdentifierMapIntern().find(name);
+        if (it != Identifier::getStringIdentifierMapIntern().end())
+            return it->second;
+        else
+            return 0;
+    }
+
+    /**
+        @brief Returns the Identifier with a given name in lowercase.
+        @param name The name of the wanted Identifier
+        @return The Identifier
+    */
+    Identifier* Identifier::getIdentifierByLowercaseString(const std::string& name)
+    {
+        std::map<std::string, Identifier*>::const_iterator it = Identifier::getLowercaseStringIdentifierMapIntern().find(name);
+        if (it != Identifier::getLowercaseStringIdentifierMapIntern().end())
+            return it->second;
+        else
+            return 0;
+    }
+
+    /**
+        @brief Returns the Identifier with a given network ID.
+        @param id The network ID of the wanted Identifier
+        @return The Identifier
+    */
+    Identifier* Identifier::getIdentifierByID(const uint32_t id)
+    {
+        std::map<uint32_t, Identifier*>::const_iterator it = Identifier::getIDIdentifierMapIntern().find(id);
+        if (it != Identifier::getIDIdentifierMapIntern().end())
+            return it->second;
+        else
+            return 0;
+    }
+
+    /**
+        @brief Cleans the NetworkID map (needed on clients for correct initialization)
+    */
+    void Identifier::clearNetworkIDs()
+    {
+        Identifier::getIDIdentifierMapIntern().clear();
     }
 
@@ -351,5 +428,5 @@
         std::map<std::string, ConfigValueContainer*>::const_iterator it = configValues_.find(varname);
         if (it != configValues_.end())
-            return ((*it).second);
+            return it->second;
         else
             return 0;
@@ -365,5 +442,5 @@
         std::map<std::string, ConfigValueContainer*>::const_iterator it = configValues_LC_.find(varname);
         if (it != configValues_LC_.end())
-            return ((*it).second);
+            return it->second;
         else
             return 0;
@@ -404,5 +481,5 @@
         std::map<std::string, ConsoleCommand*>::const_iterator it = this->consoleCommands_.find(name);
         if (it != this->consoleCommands_.end())
-            return (*it).second;
+            return it->second;
         else
             return 0;
@@ -418,5 +495,5 @@
         std::map<std::string, ConsoleCommand*>::const_iterator it = this->consoleCommands_LC_.find(name);
         if (it != this->consoleCommands_LC_.end())
-            return (*it).second;
+            return it->second;
         else
             return 0;
@@ -432,5 +509,5 @@
         std::map<std::string, XMLPortParamContainer*>::const_iterator it = this->xmlportParamContainers_.find(paramname);
         if (it != this->xmlportParamContainers_.end())
-            return ((*it).second);
+            return it->second;
         else
             return 0;
@@ -463,5 +540,5 @@
         std::map<std::string, XMLPortObjectContainer*>::const_iterator it = this->xmlportObjectContainers_.find(sectionname);
         if (it != this->xmlportObjectContainers_.end())
-            return ((*it).second);
+            return it->second;
         else
             return 0;
@@ -483,35 +560,4 @@
 
         this->xmlportObjectContainers_[sectionname] = container;
-    }
-
-    /**
-        @brief Returns a XMLPortEventContainer that attaches an event to this class.
-        @param sectionname The name of the section that contains the event
-        @return The container
-    */
-    XMLPortObjectContainer* Identifier::getXMLPortEventContainer(const std::string& eventname)
-    {
-        std::map<std::string, XMLPortObjectContainer*>::const_iterator it = this->xmlportEventContainers_.find(eventname);
-        if (it != this->xmlportEventContainers_.end())
-            return ((*it).second);
-        else
-            return 0;
-    }
-
-    /**
-        @brief Adds a new XMLPortEventContainer that attaches an event to this class.
-        @param sectionname The name of the section that contains the event
-        @param container The container
-    */
-    void Identifier::addXMLPortEventContainer(const std::string& eventname, XMLPortObjectContainer* container)
-    {
-        std::map<std::string, XMLPortObjectContainer*>::const_iterator it = this->xmlportEventContainers_.find(eventname);
-        if (it != this->xmlportEventContainers_.end())
-        {
-            COUT(2) << "Warning: Overwriting XMLPortEventContainer in class " << this->getName() << "." << std::endl;
-            delete (it->second);
-        }
-
-        this->xmlportEventContainers_[eventname] = container;
     }
 
@@ -525,5 +571,9 @@
     {
         for (std::set<const Identifier*>::const_iterator it = list.begin(); it != list.end(); ++it)
-            out << (*it)->getName() << " ";
+        {
+            if (it != list.begin())
+                out << " ";
+            out << (*it)->getName();
+        }
 
         return out;
Index: code/trunk/src/libraries/core/Identifier.h
===================================================================
--- code/trunk/src/libraries/core/Identifier.h	(revision 5781)
+++ code/trunk/src/libraries/core/Identifier.h	(revision 5929)
@@ -29,5 +29,5 @@
 /**
     @file
-    @brief Definition of the Identifier, ClassIdentifier and SubclassIdentifier classes, implementation of the ClassIdentifier and SubclassIdentifier classes.
+    @brief Definition of the Identifier class, definition and implementation of the ClassIdentifier class.
 
     The Identifier contains all needed information about the class it belongs to:
@@ -45,7 +45,4 @@
 
     Every Identifier is in fact a ClassIdentifier, but they are derived from Identifier.
-
-    SubclassIdentifier is a separated class, acting like an Identifier, but has a given class.
-    You can only assign Identifiers of exactly the given class or of a derivative to a SubclassIdentifier.
 */
 
@@ -90,14 +87,31 @@
     class _CoreExport Identifier
     {
-        template <class T>
-        friend class SubclassIdentifier;
-
-        friend class Factory;
-
         public:
+            /** @brief Returns the name of the class the Identifier belongs to. @return The name */
+            inline const std::string& getName() const { return this->name_; }
+            void setName(const std::string& name);
+
+            /** @brief Returns the network ID to identify a class through the network. @return the network ID */
+            inline const uint32_t getNetworkID() const { return this->networkID_; }
+            void setNetworkID(uint32_t id);
+
+            /** @brief Returns the unique ID of the class */
+            FORCEINLINE unsigned int getClassID() const { return this->classID_; }
+
+            /** @brief Returns the list of all existing objects of this class. @return The list */
+            inline ObjectListBase* getObjects() const { return this->objects_; }
+
             /** @brief Sets the Factory. @param factory The factory to assign */
-            inline void addFactory(BaseFactory* factory) { this->factory_ = factory; }
+            inline void addFactory(Factory* factory) { this->factory_ = factory; }
+            /** @brief Returns true if the Identifier has a Factory. */
+            inline bool hasFactory() const { return (this->factory_ != 0); }
 
             BaseObject* fabricate(BaseObject* creator);
+
+            /** @brief Returns true if the class can be loaded through XML. */
+            inline bool isLoadable() const { return this->bLoadable_; }
+            /** @brief Set the class to be loadable through XML or not. */
+            inline void setLoadable(bool bLoadable) { this->bLoadable_ = bLoadable; }
+
             bool isA(const Identifier* identifier) const;
             bool isExactlyA(const Identifier* identifier) const;
@@ -107,18 +121,12 @@
             bool isDirectParentOf(const Identifier* identifier) const;
 
-            /** @brief Returns true if the class can be loaded through XML. */
-            inline bool isLoadable() const { return this->bLoadable_; }
-            /** @brief Set the class to be loadable through XML or not. */
-            inline void setLoadable(bool bLoadable) { this->bLoadable_ = bLoadable; }
-
-            /** @brief Returns the list of all existing objects of this class. @return The list */
-            inline ObjectListBase* getObjects() const
-                { return this->objects_; }
-
-            /** @brief Returns the name of the class the Identifier belongs to. @return The name */
-            inline const std::string& getName() const { return this->name_; }
-            void setName(const std::string& name);
-
-            virtual void updateConfigValues(bool updateChildren = true) const = 0;
+
+            /////////////////////////////
+            ////// Class Hierarchy //////
+            /////////////////////////////
+            static void createClassHierarchy();
+
+            /** @brief Returns true, if a branch of the class-hierarchy is being created, causing all new objects to store their parents. @return The status of the class-hierarchy creation */
+            inline static bool isCreatingHierarchy() { return (hierarchyCreatingCounter_s > 0); }
 
             /** @brief Returns the parents of the class the Identifier belongs to. @return The list of all parents */
@@ -130,9 +138,9 @@
 
             /** @brief Returns the children of the class the Identifier belongs to. @return The list of all children */
-            inline const std::set<const Identifier*>& getChildren() const { return (*this->children_); }
+            inline const std::set<const Identifier*>& getChildren() const { return this->children_; }
             /** @brief Returns the begin-iterator of the children-list. @return The begin-iterator */
-            inline std::set<const Identifier*>::const_iterator getChildrenBegin() const { return this->children_->begin(); }
+            inline std::set<const Identifier*>::const_iterator getChildrenBegin() const { return this->children_.begin(); }
             /** @brief Returns the end-iterator of the children-list. @return The end-iterator */
-            inline std::set<const Identifier*>::const_iterator getChildrenEnd() const { return this->children_->end(); }
+            inline std::set<const Identifier*>::const_iterator getChildrenEnd() const { return this->children_.end(); }
 
             /** @brief Returns the direct parents of the class the Identifier belongs to. @return The list of all direct parents */
@@ -144,25 +152,51 @@
 
             /** @brief Returns the direct children the class the Identifier belongs to. @return The list of all direct children */
-            inline const std::set<const Identifier*>& getDirectChildren() const { return (*this->directChildren_); }
+            inline const std::set<const Identifier*>& getDirectChildren() const { return this->directChildren_; }
             /** @brief Returns the begin-iterator of the direct-children-list. @return The begin-iterator */
-            inline std::set<const Identifier*>::const_iterator getDirectChildrenBegin() const { return this->directChildren_->begin(); }
+            inline std::set<const Identifier*>::const_iterator getDirectChildrenBegin() const { return this->directChildren_.begin(); }
             /** @brief Returns the end-iterator of the direct-children-list. @return The end-iterator */
-            inline std::set<const Identifier*>::const_iterator getDirectChildrenEnd() const { return this->directChildren_->end(); }
-
-
-            /** @brief Returns the map that stores all Identifiers. @return The map */
-            static inline const std::map<std::string, Identifier*>& getIdentifierMap() { return Identifier::getIdentifierMapIntern(); }
-            /** @brief Returns a const_iterator to the beginning of the map that stores all Identifiers. @return The const_iterator */
-            static inline std::map<std::string, Identifier*>::const_iterator getIdentifierMapBegin() { return Identifier::getIdentifierMap().begin(); }
-            /** @brief Returns a const_iterator to the end of the map that stores all Identifiers. @return The const_iterator */
-            static inline std::map<std::string, Identifier*>::const_iterator getIdentifierMapEnd() { return Identifier::getIdentifierMap().end(); }
+            inline std::set<const Identifier*>::const_iterator getDirectChildrenEnd() const { return this->directChildren_.end(); }
+
+
+            //////////////////////////
+            ///// Identifier Map /////
+            //////////////////////////
+            static void destroyAllIdentifiers();
+
+            static Identifier* getIdentifierByString(const std::string& name);
+            static Identifier* getIdentifierByLowercaseString(const std::string& name);
+            static Identifier* getIdentifierByID(uint32_t id);
+
+            static void clearNetworkIDs();
+
+            /** @brief Returns the map that stores all Identifiers with their names. @return The map */
+            static inline const std::map<std::string, Identifier*>& getStringIdentifierMap() { return Identifier::getStringIdentifierMapIntern(); }
+            /** @brief Returns a const_iterator to the beginning of the map that stores all Identifiers with their names. @return The const_iterator */
+            static inline std::map<std::string, Identifier*>::const_iterator getStringIdentifierMapBegin() { return Identifier::getStringIdentifierMap().begin(); }
+            /** @brief Returns a const_iterator to the end of the map that stores all Identifiers with their names. @return The const_iterator */
+            static inline std::map<std::string, Identifier*>::const_iterator getStringIdentifierMapEnd() { return Identifier::getStringIdentifierMap().end(); }
 
             /** @brief Returns the map that stores all Identifiers with their names in lowercase. @return The map */
-            static inline const std::map<std::string, Identifier*>& getLowercaseIdentifierMap() { return Identifier::getLowercaseIdentifierMapIntern(); }
+            static inline const std::map<std::string, Identifier*>& getLowercaseStringIdentifierMap() { return Identifier::getLowercaseStringIdentifierMapIntern(); }
             /** @brief Returns a const_iterator to the beginning of the map that stores all Identifiers with their names in lowercase. @return The const_iterator */
-            static inline std::map<std::string, Identifier*>::const_iterator getLowercaseIdentifierMapBegin() { return Identifier::getLowercaseIdentifierMap().begin(); }
+            static inline std::map<std::string, Identifier*>::const_iterator getLowercaseStringIdentifierMapBegin() { return Identifier::getLowercaseStringIdentifierMap().begin(); }
             /** @brief Returns a const_iterator to the end of the map that stores all Identifiers with their names in lowercase. @return The const_iterator */
-            static inline std::map<std::string, Identifier*>::const_iterator getLowercaseIdentifierMapEnd() { return Identifier::getLowercaseIdentifierMap().end(); }
-
+            static inline std::map<std::string, Identifier*>::const_iterator getLowercaseStringIdentifierMapEnd() { return Identifier::getLowercaseStringIdentifierMap().end(); }
+
+            /** @brief Returns the map that stores all Identifiers with their IDs. @return The map */
+            static inline const std::map<uint32_t, Identifier*>& getIDIdentifierMap() { return Identifier::getIDIdentifierMapIntern(); }
+            /** @brief Returns a const_iterator to the beginning of the map that stores all Identifiers with their IDs. @return The const_iterator */
+            static inline std::map<uint32_t, Identifier*>::const_iterator getIDIdentifierMapBegin() { return Identifier::getIDIdentifierMap().begin(); }
+            /** @brief Returns a const_iterator to the end of the map that stores all Identifiers with their IDs. @return The const_iterator */
+            static inline std::map<uint32_t, Identifier*>::const_iterator getIDIdentifierMapEnd() { return Identifier::getIDIdentifierMap().end(); }
+
+
+            /////////////////////////
+            ///// Config Values /////
+            /////////////////////////
+            virtual void updateConfigValues(bool updateChildren = true) const = 0;
+
+            /** @brief Returns true if this class has at least one config value. @return True if this class has at least one config value */
+            inline bool hasConfigValues() const { return this->bHasConfigValues_; }
 
             /** @brief Returns the map that stores all config values. @return The const_iterator */
@@ -180,4 +214,14 @@
             inline std::map<std::string, ConfigValueContainer*>::const_iterator getLowercaseConfigValueMapEnd() const { return this->configValues_LC_.end(); }
 
+            void addConfigValueContainer(const std::string& varname, ConfigValueContainer* container);
+            ConfigValueContainer* getConfigValueContainer(const std::string& varname);
+            ConfigValueContainer* getLowercaseConfigValueContainer(const std::string& varname);
+
+
+            ////////////////////////////
+            ///// Console Commands /////
+            ////////////////////////////
+            /** @brief Returns true if this class has at least one console command. @return True if this class has at least one console command */
+            inline bool hasConsoleCommands() const { return this->bHasConsoleCommands_; }
 
             /** @brief Returns the map that stores all console commands. @return The const_iterator */
@@ -195,4 +239,12 @@
             inline std::map<std::string, ConsoleCommand*>::const_iterator getLowercaseConsoleCommandMapEnd() const { return this->consoleCommands_LC_.end(); }
 
+            ConsoleCommand& addConsoleCommand(ConsoleCommand* command, bool bCreateShortcut);
+            ConsoleCommand* getConsoleCommand(const std::string& name) const;
+            ConsoleCommand* getLowercaseConsoleCommand(const std::string& name) const;
+
+
+            ///////////////////
+            ///// XMLPort /////
+            ///////////////////
             /** @brief Returns the map that stores all XMLPort params. @return The const_iterator */
             inline const std::map<std::string, XMLPortParamContainer*>& getXMLPortParamMap() const { return this->xmlportParamContainers_; }
@@ -209,32 +261,4 @@
             inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortObjectMapEnd() const { return this->xmlportObjectContainers_.end(); }
 
-            /** @brief Returns the map that stores all XMLPort events. @return The const_iterator */
-            inline const std::map<std::string, XMLPortObjectContainer*>& getXMLPortEventMap() const { return this->xmlportEventContainers_; }
-            /** @brief Returns a const_iterator to the beginning of the map that stores all XMLPort events. @return The const_iterator */
-            inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortEventMapBegin() const { return this->xmlportEventContainers_.begin(); }
-            /** @brief Returns a const_iterator to the end of the map that stores all XMLPort events. @return The const_iterator */
-            inline std::map<std::string, XMLPortObjectContainer*>::const_iterator getXMLPortEventMapEnd() const { return this->xmlportEventContainers_.end(); }
-
-            /** @brief Returns true if this class has at least one config value. @return True if this class has at least one config value */
-            inline bool hasConfigValues() const { return this->bHasConfigValues_; }
-            /** @brief Returns true if this class has at least one console command. @return True if this class has at least one console command */
-            inline bool hasConsoleCommands() const { return this->bHasConsoleCommands_; }
-
-            /** @brief Returns true, if a branch of the class-hierarchy is being created, causing all new objects to store their parents. @return The status of the class-hierarchy creation */
-            inline static bool isCreatingHierarchy() { return (hierarchyCreatingCounter_s > 0); }
-
-            /** @brief Returns the network ID to identify a class through the network. @return the network ID */
-            inline const uint32_t getNetworkID() const { return this->networkID_; }
-
-            /** @brief Sets the network ID to a new value. @param id The new value */
-            void setNetworkID(uint32_t id);
-
-            /** @brief Returns the unique ID of the class */
-            FORCEINLINE unsigned int getClassID() const { return this->classID_; }
-
-            void addConfigValueContainer(const std::string& varname, ConfigValueContainer* container);
-            ConfigValueContainer* getConfigValueContainer(const std::string& varname);
-            ConfigValueContainer* getLowercaseConfigValueContainer(const std::string& varname);
-
             void addXMLPortParamContainer(const std::string& paramname, XMLPortParamContainer* container);
             XMLPortParamContainer* getXMLPortParamContainer(const std::string& paramname);
@@ -243,14 +267,4 @@
             XMLPortObjectContainer* getXMLPortObjectContainer(const std::string& sectionname);
 
-            void addXMLPortEventContainer(const std::string& eventname, XMLPortObjectContainer* container);
-            XMLPortObjectContainer* getXMLPortEventContainer(const std::string& eventname);
-
-            ConsoleCommand& addConsoleCommand(ConsoleCommand* command, bool bCreateShortcut);
-            ConsoleCommand* getConsoleCommand(const std::string& name) const;
-            ConsoleCommand* getLowercaseConsoleCommand(const std::string& name) const;
-
-            void initializeClassHierarchy(std::set<const Identifier*>* parents, bool bRootClass);
-
-            static void destroyAllIdentifiers();
 
         protected:
@@ -262,34 +276,25 @@
             virtual void createSuperFunctionCaller() const = 0;
 
-            /** @brief Returns the map that stores all Identifiers. @return The map */
-            static std::map<std::string, Identifier*>& getIdentifierMapIntern();
+            void initializeClassHierarchy(std::set<const Identifier*>* parents, bool bRootClass);
+
+            /** @brief Returns the map that stores all Identifiers with their names. @return The map */
+            static std::map<std::string, Identifier*>& getStringIdentifierMapIntern();
             /** @brief Returns the map that stores all Identifiers with their names in lowercase. @return The map */
-            static std::map<std::string, Identifier*>& getLowercaseIdentifierMapIntern();
+            static std::map<std::string, Identifier*>& getLowercaseStringIdentifierMapIntern();
+            /** @brief Returns the map that stores all Identifiers with their network IDs. @return The map */
+            static std::map<uint32_t, Identifier*>& getIDIdentifierMapIntern();
 
             /** @brief Returns the children of the class the Identifier belongs to. @return The list of all children */
-            inline std::set<const Identifier*>& getChildrenIntern() const { return (*this->children_); }
+            inline std::set<const Identifier*>& getChildrenIntern() const { return this->children_; }
             /** @brief Returns the direct children of the class the Identifier belongs to. @return The list of all direct children */
-            inline std::set<const Identifier*>& getDirectChildrenIntern() const { return (*this->directChildren_); }
+            inline std::set<const Identifier*>& getDirectChildrenIntern() const { return this->directChildren_; }
 
             ObjectListBase* objects_;                                      //!< The list of all objects of this class
 
         private:
-            /**
-                @brief Increases the hierarchyCreatingCounter_s variable, causing all new objects to store their parents.
-            */
-            inline static void startCreatingHierarchy()
-            {
-                hierarchyCreatingCounter_s++;
-                COUT(4) << "*** Identifier: Increased Hierarchy-Creating-Counter to " << hierarchyCreatingCounter_s << std::endl;
-            }
-
-            /**
-                @brief Decreases the hierarchyCreatingCounter_s variable, causing the objects to stop storing their parents.
-            */
-            inline static void stopCreatingHierarchy()
-            {
-                hierarchyCreatingCounter_s--;
-                COUT(4) << "*** Identifier: Decreased Hierarchy-Creating-Counter to " << hierarchyCreatingCounter_s << std::endl;
-            }
+            /** @brief Increases the hierarchyCreatingCounter_s variable, causing all new objects to store their parents. */
+            inline static void startCreatingHierarchy() { hierarchyCreatingCounter_s++; }
+            /** @brief Decreases the hierarchyCreatingCounter_s variable, causing the objects to stop storing their parents. */
+            inline static void stopCreatingHierarchy()  { hierarchyCreatingCounter_s--; }
 
             static std::map<std::string, Identifier*>& getTypeIDIdentifierMap();
@@ -298,8 +303,8 @@
 
             std::set<const Identifier*> parents_;                          //!< The parents of the class the Identifier belongs to
-            std::set<const Identifier*>* children_;                        //!< The children of the class the Identifier belongs to
+            mutable std::set<const Identifier*> children_;                 //!< The children of the class the Identifier belongs to
 
             std::set<const Identifier*> directParents_;                    //!< The direct parents of the class the Identifier belongs to
-            std::set<const Identifier*>* directChildren_;                  //!< The direct children of the class the Identifier belongs to
+            mutable std::set<const Identifier*> directChildren_;           //!< The direct children of the class the Identifier belongs to
 
             bool bCreatedOneObject_;                                       //!< True if at least one object of the given type was created (used to determine the need of storing the parents)
@@ -307,5 +312,5 @@
             bool bLoadable_;                                               //!< False = it's not permitted to load the object through XML
             std::string name_;                                             //!< The name of the class the Identifier belongs to
-            BaseFactory* factory_;                                         //!< The Factory, able to create new objects of the given class (if available)
+            Factory* factory_;                                             //!< The Factory, able to create new objects of the given class (if available)
             static int hierarchyCreatingCounter_s;                         //!< Bigger than zero if at least one Identifier stores its parents (its an int instead of a bool to avoid conflicts with multithreading)
             uint32_t networkID_;                                           //!< The network ID to identify a class through the network
@@ -323,5 +328,4 @@
             std::map<std::string, XMLPortParamContainer*> xmlportParamContainers_;     //!< All loadable parameters
             std::map<std::string, XMLPortObjectContainer*> xmlportObjectContainers_;   //!< All attachable objects
-            std::map<std::string, XMLPortObjectContainer*> xmlportEventContainers_;    //!< All events
     };
 
@@ -348,6 +352,6 @@
 
         public:
-            static ClassIdentifier<T> *getIdentifier();
-            static ClassIdentifier<T> *getIdentifier(const std::string& name);
+            static ClassIdentifier<T>* getIdentifier();
+            static ClassIdentifier<T>* getIdentifier(const std::string& name);
 
             bool initialiseObject(T* object, const std::string& className, bool bRootClass);
@@ -380,6 +384,6 @@
     inline ClassIdentifier<T>* ClassIdentifier<T>::getIdentifier()
     {
-        // check if the static field has already been filled
-        if (ClassIdentifier<T>::classIdentifier_s == 0)
+        // check if the Identifier already exists
+        if (!ClassIdentifier<T>::classIdentifier_s)
             ClassIdentifier<T>::initialiseIdentifier();
 
@@ -508,153 +512,4 @@
 #endif
     }
-
-
-    // ###############################
-    // ###   SubclassIdentifier    ###
-    // ###############################
-    //! The SubclassIdentifier acts almost like an Identifier, but has some prerequisites.
-    /**
-        You can only assign an Identifier that belongs to a class T (or derived) to a SubclassIdentifier<T>.
-        If you assign something else, the program aborts.
-        Because we know the minimum type, a dynamic_cast is done, which makes it easier to create a new object.
-    */
-    template <class T>
-    class SubclassIdentifier
-    {
-        public:
-            /**
-                @brief Constructor: Automaticaly assigns the Identifier of the given class.
-            */
-            SubclassIdentifier()
-            {
-                this->identifier_ = ClassIdentifier<T>::getIdentifier();
-            }
-
-            /**
-                @brief Copyconstructor: Assigns the given Identifier.
-                @param identifier The Identifier
-            */
-            SubclassIdentifier(Identifier* identifier)
-            {
-                this->operator=(identifier);
-            }
-
-            /**
-                @brief Overloading of the = operator: assigns the identifier and checks its type.
-                @param identifier The Identifier to assign
-                @return The SubclassIdentifier itself
-            */
-            SubclassIdentifier<T>& operator=(Identifier* identifier)
-            {
-                if (!identifier || !identifier->isA(ClassIdentifier<T>::getIdentifier()))
-                {
-                    COUT(1) << "An error occurred in SubclassIdentifier (Identifier.h):" << std::endl;
-                    if (identifier)
-                    {
-                        COUT(1) << "Error: Class " << identifier->getName() << " is not a " << ClassIdentifier<T>::getIdentifier()->getName() << "!" << std::endl;
-                        COUT(1) << "Error: SubclassIdentifier<" << ClassIdentifier<T>::getIdentifier()->getName() << "> = Class(" << identifier->getName() << ") is forbidden." << std::endl;
-                    }
-                    else
-                    {
-                        COUT(1) << "Error: Can't assign NULL identifier" << std::endl;
-                    }
-                }
-                else
-                {
-                    this->identifier_ = identifier;
-                }
-                return *this;
-            }
-
-            /**
-                @brief Overloading of the * operator: returns the assigned identifier.
-            */
-            inline Identifier* operator*() const
-            {
-                return this->identifier_;
-            }
-
-            /**
-                @brief Overloading of the -> operator: returns the assigned identifier.
-            */
-            inline Identifier* operator->() const
-            {
-                return this->identifier_;
-            }
-
-            /**
-                @brief Returns the assigned identifier. This allows you to assign a SubclassIdentifier to a normal Identifier*.
-            */
-            inline operator Identifier*() const
-            {
-                return this->identifier_;
-            }
-
-            /**
-                @brief Creates a new object of the type of the assigned Identifier and dynamic_casts it to the minimal type given by T.
-                @return The new object
-            */
-            T* fabricate(BaseObject* creator) const
-            {
-                BaseObject* newObject = this->identifier_->fabricate(creator);
-
-                // Check if the creation was successful
-                if (newObject)
-                {
-                    return orxonox_cast<T*>(newObject);
-                }
-                else
-                {
-                    // Something went terribly wrong
-                    if (this->identifier_)
-                    {
-                        COUT(1) << "An error occurred in SubclassIdentifier (Identifier.h):" << std::endl;
-                        COUT(1) << "Error: Class " << this->identifier_->getName() << " is not a " << ClassIdentifier<T>::getIdentifier()->getName() << "!" << std::endl;
-                        COUT(1) << "Error: Couldn't fabricate a new Object." << std::endl;
-                        COUT(1) << "Aborting..." << std::endl;
-                    }
-                    else
-                    {
-                        COUT(1) << "An error occurred in SubclassIdentifier (Identifier.h):" << std::endl;
-                        COUT(1) << "Error: Couldn't fabricate a new Object - Identifier is undefined." << std::endl;
-                        COUT(1) << "Aborting..." << std::endl;
-                    }
-
-                    assert(false);
-                    return 0;
-                }
-            }
-
-            /** @brief Returns the assigned identifier. @return The identifier */
-            inline Identifier* getIdentifier() const
-                { return this->identifier_; }
-
-//            /** @brief Returns true, if the assigned identifier is at least of the given type. @param identifier The identifier to compare with */
-//            inline bool isA(const Identifier* identifier) const
-//                { return this->identifier_->isA(identifier); }
-//
-//            /** @brief Returns true, if the assigned identifier is exactly of the given type. @param identifier The identifier to compare with */
-//            inline bool isExactlyA(const Identifier* identifier) const
-//                { return this->identifier_->isExactlyA(identifier); }
-//
-//            /** @brief Returns true, if the assigned identifier is a child of the given identifier. @param identifier The identifier to compare with */
-//            inline bool isChildOf(const Identifier* identifier) const
-//                { return this->identifier_->isChildOf(identifier); }
-//
-//            /** @brief Returns true, if the assigned identifier is a direct child of the given identifier. @param identifier The identifier to compare with */
-//            inline bool isDirectChildOf(const Identifier* identifier) const
-//                { return this->identifier_->isDirectChildOf(identifier); }
-//
-//            /** @brief Returns true, if the assigned identifier is a parent of the given identifier. @param identifier The identifier to compare with */
-//            inline bool isParentOf(const Identifier* identifier) const
-//                { return this->identifier_->isParentOf(identifier); }
-//
-//            /** @brief Returns true, if the assigned identifier is a direct parent of the given identifier. @param identifier The identifier to compare with */
-//            inline bool isDirectParentOf(const Identifier* identifier) const
-//                { return this->identifier_->isDirectParentOf(identifier); }
-
-        private:
-            Identifier* identifier_;            //!< The assigned identifier
-    };
 }
 
Index: code/trunk/src/libraries/core/Iterator.h
===================================================================
--- code/trunk/src/libraries/core/Iterator.h	(revision 5781)
+++ code/trunk/src/libraries/core/Iterator.h	(revision 5929)
@@ -167,5 +167,4 @@
 
                 return (*this);
-                return *this;
             }
 
@@ -193,6 +192,5 @@
             inline const Iterator<T>& operator++()
             {
-                if (this->element_)
-                    this->element_ = this->element_->next_;
+                this->element_ = this->element_->next_;
                 return *this;
             }
@@ -205,6 +203,5 @@
             {
                 Iterator<T> copy = *this;
-                if (this->element_)
-                    this->element_ = this->element_->next_;
+                this->element_ = this->element_->next_;
                 return copy;
             }
@@ -216,6 +213,5 @@
             inline const Iterator<T>& operator--()
             {
-                if (this->element_)
-                    this->element_ = this->element_->prev_;
+                this->element_ = this->element_->prev_;
                 return *this;
             }
@@ -228,6 +224,5 @@
             {
                 Iterator<T> copy = *this;
-                if (this->element_)
-                    this->element_ = this->element_->prev_;
+                this->element_ = this->element_->prev_;
                 return copy;
             }
@@ -239,8 +234,5 @@
             inline T* operator*() const
             {
-                if (this->element_)
-                    return orxonox_cast<T*>(this->element_->objectBase_);
-                else
-                    return 0;
+                return orxonox_cast<T*>(this->element_->objectBase_);
             }
 
@@ -251,8 +243,5 @@
             inline T* operator->() const
             {
-                if (this->element_)
-                    return orxonox_cast<T*>(this->element_->objectBase_);
-                else
-                    return 0;
+                return orxonox_cast<T*>(this->element_->objectBase_);
             }
 
Index: code/trunk/src/libraries/core/Language.cc
===================================================================
--- code/trunk/src/libraries/core/Language.cc	(revision 5781)
+++ code/trunk/src/libraries/core/Language.cc	(revision 5929)
@@ -35,8 +35,7 @@
 
 #include <fstream>
-#include <boost/filesystem.hpp>
-
 #include "util/Debug.h"
 #include "Core.h"
+#include "PathConfig.h"
 
 namespace orxonox
@@ -200,14 +199,14 @@
         COUT(4) << "Read default language file." << std::endl;
 
-        boost::filesystem::path filepath(Core::getConfigPath() / getFilename(this->defaultLanguage_));
+        std::string filepath = PathConfig::getConfigPathString() + getFilename(this->defaultLanguage_);
 
         // This creates the file if it's not existing
         std::ofstream createFile;
-        createFile.open(filepath.string().c_str(), std::fstream::app);
+        createFile.open(filepath.c_str(), std::fstream::app);
         createFile.close();
 
         // Open the file
         std::ifstream file;
-        file.open(filepath.string().c_str(), std::fstream::in);
+        file.open(filepath.c_str(), std::fstream::in);
 
         if (!file.is_open())
@@ -249,9 +248,9 @@
         COUT(4) << "Read translated language file (" << Core::getLanguage() << ")." << std::endl;
 
-        boost::filesystem::path filepath(Core::getConfigPath() / getFilename(Core::getLanguage()));
+        std::string filepath = PathConfig::getConfigPathString() + getFilename(Core::getLanguage());
 
         // Open the file
         std::ifstream file;
-        file.open(filepath.string().c_str(), std::fstream::in);
+        file.open(filepath.c_str(), std::fstream::in);
 
         if (!file.is_open())
@@ -303,9 +302,9 @@
         COUT(4) << "Language: Write default language file." << std::endl;
 
-        boost::filesystem::path filepath(Core::getConfigPath() / getFilename(this->defaultLanguage_));
+        std::string filepath = PathConfig::getConfigPathString() + getFilename(this->defaultLanguage_);
 
         // Open the file
         std::ofstream file;
-        file.open(filepath.string().c_str(), std::fstream::out);
+        file.open(filepath.c_str(), std::fstream::out);
 
         if (!file.is_open())
Index: code/trunk/src/libraries/core/Loader.cc
===================================================================
--- code/trunk/src/libraries/core/Loader.cc	(revision 5781)
+++ code/trunk/src/libraries/core/Loader.cc	(revision 5929)
@@ -103,5 +103,5 @@
         {
             if (mask.isIncluded(it->getIdentifier()))
-                delete (*(it++));
+                (it++)->destroy();
             else
                 ++it;
@@ -204,5 +204,5 @@
         {
             if ((it->getFile() == file) && mask.isIncluded(it->getIdentifier()))
-                delete (*(it++));
+                (it++)->destroy();
             else
                 ++it;
Index: code/trunk/src/libraries/core/LuaState.cc
===================================================================
--- code/trunk/src/libraries/core/LuaState.cc	(revision 5781)
+++ code/trunk/src/libraries/core/LuaState.cc	(revision 5929)
@@ -37,5 +37,4 @@
 
 #include "util/Debug.h"
-#include "Core.h"
 #include "Resource.h"
 #include "ToluaBindCore.h"
Index: code/trunk/src/libraries/core/MemoryArchive.cc
===================================================================
--- code/trunk/src/libraries/core/MemoryArchive.cc	(revision 5781)
+++ code/trunk/src/libraries/core/MemoryArchive.cc	(revision 5929)
@@ -68,8 +68,8 @@
                 continue;
             if (bDirs)
-                file = file.parent_path();
+                file = file.branch_path();
             if (file.empty())
                 continue;
-            if (file.has_parent_path() && !bRecursive)
+            if (file.has_branch_path() && !bRecursive)
                 continue;
             if (simpleList)
@@ -80,6 +80,6 @@
                 fi.archive = this;
                 fi.filename = file.string();
-                fi.basename = file.filename();
-                fi.path = file.parent_path().string();
+                fi.basename = file.leaf();
+                fi.path = file.branch_path().string();
                 fi.compressedSize = it->second.second;
                 fi.uncompressedSize = it->second.second;
@@ -119,8 +119,8 @@
 
     bool MemoryArchive::exists(const String& filename)
-	{
+    {
         const FileMap& files = archives_s[this->getName()];
         return files.find(filename) != files.end();
-	}
+    }
 
     const Ogre::String& MemoryArchiveFactory::getType(void) const
Index: code/trunk/src/libraries/core/ObjectListIterator.h
===================================================================
--- code/trunk/src/libraries/core/ObjectListIterator.h	(revision 5781)
+++ code/trunk/src/libraries/core/ObjectListIterator.h	(revision 5929)
@@ -123,6 +123,5 @@
             inline const ObjectListIterator<T>& operator++()
             {
-                if (this->element_)
-                    this->element_ = static_cast<ObjectListElement<T>*>(this->element_->next_);
+                this->element_ = static_cast<ObjectListElement<T>*>(this->element_->next_);
                 return *this;
             }
@@ -135,6 +134,5 @@
             {
                 ObjectListIterator<T> copy = *this;
-                if (this->element_)
-                    this->element_ = static_cast<ObjectListElement<T>*>(this->element_->next_);
+                this->element_ = static_cast<ObjectListElement<T>*>(this->element_->next_);
                 return copy;
             }
@@ -146,6 +144,5 @@
             inline const ObjectListIterator<T>& operator--()
             {
-                if (this->element_)
-                    this->element_ = static_cast<ObjectListElement<T>*>(this->element_->prev_);
+                this->element_ = static_cast<ObjectListElement<T>*>(this->element_->prev_);
                 return *this;
             }
@@ -158,6 +155,5 @@
             {
                 ObjectListIterator<T> copy = *this;
-                if (this->element_)
-                    this->element_ = static_cast<ObjectListElement<T>*>(this->element_->prev_);
+                this->element_ = static_cast<ObjectListElement<T>*>(this->element_->prev_);
                 return copy;
             }
@@ -169,8 +165,5 @@
             inline T* operator*() const
             {
-                if (this->element_)
-                    return this->element_->object_;
-                else
-                    return 0;
+                return this->element_->object_;
             }
 
@@ -181,8 +174,5 @@
             inline T* operator->() const
             {
-                if (this->element_)
-                    return this->element_->object_;
-                else
-                    return 0;
+                return this->element_->object_;
             }
 
Index: code/trunk/src/libraries/core/OrxonoxClass.cc
===================================================================
--- code/trunk/src/libraries/core/OrxonoxClass.cc	(revision 5781)
+++ code/trunk/src/libraries/core/OrxonoxClass.cc	(revision 5929)
@@ -36,4 +36,5 @@
 #include "MetaObjectList.h"
 #include "Identifier.h"
+#include "WeakPtr.h"
 
 namespace orxonox
@@ -45,4 +46,6 @@
         this->parents_ = 0;
         this->metaList_ = new MetaObjectList();
+        this->referenceCount_ = 0;
+        this->requestedDestruction_ = false;
     }
 
@@ -50,4 +53,9 @@
     OrxonoxClass::~OrxonoxClass()
     {
+//        if (!this->requestedDestruction_)
+//            COUT(2) << "Warning: Destroyed object without destroy() (" << this->getIdentifier()->getName() << ")" << std::endl;
+
+        assert(this->referenceCount_ <= 0);
+
         delete this->metaList_;
 
@@ -55,4 +63,16 @@
         if (this->parents_)
             delete this->parents_;
+            
+        // reset all weak pointers pointing to this object
+        for (std::set<WeakPtr<OrxonoxClass>*>::iterator it = this->weakPointers_.begin(); it != this->weakPointers_.end(); )
+            (*(it++))->objectDeleted();
+    }
+
+    /** @brief Deletes the object if no smart pointers point to this object. Otherwise schedules the object to be deleted as soon as possible. */
+    void OrxonoxClass::destroy()
+    {
+        this->requestedDestruction_ = true;
+        if (this->referenceCount_ == 0)
+            delete this;
     }
 
@@ -78,44 +98,4 @@
 
     /** @brief Returns true if the objects class is of the given type or a derivative. */
-    template <class B> bool OrxonoxClass::isA(const SubclassIdentifier<B>* identifier)
-        { return this->getIdentifier()->isA(identifier->getIdentifier()); }
-    /** @brief Returns true if the objects class is exactly of the given type. */
-    template <class B> bool OrxonoxClass::isExactlyA(const SubclassIdentifier<B>* identifier)
-        { return this->getIdentifier()->isExactlyA(identifier->getIdentifier()); }
-    /** @brief Returns true if the objects class is a child of the given type. */
-    template <class B> bool OrxonoxClass::isChildOf(const SubclassIdentifier<B>* identifier)
-        { return this->getIdentifier()->isChildOf(identifier->getIdentifier()); }
-    /** @brief Returns true if the objects class is a direct child of the given type. */
-    template <class B> bool OrxonoxClass::isDirectChildOf(const SubclassIdentifier<B>* identifier)
-        { return this->getIdentifier()->isDirectChildOf(identifier->getIdentifier()); }
-    /** @brief Returns true if the objects class is a parent of the given type. */
-    template <class B> bool OrxonoxClass::isParentOf(const SubclassIdentifier<B>* identifier)
-        { return this->getIdentifier()->isParentOf(identifier->getIdentifier()); }
-    /** @brief Returns true if the objects class is a direct parent of the given type. */
-    template <class B> bool OrxonoxClass::isDirectParentOf(const SubclassIdentifier<B>* identifier)
-        { return this->getIdentifier()->isDirectParentOf(identifier->getIdentifier()); }
-
-
-    /** @brief Returns true if the objects class is of the given type or a derivative. */
-    template <class B> bool OrxonoxClass::isA(const SubclassIdentifier<B> identifier)
-        { return this->getIdentifier()->isA(identifier.getIdentifier()); }
-    /** @brief Returns true if the objects class is exactly of the given type. */
-    template <class B> bool OrxonoxClass::isExactlyA(const SubclassIdentifier<B> identifier)
-        { return this->getIdentifier()->isExactlyA(identifier.getIdentifier()); }
-    /** @brief Returns true if the objects class is a child of the given type. */
-    template <class B> bool OrxonoxClass::isChildOf(const SubclassIdentifier<B> identifier)
-        { return this->getIdentifier()->isChildOf(identifier.getIdentifier()); }
-    /** @brief Returns true if the objects class is a direct child of the given type. */
-    template <class B> bool OrxonoxClass::isDirectChildOf(const SubclassIdentifier<B> identifier)
-        { return this->getIdentifier()->isDirectChildOf(identifier.getIdentifier()); }
-    /** @brief Returns true if the objects class is a parent of the given type. */
-    template <class B> bool OrxonoxClass::isParentOf(const SubclassIdentifier<B> identifier)
-        { return this->getIdentifier()->isParentOf(identifier.getIdentifier()); }
-    /** @brief Returns true if the objects class is a direct parent of the given type. */
-    template <class B> bool OrxonoxClass::isDirectParentOf(const SubclassIdentifier<B> identifier)
-        { return this->getIdentifier()->isDirectParentOf(identifier.getIdentifier()); }
-
-
-    /** @brief Returns true if the objects class is of the given type or a derivative. */
     bool OrxonoxClass::isA(const OrxonoxClass* object)
         { return this->getIdentifier()->isA(object->getIdentifier()); }
Index: code/trunk/src/libraries/core/OrxonoxClass.h
===================================================================
--- code/trunk/src/libraries/core/OrxonoxClass.h	(revision 5781)
+++ code/trunk/src/libraries/core/OrxonoxClass.h	(revision 5929)
@@ -55,7 +55,15 @@
         friend class ClassIdentifier;
 
+        template <class T>
+        friend class SmartPtr;
+
+        template <class T>
+        friend class WeakPtr;
+
         public:
             OrxonoxClass();
             virtual ~OrxonoxClass();
+
+            void destroy();
 
             /** @brief Function to collect the SetConfigValue-macro calls. */
@@ -72,17 +80,16 @@
             bool isDirectParentOf(const Identifier* identifier);
 
-            template <class B> bool isA(const SubclassIdentifier<B>* identifier);
-            template <class B> bool isExactlyA(const SubclassIdentifier<B>* identifier);
-            template <class B> bool isChildOf(const SubclassIdentifier<B>* identifier);
-            template <class B> bool isDirectChildOf(const SubclassIdentifier<B>* identifier);
-            template <class B> bool isParentOf(const SubclassIdentifier<B>* identifier);
-            template <class B> bool isDirectParentOf(const SubclassIdentifier<B>* identifier);
-
-            template <class B> bool isA(const SubclassIdentifier<B> identifier);
-            template <class B> bool isExactlyA(const SubclassIdentifier<B> identifier);
-            template <class B> bool isChildOf(const SubclassIdentifier<B> identifier);
-            template <class B> bool isDirectChildOf(const SubclassIdentifier<B> identifier);
-            template <class B> bool isParentOf(const SubclassIdentifier<B> identifier);
-            template <class B> bool isDirectParentOf(const SubclassIdentifier<B> identifier);
+            template <class B> inline bool isA(const SubclassIdentifier<B>* identifier)
+                { return this->isA(*identifier); }
+            template <class B> inline bool isExactlyA(const SubclassIdentifier<B>* identifier)
+                { return this->isExactlyA(*identifier); }
+            template <class B> inline bool isChildOf(const SubclassIdentifier<B>* identifier)
+                { return this->isChildOf(*identifier); }
+            template <class B> inline bool isDirectChildOf(const SubclassIdentifier<B>* identifier)
+                { return this->isDirectChildOf(*identifier); }
+            template <class B> inline bool isParentOf(const SubclassIdentifier<B>* identifier)
+                { return this->isParentOf(*identifier); }
+            template <class B> inline bool isDirectParentOf(const SubclassIdentifier<B>* identifier)
+                { return this->isDirectParentOf(*identifier); }
 
             bool isA(const OrxonoxClass* object);
@@ -93,4 +100,7 @@
             bool isDirectParentOf(const OrxonoxClass* object);
 
+            inline unsigned int getReferenceCount() const
+                { return this->referenceCount_; }
+
             /**
             @brief
@@ -100,25 +110,45 @@
                 Returns NULL if the no pointer was found.
             */
-            template <class T>
-            FORCEINLINE T* getDerivedPointer(unsigned int classID)
+            FORCEINLINE void* getDerivedPointer(unsigned int classID)
             {
                 for (int i = this->objectPointers_.size() - 1; i >= 0; --i)
                 {
                     if (this->objectPointers_[i].first == classID)
-                        return static_cast<T*>(this->objectPointers_[i].second);
+                        return this->objectPointers_[i].second;
                 }
                 return NULL;
             }
-            //! Const version of getDerivedPointer
-            template <class T>
-            FORCEINLINE const T* getDerivedPointer(unsigned int classID) const
-            {
-                return const_cast<OrxonoxClass*>(this)->getDerivedPointer<T>(classID);
-            }
+
+            //! Version of getDerivedPointer with template
+            template <class T> FORCEINLINE T* getDerivedPointer(unsigned int classID)
+            {   return static_cast<T*>(this->getDerivedPointer(classID));   }
+            //! Const version of getDerivedPointer with template
+            template <class T> FORCEINLINE const T* getDerivedPointer(unsigned int classID) const
+            {   return const_cast<OrxonoxClass*>(this)->getDerivedPointer<T>(classID);   }
 
         private:
+            /** @brief Increments the reference counter (for smart pointers). */
+            inline void incrementReferenceCount()
+                { ++this->referenceCount_; }
+            /** @brief Decrements the reference counter (for smart pointers). */
+            inline void decrementReferenceCount()
+                { --this->referenceCount_; if (this->referenceCount_ == 0 && this->requestedDestruction_) { delete this; } }
+                
+            /** @brief Register a weak pointer which points to this object. */
+            template <class T>
+            inline void registerWeakPtr(WeakPtr<T>* pointer)
+                { this->weakPointers_.insert(reinterpret_cast<WeakPtr<OrxonoxClass>*>(pointer)); }
+            /** @brief Unegister a weak pointer which pointed to this object before. */
+            template <class T>
+            inline void unregisterWeakPtr(WeakPtr<T>* pointer)
+                { this->weakPointers_.erase(reinterpret_cast<WeakPtr<OrxonoxClass>*>(pointer)); }
+
             Identifier* identifier_;                   //!< The Identifier of the object
             std::set<const Identifier*>* parents_;     //!< List of all parents of the object
             MetaObjectList* metaList_;                 //!< MetaObjectList, containing all ObjectLists and ObjectListElements the object is registered in
+            int referenceCount_;                       //!< Counts the references from smart pointers to this object
+            bool requestedDestruction_;                //!< Becomes true after someone called delete on this object
+            std::set<WeakPtr<OrxonoxClass>*> weakPointers_; //!< All weak pointers which point to this object (and like to get notified if it dies)
+
             //! 'Fast map' that holds this-pointers of all derived types
             std::vector<std::pair<unsigned int, void*> > objectPointers_;
Index: code/trunk/src/libraries/core/PathConfig.cc
===================================================================
--- code/trunk/src/libraries/core/PathConfig.cc	(revision 5929)
+++ code/trunk/src/libraries/core/PathConfig.cc	(revision 5929)
@@ -0,0 +1,323 @@
+/*
+ *   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:
+ *      ...
+ *
+ */
+
+#include "PathConfig.h"
+
+#include <cassert>
+#include <cstdlib>
+#include <cstdio>
+#include <vector>
+#include <boost/version.hpp>
+#include <boost/filesystem.hpp>
+
+#ifdef ORXONOX_PLATFORM_WINDOWS
+#  ifndef WIN32_LEAN_AND_MEAN
+#    define WIN32_LEAN_AND_MEAN
+#  endif
+#  include <windows.h>
+#  undef min
+#  undef max
+#elif defined(ORXONOX_PLATFORM_APPLE)
+#  include <sys/param.h>
+#  include <mach-o/dyld.h>
+#else /* Linux */
+#  include <sys/types.h>
+#  include <unistd.h>
+#endif
+
+#include "SpecialConfig.h"
+#include "util/Debug.h"
+#include "util/Exception.h"
+#include "CommandLine.h"
+
+// Boost 1.36 has some issues with deprecated functions that have been omitted
+#if (BOOST_VERSION == 103600)
+#  define BOOST_LEAF_FUNCTION filename
+#else
+#  define BOOST_LEAF_FUNCTION leaf
+#endif
+
+namespace orxonox
+{
+    namespace bf = boost::filesystem;
+
+    //! Static pointer to the singleton
+    PathConfig* PathConfig::singletonPtr_s  = 0;
+
+    SetCommandLineArgument(externalDataPath, "").information("Path to the external data files");
+    SetCommandLineOnlyArgument(writingPathSuffix, "").information("Additional subfolder for config and log files");
+
+    PathConfig::PathConfig()
+        : rootPath_(*(new bf::path()))
+        , executablePath_(*(new bf::path()))
+        , modulePath_(*(new bf::path()))
+        , dataPath_(*(new bf::path()))
+        , externalDataPath_(*(new bf::path()))
+        , configPath_(*(new bf::path()))
+        , logPath_(*(new bf::path()))
+        , bDevRun_(false)
+    {
+        //////////////////////////
+        // FIND EXECUTABLE PATH //
+        //////////////////////////
+
+#ifdef ORXONOX_PLATFORM_WINDOWS
+        // get executable module
+        TCHAR buffer[1024];
+        if (GetModuleFileName(NULL, buffer, 1024) == 0)
+            ThrowException(General, "Could not retrieve executable path.");
+
+#elif defined(ORXONOX_PLATFORM_APPLE)
+        char buffer[1024];
+        unsigned long path_len = 1023;
+        if (_NSGetExecutablePath(buffer, &path_len))
+            ThrowException(General, "Could not retrieve executable path.");
+
+#else /* Linux */
+        /* written by Nicolai Haehnle <prefect_@gmx.net> */
+
+        /* Get our PID and build the name of the link in /proc */
+        char linkname[64]; /* /proc/<pid>/exe */
+        if (snprintf(linkname, sizeof(linkname), "/proc/%i/exe", getpid()) < 0)
+        {
+            /* This should only happen on large word systems. I'm not sure
+               what the proper response is here.
+               Since it really is an assert-like condition, aborting the
+               program seems to be in order. */
+            assert(false);
+        }
+
+        /* Now read the symbolic link */
+        char buffer[1024];
+        int ret;
+        ret = readlink(linkname, buffer, 1024);
+        /* In case of an error, leave the handling up to the caller */
+        if (ret == -1)
+            ThrowException(General, "Could not retrieve executable path.");
+
+        /* Ensure proper NUL termination */
+        buffer[ret] = 0;
+#endif
+
+        executablePath_ = bf::path(buffer);
+#ifndef ORXONOX_PLATFORM_APPLE
+        executablePath_ = executablePath_.branch_path(); // remove executable name
+#endif
+
+        /////////////////////
+        // SET MODULE PATH //
+        /////////////////////
+
+        if (bf::exists(executablePath_ / "orxonox_dev_build.keep_me"))
+        {
+            COUT(1) << "Running from the build tree." << std::endl;
+            PathConfig::bDevRun_ = true;
+            modulePath_ = specialConfig::moduleDevDirectory;
+        }
+        else
+        {
+
+#ifdef INSTALL_COPYABLE // --> relative paths
+
+            // Also set the root path
+            bf::path relativeExecutablePath(specialConfig::defaultRuntimePath);
+            rootPath_ = executablePath_;
+            while (!bf::equivalent(rootPath_ / relativeExecutablePath, executablePath_) && !rootPath_.empty())
+                rootPath_ = rootPath_.branch_path();
+            if (rootPath_.empty())
+                ThrowException(General, "Could not derive a root directory. Might the binary installation directory contain '..' when taken relative to the installation prefix path?");
+
+            // Module path is fixed as well
+            modulePath_ = rootPath_ / specialConfig::defaultModulePath;
+
+#else
+
+            // There is no root path, so don't set it at all
+            // Module path is fixed as well
+            modulePath_ = specialConfig::moduleInstallDirectory;
+
+#endif
+        }
+    }
+
+    PathConfig::~PathConfig()
+    {
+        delete &rootPath_;
+        delete &executablePath_;
+        delete &modulePath_;
+        delete &dataPath_;
+        delete &externalDataPath_;
+        delete &configPath_;
+        delete &logPath_;
+    }
+
+    void PathConfig::setConfigurablePaths()
+    {
+        if (bDevRun_)
+        {
+            dataPath_         = specialConfig::dataDevDirectory;
+            configPath_       = specialConfig::configDevDirectory;
+            logPath_          = specialConfig::logDevDirectory;
+
+            // Check for data path override by the command line
+            if (!CommandLine::getArgument("externalDataPath")->hasDefaultValue())
+                externalDataPath_ = CommandLine::getValue("externalDataPath").getString();
+            else
+                externalDataPath_ = specialConfig::externalDataDevDirectory;
+        }
+        else
+        {
+
+#ifdef INSTALL_COPYABLE // --> relative paths
+
+            // Using paths relative to the install prefix, complete them
+            dataPath_   = rootPath_ / specialConfig::defaultDataPath;
+            configPath_ = rootPath_ / specialConfig::defaultConfigPath;
+            logPath_    = rootPath_ / specialConfig::defaultLogPath;
+
+#else
+
+            dataPath_  = specialConfig::dataInstallDirectory;
+
+            // Get user directory
+#  ifdef ORXONOX_PLATFORM_UNIX /* Apple? */
+            char* userDataPathPtr(getenv("HOME"));
+#  else
+            char* userDataPathPtr(getenv("APPDATA"));
+#  endif
+            if (userDataPathPtr == NULL)
+                ThrowException(General, "Could not retrieve user data path.");
+            bf::path userDataPath(userDataPathPtr);
+            userDataPath /= ".orxonox";
+
+            configPath_ = userDataPath / specialConfig::defaultConfigPath;
+            logPath_    = userDataPath / specialConfig::defaultLogPath;
+
+#endif
+
+        }
+
+        // Option to put all the config and log files in a separate folder
+        if (!CommandLine::getArgument("writingPathSuffix")->hasDefaultValue())
+        {
+            std::string directory(CommandLine::getValue("writingPathSuffix").getString());
+            configPath_ = configPath_ / directory;
+            logPath_    = logPath_    / directory;
+        }
+
+        // Create directories to avoid problems when opening files in non existent folders.
+        std::vector<std::pair<bf::path, std::string> > directories;
+        directories.push_back(std::make_pair(bf::path(configPath_), "config"));
+        directories.push_back(std::make_pair(bf::path(logPath_), "log"));
+
+        for (std::vector<std::pair<bf::path, std::string> >::iterator it = directories.begin();
+            it != directories.end(); ++it)
+        {
+            if (bf::exists(it->first) && !bf::is_directory(it->first))
+            {
+                ThrowException(General, std::string("The ") + it->second + " directory has been preoccupied by a file! \
+                                         Please remove " + it->first.string());
+            }
+            if (bf::create_directories(it->first)) // function may not return true at all (bug?)
+            {
+                COUT(4) << "Created " << it->second << " directory" << std::endl;
+            }
+        }
+    }
+
+    std::vector<std::string> PathConfig::getModulePaths()
+    {
+        std::vector<std::string> modulePaths;
+
+        // We search for helper files with the following extension
+        std::string moduleextension = specialConfig::moduleExtension;
+        size_t moduleextensionlength = moduleextension.size();
+
+        // Add that path to the PATH variable in case a module depends on another one
+        std::string pathVariable = getenv("PATH");
+        putenv(const_cast<char*>(("PATH=" + pathVariable + ";" + modulePath_.string()).c_str()));
+
+        boost::filesystem::directory_iterator file(modulePath_);
+        boost::filesystem::directory_iterator end;
+
+        // Iterate through all files
+        while (file != end)
+        {
+            std::string filename = file->BOOST_LEAF_FUNCTION();
+
+            // Check if the file ends with the exension in question
+            if (filename.size() > moduleextensionlength)
+            {
+                if (filename.substr(filename.size() - moduleextensionlength) == moduleextension)
+                {
+                    // We've found a helper file
+                    std::string library = filename.substr(0, filename.size() - moduleextensionlength);
+                    modulePaths.push_back((modulePath_ / library).file_string());
+                }
+            }
+            ++file;
+        }
+
+        return modulePaths;
+    }
+
+    /*static*/ std::string PathConfig::getRootPathString()
+    {
+        return getInstance().rootPath_.string() + '/';
+    }
+
+    /*static*/ std::string PathConfig::getExecutablePathString()
+    {
+        return getInstance().executablePath_.string() + '/';
+    }
+
+    /*static*/ std::string PathConfig::getDataPathString()
+    {
+        return getInstance().dataPath_.string() + '/';
+    }
+
+    /*static*/ std::string PathConfig::getExternalDataPathString()
+    {
+        return getInstance().externalDataPath_.string() + '/';
+    }
+
+    /*static*/ std::string PathConfig::getConfigPathString()
+    {
+        return getInstance().configPath_.string() + '/';
+    }
+
+    /*static*/ std::string PathConfig::getLogPathString()
+    {
+        return getInstance().logPath_.string() + '/';
+    }
+
+    /*static*/ std::string PathConfig::getModulePathString()
+    {
+        return getInstance().modulePath_.string() + '/';
+    }
+}
Index: code/trunk/src/libraries/core/PathConfig.h
===================================================================
--- code/trunk/src/libraries/core/PathConfig.h	(revision 5929)
+++ code/trunk/src/libraries/core/PathConfig.h	(revision 5929)
@@ -0,0 +1,137 @@
+/*
+ *   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:
+ *      ...
+ *
+ */
+
+#ifndef _PathConfig_H__
+#define _PathConfig_H__
+
+#include "CorePrereqs.h"
+
+#include <string>
+#include <vector>
+#include "util/Singleton.h"
+
+namespace orxonox
+{
+    /**
+    @brief
+        The PathConfig class is a singleton used to configure different paths.
+    @details
+        The class provides information about the data, config, log, executable,
+        root and module path.
+        It determines those by the use of platform specific functions.
+    @remarks
+        Not all paths are always available:
+        - root only when installed copyable
+        - externalData only for development builds in the build tree
+    */
+    class _CoreExport PathConfig : public Singleton<PathConfig>
+    {
+        friend class Singleton<PathConfig>;
+        friend class Core;
+
+        public:
+            /**
+            @brief
+                Retrievs the executable path and sets all hard coded fixed paths (currently only the module path)
+                Also checks for "orxonox_dev_build.keep_me" in the executable diretory.
+                If found it means that this is not an installed run, hence we
+                don't write the logs and config files to ~/.orxonox
+            @throw
+                GeneralException
+            */
+            PathConfig();
+            ~PathConfig();
+
+            //! Returns the path to the root folder as boost::filesystem::path
+            static const boost::filesystem::path& getRootPath()
+                { return getInstance().rootPath_; }
+            //! Returns the path to the executable folder as boost::filesystem::path
+            static const boost::filesystem::path& getExecutablePath()
+                { return getInstance().executablePath_; }
+            //! Returns the path to the data files as boost::filesystem::path
+            static const boost::filesystem::path& getDataPath()
+                { return getInstance().dataPath_; }
+            //! Returns the path to the external data files as boost::filesystem::path
+            static const boost::filesystem::path& getExternalDataPath()
+                { return getInstance().externalDataPath_; }
+            //! Returns the path to the config files as boost::filesystem::path
+            static const boost::filesystem::path& getConfigPath()
+                { return getInstance().configPath_; }
+            //! Returns the path to the log files as boost::filesystem::path
+            static const boost::filesystem::path& getLogPath()
+                { return getInstance().logPath_; }
+            //! Returns the path to the modules as boost::filesystem::path
+            static const boost::filesystem::path& getModulePath()
+                { return getInstance().modulePath_; }
+
+            //! Returns the path to the root folder as std::string
+            static std::string getRootPathString();
+            //! Returns the path to the executable folder as std::string
+            static std::string getExecutablePathString();
+            //! Returns the path to the data files as std::string
+            static std::string getDataPathString();
+            //! Returns the path to the external data files as std::string
+            static std::string getExternalDataPathString();
+            //! Returns the path to the config files as std::string
+            static std::string getConfigPathString();
+            //! Returns the path to the log files as std::string
+            static std::string getLogPathString();
+            //! Returns the path to the modules as std::string
+            static std::string getModulePathString();
+
+            //! Return trrue for runs in the build directory (not installed)
+            static bool isDevelopmentRun() { return getInstance().bDevRun_; }
+
+        private:
+            PathConfig(const PathConfig&); //!< Don't use (undefined symbol)
+
+            /**
+            @brief
+                Sets config, log and media path and creates the folders if necessary.
+            @throws
+                GeneralException
+            */
+            void setConfigurablePaths();
+            //! Returns a list with all modules declared by a *.module file in the module folder.
+            std::vector<std::string> getModulePaths();
+
+            //! Path to the parent directory of the ones above if program was installed with relativ paths
+            boost::filesystem::path& rootPath_;
+            boost::filesystem::path& executablePath_;        //!< Path to the executable
+            boost::filesystem::path& modulePath_;            //!< Path to the modules
+            boost::filesystem::path& dataPath_;              //!< Path to the data files folder
+            boost::filesystem::path& externalDataPath_;      //!< Path to the external data files folder
+            boost::filesystem::path& configPath_;            //!< Path to the config files folder
+            boost::filesystem::path& logPath_;               //!< Path to the log files folder
+
+            bool                     bDevRun_;               //!< True for runs in the build directory (not installed)
+            static PathConfig* singletonPtr_s;
+    };
+}
+
+#endif /* _PathConfig_H__ */
Index: code/trunk/src/libraries/core/Resource.h
===================================================================
--- code/trunk/src/libraries/core/Resource.h	(revision 5781)
+++ code/trunk/src/libraries/core/Resource.h	(revision 5929)
@@ -64,5 +64,5 @@
         // Docs by Ogre::ResourceGroupManager.h
     public:
-		/**
+        /**
         @brief
             Open a single resource by name and return a DataStream
@@ -81,10 +81,10 @@
             Shared pointer to data stream containing the data. Will be
             destroyed automatically when no longer referenced.
-		*/
+        */
         static DataStreamPtr open(const std::string& name,
             const std::string& group = Resource::DEFAULT_GROUP,
             bool bSearchGroupsIfNotFound = false);
 
-		/**
+        /**
         @brief
             Open all resources matching a given pattern (which can contain
@@ -101,5 +101,5 @@
             Shared pointer to a data stream list , will be
             destroyed automatically when no longer referenced
-		*/
+        */
         static DataStreamListPtr openMulti(const std::string& pattern, const std::string& group = Resource::DEFAULT_GROUP);
 
Index: code/trunk/src/libraries/core/ScopedSingletonManager.cc
===================================================================
--- code/trunk/src/libraries/core/ScopedSingletonManager.cc	(revision 5929)
+++ code/trunk/src/libraries/core/ScopedSingletonManager.cc	(revision 5929)
@@ -0,0 +1,59 @@
+/*
+ *   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:
+ *      ...
+ *
+ */
+
+#include "ScopedSingletonManager.h"
+
+namespace orxonox
+{
+    /*static*/ std::map<std::string, ScopedSingletonManager*>& ScopedSingletonManager::getManagers()
+    {
+        static std::map<std::string, ScopedSingletonManager*> managers;
+        return managers;
+    }
+    /*static*/ ScopedSingletonManager::ManagerMultiMap& ScopedSingletonManager::getManagersByScope()
+    {
+        static ManagerMultiMap managers;
+        return managers;
+    }
+
+    /*static*/ void ScopedSingletonManager::addManager(ScopedSingletonManager* manager)
+    {
+        getManagers()[manager->className_] = manager;
+        getManagersByScope().insert(std::make_pair(manager->scope_, manager));
+    }
+
+    /*static*/ void ScopedSingletonManager::removeManager(ScopedSingletonManager* manager)
+    {
+        getManagers().erase(getManagers().find(manager->className_));
+        for (ManagerMultiMap::iterator it = getManagersByScope().lower_bound(manager->scope_); it != getManagersByScope().upper_bound(manager->scope_);)
+            if (it->second == manager)
+                getManagersByScope().erase(it++);
+            else
+                ++it;
+    }
+}
Index: code/trunk/src/libraries/core/ScopedSingletonManager.h
===================================================================
--- code/trunk/src/libraries/core/ScopedSingletonManager.h	(revision 5929)
+++ code/trunk/src/libraries/core/ScopedSingletonManager.h	(revision 5929)
@@ -0,0 +1,189 @@
+/*
+ *   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:
+ *      ...
+ *
+ */
+
+#ifndef __ScopedSingletonManager_H__
+#define __ScopedSingletonManager_H__
+
+#include "CorePrereqs.h"
+
+#include <cassert>
+#include <map>
+#include "util/Exception.h"
+#include "util/Scope.h"
+#include "util/Singleton.h"
+
+#define ManageScopedSingleton(className, scope, allowedToFail) \
+    static ClassScopedSingletonManager<className, scope, allowedToFail> className##ScopedSingletonManager(#className)
+
+namespace orxonox
+{
+    class _CoreExport ScopedSingletonManager
+    {
+        public:
+            ScopedSingletonManager(const std::string& className, ScopeID::Value scope)
+                : className_(className)
+                , scope_(scope)
+            { }
+            virtual ~ScopedSingletonManager() { }
+            static void addManager(ScopedSingletonManager* manager);
+            static void removeManager(ScopedSingletonManager* manager);
+
+            template<ScopeID::Value scope>
+            static void update(const Clock& time)
+            {
+                assert(Scope<scope>::isActive());
+                for (ManagerMultiMap::iterator it = getManagersByScope().lower_bound(scope); it != getManagersByScope().upper_bound(scope); ++it)
+                    it->second->update(time);
+            }
+            virtual void update(const Clock& time) = 0;
+
+            static std::map<std::string, ScopedSingletonManager*>& getManagers();
+            typedef std::multimap<ScopeID::Value, ScopedSingletonManager*> ManagerMultiMap;
+            static ManagerMultiMap& getManagersByScope();
+
+        protected:
+            const std::string className_;
+            const ScopeID::Value scope_;
+    };
+
+    template <class T, ScopeID::Value scope, bool allowedToFail>
+    class ClassScopedSingletonManager : public ScopedSingletonManager, public ScopeListener
+    {
+    public:
+        ClassScopedSingletonManager(const std::string& className)
+            : ScopedSingletonManager(className, scope)
+            , ScopeListener(scope)
+            , singletonPtr_(NULL)
+        {
+            ScopedSingletonManager::addManager(this);
+        }
+
+        ~ClassScopedSingletonManager()
+        {
+            //assert(singletonPtr_ == NULL); // Might get triggered in the SignalHandler
+            ScopedSingletonManager::removeManager(this);
+        }
+
+        //! Called if the Scope of the Singleton gets active (creates the instance)
+        void activated()
+        {
+            assert(singletonPtr_ == NULL);
+            singletonPtr_ = new T();
+        }
+
+        //! Called if the Scope of this Singleton gets deactivated (destroys the instance)
+        void deactivated()
+        {
+            assert(singletonPtr_ != NULL);
+            this->destroy(singletonPtr_);
+            singletonPtr_ = NULL;
+        }
+
+        void destroy(OrxonoxClass*)
+        {
+            singletonPtr_->destroy();
+        }
+        void destroy(void*)
+        {
+            delete singletonPtr_;
+        }
+
+        //! Called every frame by the ScopedSingletonManager
+        void update(const Clock& time)
+        {
+            assert(Scope<scope>::isActive());
+            // assuming T inherits Singleton<T>
+            singletonPtr_->updateSingleton(time);
+        }
+
+    private:
+        T* singletonPtr_;
+    };
+
+    template <class T, ScopeID::Value scope>
+    class ClassScopedSingletonManager<T, scope, true> : public ScopedSingletonManager, public ScopeListener
+    {
+    public:
+        ClassScopedSingletonManager(const std::string& className)
+            : ScopedSingletonManager(className, scope)
+            , ScopeListener(scope)
+            , singletonPtr_(NULL)
+        {
+            ScopedSingletonManager::addManager(this);
+        }
+
+        ~ClassScopedSingletonManager()
+        {
+            assert(singletonPtr_ == NULL);
+            ScopedSingletonManager::removeManager(this);
+        }
+
+        //! Called if the Scope of the Singleton gets active (creates the instance)
+        void activated()
+        {
+            assert(singletonPtr_ == NULL);
+            try
+                { singletonPtr_ = new T(); }
+            catch (...)
+                { COUT(1) << "Singleton creation failed: " << Exception::handleMessage() << std::endl; }
+        }
+
+        //! Called if the Scope of this Singleton gets deactivated (destroys the instance)
+        void deactivated()
+        {
+            if (singletonPtr_ != NULL)
+            {
+                this->destroy(singletonPtr_);
+                singletonPtr_ = NULL;
+            }
+        }
+
+        void destroy(OrxonoxClass* ptr)
+        {
+            singletonPtr_->destroy();
+        }
+        void destroy(void* ptr)
+        {
+            delete singletonPtr_;
+        }
+
+        //! Called every frame by the ScopedSingletonManager
+        void update(const Clock& time)
+        {
+            assert(Scope<scope>::isActive());
+            // assuming T inherits Singleton<T>
+            if (singletonPtr_ != NULL)
+                singletonPtr_->updateSingleton(time);
+        }
+
+    private:
+        T* singletonPtr_;
+    };
+}
+
+#endif /* __ScopedSingletonManager_H__ */
Index: code/trunk/src/libraries/core/Shell.cc
===================================================================
--- code/trunk/src/libraries/core/Shell.cc	(revision 5781)
+++ code/trunk/src/libraries/core/Shell.cc	(revision 5929)
@@ -88,5 +88,5 @@
         OutputHandler::getOutStream().setOutputBuffer(0);
         if (this->inputBuffer_)
-            delete this->inputBuffer_;
+            this->inputBuffer_->destroy();
     }
 
Index: code/trunk/src/libraries/core/SmartPtr.h
===================================================================
--- code/trunk/src/libraries/core/SmartPtr.h	(revision 5929)
+++ code/trunk/src/libraries/core/SmartPtr.h	(revision 5929)
@@ -0,0 +1,200 @@
+/*
+ *   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:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+// Inspired by boost::intrusive_ptr by Peter Dimov
+
+#ifndef _SmartPtr_H__
+#define _SmartPtr_H__
+
+#include "CorePrereqs.h"
+
+#include <cassert>
+
+#include "OrxonoxClass.h"
+#include "WeakPtr.h"
+
+namespace orxonox
+{
+    template <class T>
+    class SmartPtr
+    {
+        public:
+            inline SmartPtr() : pointer_(0), base_(0)
+            {
+            }
+
+            inline SmartPtr(int) : pointer_(0), base_(0)
+            {
+            }
+
+            inline SmartPtr(T* pointer, bool bAddRef = true) : pointer_(pointer), base_(pointer)
+            {
+                if (this->base_ && bAddRef)
+                    this->base_->incrementReferenceCount();
+            }
+
+            inline SmartPtr(const SmartPtr& other) : pointer_(other.pointer_), base_(other.base_)
+            {
+                if (this->base_)
+                    this->base_->incrementReferenceCount();
+            }
+
+            template <class O>
+            inline SmartPtr(const SmartPtr<O>& other) : pointer_(other.get()), base_(other.base_)
+            {
+                if (this->base_)
+                    this->base_->incrementReferenceCount();
+            }
+
+            template <class O>
+            inline SmartPtr(const WeakPtr<O>& other) : pointer_(other.get()), base_(other.getBase())
+            {
+                if (this->base_)
+                    this->base_->incrementReferenceCount();
+            }
+
+            inline ~SmartPtr()
+            {
+                if (this->base_)
+                    this->base_->decrementReferenceCount();
+            }
+            
+            inline const SmartPtr& operator=(int)
+            {
+                SmartPtr(0).swap(*this);
+                return *this;
+            }
+
+            inline const SmartPtr& operator=(T* pointer)
+            {
+                SmartPtr(pointer).swap(*this);
+                return *this;
+            }
+
+            inline const SmartPtr& operator=(const SmartPtr& other)
+            {
+                SmartPtr(other).swap(*this);
+                return *this;
+            }
+
+            template <class O>
+            inline const SmartPtr& operator=(const SmartPtr<O>& other)
+            {
+                SmartPtr(other).swap(*this);
+                return *this;
+            }
+
+            template <class O>
+            inline const SmartPtr& operator=(const WeakPtr<O>& other)
+            {
+                SmartPtr(other).swap(*this);
+                return *this;
+            }
+
+            inline T* get() const
+            {
+                return this->pointer_;
+            }
+
+            inline OrxonoxClass* getBase() const
+            {
+                return this->base_;
+            }
+
+            inline operator T*() const
+            {
+                return this->pointer_;
+            }
+
+            inline T* operator->() const
+            {
+                assert(this->pointer_ != 0);
+                return this->pointer_;
+            }
+
+            inline T& operator*() const
+            {
+                assert(this->pointer_ != 0);
+                return *this->pointer_;
+            }
+
+            inline bool operator!() const
+            {
+                return (this->pointer_ == 0);
+            }
+
+            inline void swap(SmartPtr& other)
+            {
+                {
+                    T* temp = this->pointer_;
+                    this->pointer_ = other.pointer_;
+                    other.pointer_ = temp;
+                }
+                {
+                    OrxonoxClass* temp = this->base_;
+                    this->base_ = other.base_;
+                    other.base_ = temp;
+                }
+            }
+
+            inline void reset()
+            {
+                SmartPtr().swap(*this);
+            }
+
+        private:
+            T* pointer_;
+            OrxonoxClass* base_;
+    };
+
+    template <class T>
+    void swap(SmartPtr<T>& a, SmartPtr<T>& b)
+    {
+        a.swap(b);
+    }
+
+    template <class T, class U>
+    SmartPtr<T> static_pointer_cast(const SmartPtr<U>& p)
+    {
+        return static_cast<T*>(p.get());
+    }
+
+    template <class T, class U>
+    SmartPtr<T> const_pointer_cast(const SmartPtr<U>& p)
+    {
+        return const_cast<T*>(p.get());
+    }
+
+    template <class T, class U>
+    SmartPtr<T> dynamic_pointer_cast(const SmartPtr<U>& p)
+    {
+        return dynamic_cast<T*>(p.get());
+    }
+}
+
+#endif /* _SmartPtr_H__ */
Index: code/trunk/src/libraries/core/SubclassIdentifier.h
===================================================================
--- code/trunk/src/libraries/core/SubclassIdentifier.h	(revision 5929)
+++ code/trunk/src/libraries/core/SubclassIdentifier.h	(revision 5929)
@@ -0,0 +1,192 @@
+/*
+ *   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:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+/**
+    @file
+    @brief Definition of SubclassIdentifier.
+
+    SubclassIdentifier is a separated class, acting like an Identifier, but has a given class.
+    You can only assign Identifiers of exactly the given class or of a derivative to a SubclassIdentifier.
+*/
+
+#ifndef _SubclassIdentifier_H__
+#define _SubclassIdentifier_H__
+
+#include "CorePrereqs.h"
+
+#include <cstdlib>
+#include "util/Debug.h"
+#include "Identifier.h"
+
+namespace orxonox
+{
+    // ###############################
+    // ###   SubclassIdentifier    ###
+    // ###############################
+    //! The SubclassIdentifier acts almost like an Identifier, but has some prerequisites.
+    /**
+        You can only assign an Identifier that belongs to a class T (or derived) to a SubclassIdentifier<T>.
+        If you assign something else, the program aborts.
+        Because we know the minimum type, a dynamic_cast is done, which makes it easier to create a new object.
+    */
+    template <class T>
+    class SubclassIdentifier
+    {
+        public:
+            /**
+                @brief Constructor: Automaticaly assigns the Identifier of the given class.
+            */
+            SubclassIdentifier()
+            {
+                this->identifier_ = ClassIdentifier<T>::getIdentifier();
+            }
+
+            /**
+                @brief Constructor: Assigns the given Identifier.
+                @param identifier The Identifier
+            */
+            SubclassIdentifier(Identifier* identifier)
+            {
+                this->operator=(identifier);
+            }
+
+            /**
+                @brief Copyconstructor: Assigns the identifier of the other SubclassIdentifier.
+                @param identifier The other SublcassIdentifier
+            */
+            template <class O>
+            SubclassIdentifier(const SubclassIdentifier<O>& identifier)
+            {
+                this->operator=(identifier.getIdentifier());
+            }
+
+            /**
+                @brief Overloading of the = operator: assigns the identifier and checks its type.
+                @param identifier The Identifier to assign
+                @return The SubclassIdentifier itself
+            */
+            const SubclassIdentifier<T>& operator=(Identifier* identifier)
+            {
+                if (!identifier || !identifier->isA(ClassIdentifier<T>::getIdentifier()))
+                {
+                    COUT(1) << "An error occurred in SubclassIdentifier (Identifier.h):" << std::endl;
+                    if (identifier)
+                    {
+                        COUT(1) << "Error: Class " << identifier->getName() << " is not a " << ClassIdentifier<T>::getIdentifier()->getName() << "!" << std::endl;
+                        COUT(1) << "Error: SubclassIdentifier<" << ClassIdentifier<T>::getIdentifier()->getName() << "> = Class(" << identifier->getName() << ") is forbidden." << std::endl;
+                    }
+                    else
+                    {
+                        COUT(1) << "Error: Can't assign NULL identifier" << std::endl;
+                    }
+                }
+                else
+                {
+                    this->identifier_ = identifier;
+                }
+                return *this;
+            }
+
+            /**
+                @brief Overloading of the = operator: assigns the identifier of the other SubclassIdentifier.
+                @param identifier The other SublcassIdentifier
+            */
+            template <class O>
+            const SubclassIdentifier<T>& operator=(const SubclassIdentifier<O>& identifier)
+            {
+                return this->operator=(identifier.getIdentifier());
+            }
+
+            /**
+                @brief Overloading of the * operator: returns the assigned identifier.
+            */
+            inline Identifier* operator*() const
+            {
+                return this->identifier_;
+            }
+
+            /**
+                @brief Overloading of the -> operator: returns the assigned identifier.
+            */
+            inline Identifier* operator->() const
+            {
+                return this->identifier_;
+            }
+
+            /**
+                @brief Returns the assigned identifier. This allows you to assign a SubclassIdentifier to a normal Identifier*.
+            */
+            inline operator Identifier*() const
+            {
+                return this->identifier_;
+            }
+
+            /**
+                @brief Creates a new object of the type of the assigned Identifier and dynamic_casts it to the minimal type given by T.
+                @return The new object
+            */
+            T* fabricate(BaseObject* creator) const
+            {
+                BaseObject* newObject = this->identifier_->fabricate(creator);
+
+                // Check if the creation was successful
+                if (newObject)
+                {
+                    return orxonox_cast<T*>(newObject);
+                }
+                else
+                {
+                    // Something went terribly wrong
+                    if (this->identifier_)
+                    {
+                        COUT(1) << "An error occurred in SubclassIdentifier (Identifier.h):" << std::endl;
+                        COUT(1) << "Error: Class " << this->identifier_->getName() << " is not a " << ClassIdentifier<T>::getIdentifier()->getName() << "!" << std::endl;
+                        COUT(1) << "Error: Couldn't fabricate a new Object." << std::endl;
+                    }
+                    else
+                    {
+                        COUT(1) << "An error occurred in SubclassIdentifier (Identifier.h):" << std::endl;
+                        COUT(1) << "Error: Couldn't fabricate a new Object - Identifier is undefined." << std::endl;
+                    }
+
+                    COUT(1) << "Aborting..." << std::endl;
+                    abort();
+                    return 0;
+                }
+            }
+
+            /** @brief Returns the assigned identifier. @return The identifier */
+            inline Identifier* getIdentifier() const
+                { return this->identifier_; }
+
+        private:
+            Identifier* identifier_;            //!< The assigned identifier
+    };
+}
+
+#endif /* _SubclassIdentifier_H__ */
Index: code/trunk/src/libraries/core/Super.h
===================================================================
--- code/trunk/src/libraries/core/Super.h	(revision 5781)
+++ code/trunk/src/libraries/core/Super.h	(revision 5929)
@@ -250,11 +250,8 @@
         SUPER_NOARGS(classname, functionname)
 
-    #define SUPER_processEvent(classname, functionname, ...) \
+    #define SUPER_XMLEventPort(classname, functionname, ...) \
         SUPER_ARGS(classname, functionname, __VA_ARGS__)
 
     #define SUPER_changedScale(classname, functionname, ...) \
-        SUPER_NOARGS(classname, functionname)
-
-    #define SUPER_changedMainState(classname, functionname, ...) \
         SUPER_NOARGS(classname, functionname)
 
@@ -497,6 +494,6 @@
         SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
 
-        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(4, processEvent, true, Event& event)
-            (event)
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(4, XMLEventPort, true, Element& xmlelement, XMLPort::Mode mode)
+            (xmlelement, mode)
         SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
 
@@ -505,21 +502,17 @@
         SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
 
-        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(6, changedMainState, false)
-            ()
-        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
-
-        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(7, changedOwner, false)
-            ()
-        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
-
-        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(8, changedOverlayGroup, false)
-            ()
-        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
-
-        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(9, changedName, false)
-            ()
-        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
-
-        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(10, changedGametype, false)
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(6, changedOwner, false)
+            ()
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
+
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(7, changedOverlayGroup, false)
+            ()
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
+
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(8, changedName, false)
+            ()
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
+
+        SUPER_FUNCTION_GLOBAL_DECLARATION_PART1(9, changedGametype, false)
             ()
         SUPER_FUNCTION_GLOBAL_DECLARATION_PART2;
@@ -571,7 +564,6 @@
     SUPER_INTRUSIVE_DECLARATION(changedActivity);
     SUPER_INTRUSIVE_DECLARATION(changedVisibility);
-    SUPER_INTRUSIVE_DECLARATION(processEvent);
+    SUPER_INTRUSIVE_DECLARATION(XMLEventPort);
     SUPER_INTRUSIVE_DECLARATION(changedScale);
-    SUPER_INTRUSIVE_DECLARATION(changedMainState);
     SUPER_INTRUSIVE_DECLARATION(changedOwner);
     SUPER_INTRUSIVE_DECLARATION(changedOverlayGroup);
Index: code/trunk/src/libraries/core/TclBind.cc
===================================================================
--- code/trunk/src/libraries/core/TclBind.cc	(revision 5781)
+++ code/trunk/src/libraries/core/TclBind.cc	(revision 5929)
@@ -39,5 +39,5 @@
 #include "CommandExecutor.h"
 #include "ConsoleCommand.h"
-#include "Core.h"
+#include "PathConfig.h"
 #include "TclThreadManager.h"
 
@@ -123,8 +123,8 @@
     {
 #ifdef DEPENDENCY_PACKAGE_ENABLE
-        if (Core::isDevelopmentRun())
+        if (PathConfig::isDevelopmentRun())
             return (std::string(specialConfig::dependencyLibraryDirectory) + "/tcl");
         else
-            return (Core::getRootPathString() + "lib/tcl");
+            return (PathConfig::getRootPathString() + "lib/tcl");
 #else
         return "";
Index: code/trunk/src/libraries/core/TclThreadManager.cc
===================================================================
--- code/trunk/src/libraries/core/TclThreadManager.cc	(revision 5781)
+++ code/trunk/src/libraries/core/TclThreadManager.cc	(revision 5929)
@@ -36,7 +36,7 @@
 #include <cpptcl/cpptcl.h>
 
+#include "util/Clock.h"
 #include "util/Convert.h"
 #include "util/Exception.h"
-#include "Clock.h"
 #include "CommandExecutor.h"
 #include "ConsoleCommand.h"
Index: code/trunk/src/libraries/core/WeakPtr.h
===================================================================
--- code/trunk/src/libraries/core/WeakPtr.h	(revision 5929)
+++ code/trunk/src/libraries/core/WeakPtr.h	(revision 5929)
@@ -0,0 +1,219 @@
+/*
+ *   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:
+ *      Fabian 'x3n' Landau
+ *   Co-authors:
+ *      ...
+ *
+ */
+
+// Inspired by boost::intrusive_ptr by Peter Dimov
+
+#ifndef _WeakPtr_H__
+#define _WeakPtr_H__
+
+#include "CorePrereqs.h"
+
+#include <cassert>
+#include "OrxonoxClass.h"
+#include "Functor.h"
+
+namespace orxonox
+{
+    template <class T>
+    class WeakPtr
+    {
+        friend class OrxonoxClass;
+        
+        public:
+            inline WeakPtr() : pointer_(0), base_(0), callback_(0)
+            {
+            }
+
+            inline WeakPtr(int) : pointer_(0), base_(0), callback_(0)
+            {
+            }
+
+            inline WeakPtr(T* pointer) : pointer_(pointer), base_(pointer), callback_(0)
+            {
+                if (this->base_)
+                    this->base_->registerWeakPtr(this);
+            }
+
+            inline WeakPtr(const WeakPtr& other) : pointer_(other.pointer_), base_(other.base_), callback_(0)
+            {
+                if (this->base_)
+                    this->base_->registerWeakPtr(this);
+            }
+
+            template <class O>
+            inline WeakPtr(const WeakPtr<O>& other) : pointer_(other.get()), base_(other.base_), callback_(0)
+            {
+                if (this->base_)
+                    this->base_->registerWeakPtr(this);
+            }
+
+            inline ~WeakPtr()
+            {
+                if (this->base_)
+                    this->base_->unregisterWeakPtr(this);
+                if (this->callback_)
+                    delete this->callback_;
+                    
+            }
+            
+            inline const WeakPtr& operator=(int)
+            {
+                WeakPtr(0).swap(*this);
+                return *this;
+            }
+
+            inline const WeakPtr& operator=(T* pointer)
+            {
+                WeakPtr(pointer).swap(*this);
+                return *this;
+            }
+
+            inline const WeakPtr& operator=(const WeakPtr& other)
+            {
+                WeakPtr(other).swap(*this);
+                return *this;
+            }
+
+            template <class O>
+            inline const WeakPtr& operator=(const WeakPtr<O>& other)
+            {
+                WeakPtr(other).swap(*this);
+                return *this;
+            }
+
+            inline T* get() const
+            {
+                return this->pointer_;
+            }
+
+            inline OrxonoxClass* getBase() const
+            {
+                return this->base_;
+            }
+
+            inline operator T*() const
+            {
+                return this->pointer_;
+            }
+
+            inline T* operator->() const
+            {
+                assert(this->pointer_ != 0);
+                return this->pointer_;
+            }
+
+            inline T& operator*() const
+            {
+                assert(this->pointer_ != 0);
+                return *this->pointer_;
+            }
+
+            inline bool operator!() const
+            {
+                return (this->pointer_ == 0);
+            }
+
+            inline void swap(WeakPtr& other)
+            {
+                if (this->base_)
+                    this->base_->unregisterWeakPtr(this);
+                if (other.base_)
+                    other.base_->unregisterWeakPtr(&other);
+                
+                {
+                    T* temp = this->pointer_;
+                    this->pointer_ = other.pointer_;
+                    other.pointer_ = temp;
+                }
+                {
+                    OrxonoxClass* temp = this->base_;
+                    this->base_ = other.base_;
+                    other.base_ = temp;
+                }
+
+                if (this->base_)
+                    this->base_->registerWeakPtr(this);
+                if (other.base_)
+                    other.base_->registerWeakPtr(&other);
+            }
+
+            inline void reset()
+            {
+                WeakPtr().swap(*this);
+            }
+            
+            inline void setCallback(Functor* callback)
+            {
+                this->callback_ = callback;
+            }
+            
+            inline Functor* getFunctor() const
+            {
+                return this->callback_;
+            }
+
+        private:
+            inline void objectDeleted()
+            {
+                this->base_ = 0;
+                this->pointer_ = 0;
+                if (this->callback_)
+                    (*this->callback_)();
+            }
+        
+            T* pointer_;
+            OrxonoxClass* base_;
+            Functor* callback_;
+    };
+
+    template <class T>
+    void swap(WeakPtr<T>& a, WeakPtr<T>& b)
+    {
+        a.swap(b);
+    }
+
+    template <class T, class U>
+    WeakPtr<T> static_pointer_cast(const WeakPtr<U>& p)
+    {
+        return static_cast<T*>(p.get());
+    }
+
+    template <class T, class U>
+    WeakPtr<T> const_pointer_cast(const WeakPtr<U>& p)
+    {
+        return const_cast<T*>(p.get());
+    }
+
+    template <class T, class U>
+    WeakPtr<T> dynamic_pointer_cast(const WeakPtr<U>& p)
+    {
+        return dynamic_cast<T*>(p.get());
+    }
+}
+
+#endif /* _WeakPtr_H__ */
Index: code/trunk/src/libraries/core/XMLPort.h
===================================================================
--- code/trunk/src/libraries/core/XMLPort.h	(revision 5781)
+++ code/trunk/src/libraries/core/XMLPort.h	(revision 5929)
@@ -51,5 +51,4 @@
 #include "util/MultiType.h"
 #include "util/OrxAssert.h"
-#include "Factory.h"
 #include "Identifier.h"
 #include "Executor.h"
@@ -377,5 +376,5 @@
                             this->owner_->xmlAttributes_.clear();
                             // Iterate through the attributes manually in order to make them case insensitive
-                            Attribute* attribute = xmlelement.FirstAttribute(false);
+                            ticpp::Attribute* attribute = xmlelement.FirstAttribute(false);
                             while (attribute != 0)
                             {
@@ -412,5 +411,5 @@
                     }
                 }
-                else
+                else if (mode == XMLPort::SaveObject)
                 {
                     if (this->saveexecutor_)
@@ -548,5 +547,5 @@
                             for (ticpp::Iterator<ticpp::Element> child = xmlsubelement->FirstChildElement(false); child != child.end(); child++)
                             {
-                                Identifier* identifier = Factory::getIdentifier(child->Value());
+                                Identifier* identifier = Identifier::getIdentifierByString(child->Value());
                                 if (identifier)
                                 {
@@ -629,5 +628,5 @@
                     }
                 }
-                else
+                else if (mode == XMLPort::SaveObject)
                 {
                 }
Index: code/trunk/src/libraries/core/input/Button.cc
===================================================================
--- code/trunk/src/libraries/core/input/Button.cc	(revision 5781)
+++ code/trunk/src/libraries/core/input/Button.cc	(revision 5929)
@@ -170,8 +170,8 @@
 
                 // evaluate the command
-                CommandEvaluation eval = CommandExecutor::evaluate(commandStr);
+                const CommandEvaluation& eval = CommandExecutor::evaluate(commandStr);
                 if (!eval.isValid())
                 {
-                    parseError("Command evaluation failed.", true);
+                    parseError("Command evaluation of \"" + commandStr + "\"failed.", true);
                     continue;
                 }
Index: code/trunk/src/libraries/core/input/CMakeLists.txt
===================================================================
--- code/trunk/src/libraries/core/input/CMakeLists.txt	(revision 5781)
+++ code/trunk/src/libraries/core/input/CMakeLists.txt	(revision 5929)
@@ -9,4 +9,5 @@
   JoyStickQuantityListener.cc
   KeyBinder.cc
+  KeyBinderManager.cc
   Keyboard.cc
   KeyDetector.cc
Index: code/trunk/src/libraries/core/input/InputDevice.h
===================================================================
--- code/trunk/src/libraries/core/input/InputDevice.h	(revision 5781)
+++ code/trunk/src/libraries/core/input/InputDevice.h	(revision 5929)
@@ -41,7 +41,7 @@
 #include <ois/OISInputManager.h>
 
+#include "util/Clock.h"
 #include "util/Debug.h"
 #include "util/Exception.h"
-#include "core/Clock.h"
 #include "InputState.h"
 
Index: code/trunk/src/libraries/core/input/InputManager.cc
===================================================================
--- code/trunk/src/libraries/core/input/InputManager.cc	(revision 5781)
+++ code/trunk/src/libraries/core/input/InputManager.cc	(revision 5929)
@@ -41,8 +41,8 @@
 #include <boost/foreach.hpp>
 
+#include "util/Clock.h"
 #include "util/Convert.h"
 #include "util/Exception.h"
 #include "util/ScopeGuard.h"
-#include "core/Clock.h"
 #include "core/CoreIncludes.h"
 #include "core/ConfigValueIncludes.h"
@@ -53,5 +53,4 @@
 
 #include "InputBuffer.h"
-#include "KeyDetector.h"
 #include "JoyStick.h"
 #include "JoyStickQuantityListener.h"
@@ -88,7 +87,6 @@
         , oisInputManager_(0)
         , devices_(2)
-        , bExclusiveMouse_(false)
+        , mouseMode_(MouseMode::Nonexclusive)
         , emptyState_(0)
-        , keyDetector_(0)
         , calibratorCallbackHandler_(0)
     {
@@ -99,4 +97,6 @@
         this->setConfigValues();
 
+        if (GraphicsManager::getInstance().isFullScreen())
+            mouseMode_ = MouseMode::Exclusive;
         this->loadDevices();
 
@@ -105,13 +105,4 @@
         emptyState_->setHandler(&InputHandler::EMPTY);
         activeStates_[emptyState_->getPriority()] = emptyState_;
-
-        // KeyDetector to evaluate a pressed key's name
-        InputState* detector = createInputState("detector", false, false, InputStatePriority::Detector);
-        // Create a callback to avoid buttonHeld events after the key has been detected
-        FunctorMember<InputManager>* bufferFunctor = createFunctor(&InputManager::clearBuffers);
-        bufferFunctor->setObject(this);
-        detector->setLeaveFunctor(bufferFunctor);
-        keyDetector_ = new KeyDetector();
-        detector->setHandler(keyDetector_);
 
         // Joy stick calibration helper callback
@@ -124,16 +115,8 @@
         this->updateActiveStates();
 
-        {
-            // calibrate console command
-            FunctorMember<InputManager>* functor = createFunctor(&InputManager::calibrate);
-            functor->setObject(this);
-            this->getIdentifier()->addConsoleCommand(createConsoleCommand(functor, "calibrate"), true);
-        }
-        {
-            // reload console command
-            FunctorMember<InputManager>* functor = createFunctor(&InputManager::reload);
-            functor->setObject(this);
-            this->getIdentifier()->addConsoleCommand(createConsoleCommand(functor, "reload"), false);
-        }
+        // calibrate console command
+        this->getIdentifier()->addConsoleCommand(createConsoleCommand(createFunctor(&InputManager::calibrate, this), "calibrate"), true);
+        // reload console command
+        this->getIdentifier()->addConsoleCommand(createConsoleCommand(createFunctor(&InputManager::reload, this), "reload"), false);
 
         CCOUT(4) << "Construction complete." << std::endl;
@@ -172,5 +155,5 @@
         paramList.insert(std::make_pair("w32_keyboard", "DISCL_FOREGROUND"));
         paramList.insert(std::make_pair("w32_mouse", "DISCL_FOREGROUND"));
-        if (bExclusiveMouse_ || GraphicsManager::getInstance().isFullScreen())
+        if (mouseMode_ == MouseMode::Exclusive || GraphicsManager::getInstance().isFullScreen())
         {
             // Disable Windows key plus special keys (like play, stop, next, etc.)
@@ -185,5 +168,5 @@
         paramList.insert(std::make_pair("XAutoRepeatOn", "true"));
 
-        if (bExclusiveMouse_ || GraphicsManager::getInstance().isFullScreen())
+        if (mouseMode_ == MouseMode::Exclusive || GraphicsManager::getInstance().isFullScreen())
         {
             if (CommandLine::getValue("keyboard_no_grab").getBool())
@@ -274,9 +257,4 @@
     }
 
-    void InputManager::setKeyDetectorCallback(const std::string& command)
-    {
-        this->keyDetector_->setCallbackCommand(command);
-    }
-
     // ############################################################
     // #####                    Destruction                   #####
@@ -289,9 +267,7 @@
 
         // Destroy calibrator helper handler and state
-        delete keyDetector_;
         this->destroyState("calibrator");
         // Destroy KeyDetector and state
-        delete calibratorCallbackHandler_;
-        this->destroyState("detector");
+        calibratorCallbackHandler_->destroy();
         // destroy the empty InputState
         this->destroyStateInternal(this->emptyState_);
@@ -528,9 +504,13 @@
 
         // Check whether we have to change the mouse mode
+        MouseMode::Value requestedMode = MouseMode::Dontcare;
         std::vector<InputState*>& mouseStates = devices_[InputDeviceEnumerator::Mouse]->getStateListRef();
-        if (mouseStates.empty() && bExclusiveMouse_ ||
-            !mouseStates.empty() && mouseStates.front()->getIsExclusiveMouse() != bExclusiveMouse_)
-        {
-            bExclusiveMouse_ = !bExclusiveMouse_;
+        if (mouseStates.empty())
+            requestedMode = MouseMode::Nonexclusive;
+        else 
+            requestedMode = mouseStates.front()->getMouseMode();
+        if (requestedMode != MouseMode::Dontcare && mouseMode_ != requestedMode)
+        {
+            mouseMode_ = requestedMode;
             if (!GraphicsManager::getInstance().isFullScreen())
                 this->reloadInternal();
@@ -722,5 +702,5 @@
         }
         statesByName_.erase(state->getName());
-        delete state;
+        state->destroy();
     }
 }
Index: code/trunk/src/libraries/core/input/InputManager.h
===================================================================
--- code/trunk/src/libraries/core/input/InputManager.h	(revision 5781)
+++ code/trunk/src/libraries/core/input/InputManager.h	(revision 5929)
@@ -161,6 +161,4 @@
         // Various getters and setters
         //-------------------------------
-        //! Sets the the name of the command used by the KeyDetector as callback.
-        void setKeyDetectorCallback(const std::string& command);
         //! Returns the number of joy stick that have been created since the c'tor or last call to reload().
         unsigned int getJoyStickQuantity() const
@@ -193,9 +191,8 @@
         OIS::InputManager*                  oisInputManager_;      //!< OIS input manager
         std::vector<InputDevice*>           devices_;              //!< List of all input devices (keyboard, mouse, joy sticks)
-        bool                                bExclusiveMouse_;      //!< Currently applied mouse mode
+        MouseMode::Value                    mouseMode_;            //!< Currently applied mouse mode
 
         // some internally handled states and handlers
         InputState*                         emptyState_;           //!< Lowest priority states (makes handling easier)
-        KeyDetector*                        keyDetector_;          //!< KeyDetector instance
         //! InputBuffer that reacts to the Enter key when calibrating the joy sticks
         InputBuffer*                        calibratorCallbackHandler_;
Index: code/trunk/src/libraries/core/input/InputState.cc
===================================================================
--- code/trunk/src/libraries/core/input/InputState.cc	(revision 5781)
+++ code/trunk/src/libraries/core/input/InputState.cc	(revision 5929)
@@ -37,5 +37,5 @@
         , bAlwaysGetsInput_(bAlwaysGetsInput)
         , bTransparent_(bTransparent)
-        , bExclusiveMouse_(true)
+        , mouseMode_(MouseMode::Dontcare)
         , bExpired_(true)
         , handlers_(2)
Index: code/trunk/src/libraries/core/input/InputState.h
===================================================================
--- code/trunk/src/libraries/core/input/InputState.h	(revision 5781)
+++ code/trunk/src/libraries/core/input/InputState.h	(revision 5929)
@@ -55,4 +55,14 @@
         static const int Detector     = HighPriority + 2;
     };
+
+    namespace MouseMode
+    {
+        enum Value
+        {
+            Exclusive,
+            Nonexclusive,
+            Dontcare
+        };
+    }
 
     /**
@@ -120,6 +130,6 @@
         void setHandler        (InputHandler* handler);
 
-        void setIsExclusiveMouse(bool value) { bExclusiveMouse_ = value; this->bExpired_ = true; }
-        bool getIsExclusiveMouse() const { return bExclusiveMouse_; }
+        void setMouseMode(MouseMode::Value value) { mouseMode_ = value; this->bExpired_ = true; }
+        MouseMode::Value getMouseMode() const { return mouseMode_; }
 
         //! Returns the name of the state (which is unique!)
@@ -174,5 +184,5 @@
         const bool                  bAlwaysGetsInput_;      //!< See class declaration for explanation
         const bool                  bTransparent_;          //!< See class declaration for explanation
-        bool                        bExclusiveMouse_;       //!< See class declaration for explanation
+        MouseMode::Value            mouseMode_;             //!< See class declaration for explanation
         int                         priority_;              //!< Current priority (might change)
         bool                        bExpired_;              //!< See hasExpired()
Index: code/trunk/src/libraries/core/input/KeyBinder.cc
===================================================================
--- code/trunk/src/libraries/core/input/KeyBinder.cc	(revision 5781)
+++ code/trunk/src/libraries/core/input/KeyBinder.cc	(revision 5929)
@@ -27,13 +27,9 @@
  */
 
-/**
- @file
- @brief Implementation of the different input handlers.
- */
-
 #include "KeyBinder.h"
 
 #include "util/Convert.h"
 #include "util/Debug.h"
+#include "util/Exception.h"
 #include "core/ConfigValueIncludes.h"
 #include "core/CoreIncludes.h"
@@ -48,6 +44,7 @@
         Constructor that does as little as necessary.
     */
-    KeyBinder::KeyBinder()
+    KeyBinder::KeyBinder(const std::string& filename)
         : deriveTime_(0.0f)
+        , filename_(filename)
     {
         mouseRelative_[0] = 0;
@@ -103,4 +100,8 @@
         // set them here to use allHalfAxes_
         setConfigValues();
+
+        // Load the bindings if filename was given
+        if (!this->filename_.empty())
+            this->loadBindings();
     }
 
@@ -240,24 +241,15 @@
     @brief
         Loads the key and button bindings.
-    @return
-        True if loading succeeded.
-    */
-    void KeyBinder::loadBindings(const std::string& filename)
+    */
+    void KeyBinder::loadBindings()
     {
         COUT(3) << "KeyBinder: Loading key bindings..." << std::endl;
 
-        if (filename.empty())
-            return;
-
-        if (this->configFile_ == ConfigFileType::NoType)
-        {
-            // Get a new ConfigFileType from the ConfigFileManager
-            this->configFile_ = ConfigFileManager::getInstance().getNewConfigFileType();
-        }
-
-        ConfigFileManager::getInstance().setFilename(this->configFile_, filename);
+        // Get a new ConfigFileType from the ConfigFileManager
+        this->configFile_ = ConfigFileManager::getInstance().getNewConfigFileType();
+
+        ConfigFileManager::getInstance().setFilename(this->configFile_, this->filename_);
 
         // Parse bindings and create the ConfigValueContainers if necessary
-        clearBindings();
         for (std::map<std::string, Button*>::const_iterator it = allButtons_.begin(); it != allButtons_.end(); ++it)
             it->second->readConfigValue(this->configFile_);
Index: code/trunk/src/libraries/core/input/KeyBinder.h
===================================================================
--- code/trunk/src/libraries/core/input/KeyBinder.h	(revision 5781)
+++ code/trunk/src/libraries/core/input/KeyBinder.h	(revision 5929)
@@ -26,10 +26,4 @@
  *
  */
-
-/**
-@file
-@brief
-    Different definitions of input processing.
-*/
 
 #ifndef _KeyBinder_H__
@@ -53,20 +47,32 @@
     /**
     @brief
-        Handles mouse, keyboard and joy stick input while in the actual game mode.
-        Manages the key bindings.
+        Maps mouse, keyboard and joy stick input to command strings and executes them.
+
+        The bindings are stored in ini-files (like the one for configValues) in the config Path.
+    @remarks
+        You cannot change the filename because the KeyBinderManager maps these filenames to the
+        KeyBinders. If you need to load other bindings, just create a new one.
     */
     class _CoreExport KeyBinder : public InputHandler, public JoyStickQuantityListener
     {
     public:
-        KeyBinder ();
+        KeyBinder (const std::string& filename);
         virtual ~KeyBinder();
 
-        void loadBindings(const std::string& filename);
         void clearBindings();
         bool setBinding(const std::string& binding, const std::string& name, bool bTemporary = false);
+        const std::string& getBindingsFilename()
+            { return this->filename_; }
         void setConfigValues();
         void resetJoyStickAxes();
 
     protected: // functions
+        void loadBindings();
+        void buttonThresholdChanged();
+        void initialiseJoyStickBindings();
+        void compilePointerLists();
+        // from JoyStickQuantityListener interface
+        virtual void JoyStickQuantityChanged(const std::vector<JoyStick*>& joyStickList);
+
         void allDevicesUpdated(float dt);
         void mouseUpdated(float dt);
@@ -74,10 +80,4 @@
         // internal
         void tickHalfAxis(HalfAxis& halfAxis);
-
-        void buttonThresholdChanged();
-        // from JoyStickQuantityListener interface
-        virtual void JoyStickQuantityChanged(const std::vector<JoyStick*>& joyStickList);
-        void initialiseJoyStickBindings();
-        void compilePointerLists();
 
         void buttonPressed (const KeyEvent& evt);
@@ -144,4 +144,6 @@
         float deriveTime_;
 
+        //! Name of the file used in this KeyBinder (constant!)
+        const std::string filename_;
         //! Config file used. ConfigFileType::NoType in case of KeyDetector. Also indicates whether we've already loaded.
         ConfigFileType configFile_;
@@ -171,4 +173,5 @@
     };
 
+
     inline void KeyBinder::buttonPressed (const KeyEvent& evt)
     { assert(!keys_[evt.getKeyCode()].name_.empty()); keys_[evt.getKeyCode()].execute(KeybindMode::OnPress); }
Index: code/trunk/src/libraries/core/input/KeyBinderManager.cc
===================================================================
--- code/trunk/src/libraries/core/input/KeyBinderManager.cc	(revision 5929)
+++ code/trunk/src/libraries/core/input/KeyBinderManager.cc	(revision 5929)
@@ -0,0 +1,169 @@
+/*
+ *   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:
+ *      ...
+ *
+ */
+
+#include "KeyBinderManager.h"
+
+#include "util/Debug.h"
+#include "util/Exception.h"
+#include "core/ConfigValueIncludes.h"
+#include "core/ConsoleCommand.h"
+#include "core/CoreIncludes.h"
+#include "core/ScopedSingletonManager.h"
+#include "InputManager.h"
+#include "KeyDetector.h"
+
+namespace orxonox
+{
+    KeyBinderManager* KeyBinderManager::singletonPtr_s = 0;
+    ManageScopedSingleton(KeyBinderManager, ScopeID::Graphics, false);
+
+    KeyBinderManager::KeyBinderManager()
+        : currentBinder_(NULL)
+        , bDefaultFileLoaded_(true)
+        , bBinding_(false)
+    {
+        this->callbackFunction_ = createFunctor(&KeyBinderManager::callback, this);
+
+        RegisterObject(KeyBinderManager);
+        this->setConfigValues();
+
+        // keybind console commands
+        CommandExecutor::addConsoleCommandShortcut(createConsoleCommand(createFunctor(&KeyBinderManager::keybind,  this), "keybind" ))
+            .defaultValues("");
+        CommandExecutor::addConsoleCommandShortcut(createConsoleCommand(createFunctor(&KeyBinderManager::tkeybind, this), "tkeybind"))
+            .defaultValues("");
+
+        // Load default key binder
+        this->setCurrent(defaultFilename_);
+    }
+
+    KeyBinderManager::~KeyBinderManager()
+    {
+        // Delete all remaining KeyBinders
+        for (std::map<std::string, KeyBinder*>::const_iterator it = this->binders_.begin(); it != this->binders_.end(); ++it)
+            delete it->second;
+        delete this->callbackFunction_;
+    }
+
+    void KeyBinderManager::setConfigValues()
+    {
+        SetConfigValue(defaultFilename_, "keybindings.ini")
+            .description("Filename for the default keybindings file.")
+            .callback(this, &KeyBinderManager::defaultFilenameChanged);
+    }
+
+    void KeyBinderManager::defaultFilenameChanged()
+    {
+        if (this->bDefaultFileLoaded_)
+            this->setCurrent(this->defaultFilename_);
+    }
+
+    void KeyBinderManager::setCurrent(const std::string& filename)
+    {
+        this->currentBinder_ = this->get(filename);
+        if (filename == this->defaultFilename_)
+            this->bDefaultFileLoaded_ = true;
+        else
+            this->bDefaultFileLoaded_ = false;
+    }
+
+    void KeyBinderManager::load(const std::string& filename)
+    {
+        std::map<std::string, KeyBinder*>::const_iterator it = this->binders_.find(filename);
+        if (it != this->binders_.end())
+            return;
+
+        KeyBinder* binder = new KeyBinder(filename);
+        this->binders_[filename] = binder;
+    }
+
+    void KeyBinderManager::unload(const std::string& filename)
+    {
+        if (filename == this->defaultFilename_)
+            ThrowException(General, "KeyBinderManager: Cannot unload the default file");
+        if (filename == this->currentBinder_->getBindingsFilename())
+        {
+            // unloading current file --> set default file
+            this->setCurrent(this->defaultFilename_);
+        }
+        std::map<std::string, KeyBinder*>::iterator it = this->binders_.find(filename);
+        if (it != this->binders_.end())
+        {
+            delete it->second;
+            this->binders_.erase(it);
+        }
+    }
+
+    KeyBinder* KeyBinderManager::get(const std::string& name)
+    {
+        this->load(name);
+        return this->binders_[name];
+    }
+
+    InputHandler* KeyBinderManager::getCurrentAsHandler()
+    {
+        return this->getCurrent();
+    }
+
+    InputHandler* KeyBinderManager::getDefaultAsHandler()
+    {
+        return this->getDefault();
+    }
+
+    InputHandler* KeyBinderManager::getAsHandler(const std::string& name)
+    {
+        return this->get(name);
+    }
+
+    void KeyBinderManager::keybindInternal(const std::string& command, bool bTemporary)
+    {
+        if (!this->bBinding_)
+        {
+            COUT(0) << "Press any button/key or move a mouse/joystick axis" << std::endl;
+            KeyDetector::getInstance().setCallback(callbackFunction_);
+            InputManager::getInstance().enterState("detector");
+            this->command_ = command;
+            this->bTemporary_ = bTemporary;
+            this->bBinding_ = true;
+        }
+        // else: We're still in a keybind command. Ignore this call.
+    }
+
+    // Gets called by the KeyDetector (registered with a Functor)
+    void KeyBinderManager::callback(const std::string& keyName)
+    {
+        if (this->bBinding_)
+        {
+            COUT(0) << "Binding string \"" << command_ << "\" on key '" << keyName << "'" << std::endl;
+            this->currentBinder_->setBinding(command_, keyName, bTemporary_);
+            InputManager::getInstance().leaveState("detector");
+            this->bBinding_ = false;
+        }
+        // else: A key was probably pressed within the same tick, ignore it.
+    }
+}
Index: code/trunk/src/libraries/core/input/KeyBinderManager.h
===================================================================
--- code/trunk/src/libraries/core/input/KeyBinderManager.h	(revision 5929)
+++ code/trunk/src/libraries/core/input/KeyBinderManager.h	(revision 5929)
@@ -0,0 +1,120 @@
+/*
+ *   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:
+ *      ...
+ *
+ */
+
+#ifndef _KeyBinderManager_H__
+#define _KeyBinderManager_H__
+
+#include "InputPrereqs.h"
+
+#include <map>
+#include <string>
+#include "util/Singleton.h"
+#include "core/OrxonoxClass.h"
+
+namespace orxonox
+{
+    /**
+    @brief
+        Handles the KeyBinders and supplies them throughout the game.
+
+        This interface merely serves to provide a static "keybind" command that always
+        maps to the currently active KeyBinder. You can set that with setCurrent().
+        There is also a default one, retrieved with getDefault(). The idea is that
+        mostly the default KeyBinder is active except for special situtations (mini-game for inst).
+    @remarks
+        You are not forced to use the KeyBinder imposed by getCurrent(). But be aware that "keybind"
+        will not work as expected!
+    */
+    class _CoreExport KeyBinderManager : public Singleton<KeyBinderManager>, public OrxonoxClass
+    {
+        friend class Singleton<KeyBinderManager>;
+    public:
+        KeyBinderManager();
+        ~KeyBinderManager();
+        void setConfigValues();
+
+        //! Returns the currently selected KeyBinder
+        KeyBinder*    getCurrent()
+            { return this->currentBinder_; }
+        //! Like getCurrent(), but returns it as InputHandler* (so you don't have to include KeyBinder.h)
+        InputHandler* getCurrentAsHandler();
+        //! Selects the current KeyBinder and creates it if not yet loaded.
+        void setCurrent(const std::string& filename);
+
+        //! Returns the default KeyBinder
+        KeyBinder*    getDefault()
+            { return binders_[this->defaultFilename_]; }
+        //! Returns the default KeyBinder as InputHandler* (so you don't have to include KeyBinder.h)
+        InputHandler* getDefaultAsHandler();
+        //! Returns the filename of the default key bindings
+        const std::string& getDefaultFilename()
+            { return defaultFilename_; }
+        //! Selects the default KeyBinder as current one
+        void setToDefault()
+            { this->setCurrent(this->defaultFilename_); }
+
+        //! Returns a pointer to a KeyBinder (creates it if not yet loaded)
+        KeyBinder*    get(const std::string& name);
+        //! Like get() but return value is of type InputHandler* (so you don't have to include KeyBinder.h)
+        InputHandler* getAsHandler(const std::string& name);
+
+        //! Loads a KeyBinder by creating it (no different from get() except for the return value)
+        void load  (const std::string& filename);
+        //! Destroys a KeyBinder completely (does nothing if not yet loaded)
+        void unload(const std::string& filename);
+
+        //! Bind 'command' to any key pressed after this call (use with care!)
+        inline void keybind(const std::string& command)
+            { this->keybindInternal(command, false); }
+        //! Bind 'command' to any key pressed after this call (use with care!), but temporarily (no file save)
+        inline void tkeybind(const std::string& command)
+            { this->keybindInternal(command, true); }
+
+    private:
+        KeyBinderManager(const KeyBinderManager&);
+        void keybindInternal(const std::string& command, bool bTemporary);
+        void callback(const std::string& keyName);
+        void defaultFilenameChanged();
+
+        // KeyBinder management
+        KeyBinder* currentBinder_;                   //! Currently selected KeyBinder (never NULL!)
+        std::map<std::string, KeyBinder*> binders_;  //! All loaded KeyBinders
+        bool bDefaultFileLoaded_;                    //! Tells whether the default one is loaded
+        std::string defaultFilename_;                //! Name of the file with the default key bindings
+
+        // keybind command related
+        Functor* callbackFunction_;                  //! Function to be called when key was pressed after "keybind" command
+        bool bBinding_;                              //! Tells whether a key binding process is active
+        bool bTemporary_;                            //! Stores tkeybind/keybind value
+        std::string command_;                        //! Stores the command received by (t)keybind
+
+        static KeyBinderManager* singletonPtr_s;
+    };
+}
+
+#endif /* _KeyBinderManager_H__ */
Index: code/trunk/src/libraries/core/input/KeyDetector.cc
===================================================================
--- code/trunk/src/libraries/core/input/KeyDetector.cc	(revision 5781)
+++ code/trunk/src/libraries/core/input/KeyDetector.cc	(revision 5929)
@@ -29,40 +29,53 @@
 #include "KeyDetector.h"
 
-#include "util/Debug.h"
+#include "core/ConsoleCommand.h"
 #include "core/CoreIncludes.h"
+#include "core/ScopedSingletonManager.h"
 #include "Button.h"
+#include "InputManager.h"
+#include "InputState.h"
 
 namespace orxonox
 {
-    /**
-    @brief
-        Constructor
-    */
+    std::string KeyDetector::callbackCommand_s = "KeyDetectorKeyPressed";
+    KeyDetector* KeyDetector::singletonPtr_s = 0;
+    ManageScopedSingleton(KeyDetector, ScopeID::Graphics, false);
+
     KeyDetector::KeyDetector()
+        : KeyBinder("")
     {
         RegisterObject(KeyDetector);
+
+        CommandExecutor::addConsoleCommandShortcut(createConsoleCommand(createFunctor(&KeyDetector::callback,  this), callbackCommand_s));
+        this->assignCommands();
+
+        inputState_ = InputManager::getInstance().createInputState("detector", false, false, InputStatePriority::Detector);
+        // Create a callback to avoid buttonHeld events after the key has been detected
+        inputState_->setLeaveFunctor(createFunctor(&InputManager::clearBuffers, &InputManager::getInstance()));
+        inputState_->setHandler(this);
     }
 
-    /**
-    @brief
-        Destructor
-    */
     KeyDetector::~KeyDetector()
     {
+        inputState_->setHandler(NULL);
+        InputManager::getInstance().destroyState("detector");
     }
 
-    /**
-    @brief
-        Assigns all the buttons 'command' plus the button's name.
-    */
-    void KeyDetector::setCallbackCommand(const std::string& command)
+    void KeyDetector::assignCommands()
     {
-        callbackCommand_ = command;
+        // Assign every button/axis the same command, but with its name as argument
         clearBindings();
         for (std::map<std::string, Button*>::const_iterator it = allButtons_.begin(); it != allButtons_.end(); ++it)
         {
-            it->second->bindingString_ = callbackCommand_ + it->second->groupName_ + "." + it->second->name_;
+            it->second->bindingString_ = callbackCommand_s + " " + it->second->groupName_ + "." + it->second->name_;
             it->second->parse();
         }
+    }
+
+    void KeyDetector::callback(const std::string& name)
+    {
+        // Call the registered function
+        if (this->callbackFunction_)
+            (*this->callbackFunction_)(name);
     }
 
@@ -70,6 +83,5 @@
     {
         KeyBinder::JoyStickQuantityChanged(joyStickList);
-        if (!callbackCommand_.empty())
-            setCallbackCommand(callbackCommand_);
+        this->assignCommands();
     }
 }
Index: code/trunk/src/libraries/core/input/KeyDetector.h
===================================================================
--- code/trunk/src/libraries/core/input/KeyDetector.h	(revision 5781)
+++ code/trunk/src/libraries/core/input/KeyDetector.h	(revision 5929)
@@ -32,19 +32,30 @@
 #include "InputPrereqs.h"
 
-#include <string>
+#include "util/Singleton.h"
 #include "KeyBinder.h"
 
 namespace orxonox
 {
-    class _CoreExport KeyDetector : public KeyBinder
+    class _CoreExport KeyDetector : public KeyBinder, public Singleton<KeyDetector>
     {
+        friend class Singleton<KeyDetector>;
+
     public:
         KeyDetector();
         ~KeyDetector();
-        void setCallbackCommand(const std::string& command);
-        void JoyStickQuantityChanged(const std::vector<JoyStick*>& joyStickList);
+
+        void setCallback(Functor* function) { this->callbackFunction_ = function; }
 
     private:
-        std::string callbackCommand_;
+        KeyDetector(const KeyDetector&);
+
+        void callback(const std::string& name);
+        void JoyStickQuantityChanged(const std::vector<JoyStick*>& joyStickList);
+        void assignCommands();
+
+        Functor* callbackFunction_;
+        InputState* inputState_;
+        static std::string callbackCommand_s;
+        static KeyDetector* singletonPtr_s;
     };
 }
Index: code/trunk/src/libraries/core/input/Mouse.cc
===================================================================
--- code/trunk/src/libraries/core/input/Mouse.cc	(revision 5781)
+++ code/trunk/src/libraries/core/input/Mouse.cc	(revision 5929)
@@ -48,16 +48,8 @@
 
 #ifdef ORXONOX_PLATFORM_LINUX
-        {
-            // Mouse grab console command
-            FunctorMember<Mouse>* functor = createFunctor(&Mouse::grab);
-            functor->setObject(this);
-            this->getIdentifier()->addConsoleCommand(createConsoleCommand(functor, "grab"), false);
-        }
-        {
-            // Mouse ungrab console command
-            FunctorMember<Mouse>* functor = createFunctor(&Mouse::ungrab);
-            functor->setObject(this);
-            this->getIdentifier()->addConsoleCommand(createConsoleCommand(functor, "ungrab"), false);
-        }
+        // Mouse grab console command
+        this->getIdentifier()->addConsoleCommand(createConsoleCommand(createFunctor(&Mouse::grab, this), "grab"), false);
+        // Mouse ungrab console command
+        this->getIdentifier()->addConsoleCommand(createConsoleCommand(createFunctor(&Mouse::ungrab, this), "ungrab"), false);
 #endif
     }
