Index: code/branches/gui/src/core/Core.cc
===================================================================
--- code/branches/gui/src/core/Core.cc	(revision 2798)
+++ code/branches/gui/src/core/Core.cc	(revision 2799)
@@ -22,6 +22,7 @@
  *   Author:
  *      Fabian 'x3n' Landau
+ *      Reto Grieder
  *   Co-authors:
- *      Reto Grieder
+ *      ...
  *
  */
@@ -41,4 +42,7 @@
 
 #ifdef ORXONOX_PLATFORM_WINDOWS
+#  ifndef WIN32_LEAN_AND_MEAN
+#    define WIN32_LEAN_AND_MEAN
+#  endif
 #  include <windows.h>
 #elif defined(ORXONOX_PLATFORM_APPLE)
@@ -51,10 +55,20 @@
 
 #include "SpecialConfig.h"
+#include "util/Debug.h"
 #include "util/Exception.h"
+#include "util/SignalHandler.h"
+#include "Clock.h"
+#include "CommandExecutor.h"
+#include "CommandLine.h"
+#include "ConfigFileManager.h"
+#include "ConfigValueIncludes.h"
+#include "CoreIncludes.h"
+#include "Factory.h"
+#include "Identifier.h"
 #include "Language.h"
-#include "CoreIncludes.h"
-#include "ConfigValueIncludes.h"
 #include "LuaBind.h"
-#include "CommandLine.h"
+#include "Shell.h"
+#include "TclBind.h"
+#include "TclThreadManager.h"
 
 namespace orxonox
@@ -73,9 +87,10 @@
     bool Core::bIsMaster_s      = false;
 
-    bool Core::isDevBuild_s     = false;
     Core* Core::singletonRef_s  = 0;
 
     SetCommandLineArgument(mediaPath, "").information("PATH");
-    SetCommandLineArgument(directory, "").information("DIR");
+    SetCommandLineArgument(writingPathSuffix, "").information("DIR");
+    SetCommandLineArgument(settingsFile, "orxonox.ini");
+    SetCommandLineArgument(limitToCPU, 0).information("0: off | #cpu");
 
     /**
@@ -83,5 +98,5 @@
         @param A reference to a global variable, used to avoid an infinite recursion in getSoftDebugLevel()
     */
-    Core::Core()
+    Core::Core(int argc, char** argv)
     {
         RegisterRootObject(Core);
@@ -90,10 +105,51 @@
         Core::singletonRef_s = this;
 
-        this->bInitializeRandomNumberGenerator_ = false;
-        this->setConfigValues();
+        // Parse command line arguments fist
+        try
+        {
+            CommandLine::parseAll(argc, argv);
+        }
+        catch (ArgumentException& ex)
+        {
+            COUT(1) << ex.what() << std::endl;
+            COUT(0) << "Usage:" << std::endl << "orxonox " << CommandLine::getUsageInformation() << std::endl;
+        }
+
+        // limit the main thread to the first core so that QueryPerformanceCounter doesn't jump
+        // do this after ogre has initialised. Somehow Ogre changes the settings again (not through
+        // the timer though).
+        int limitToCPU = CommandLine::getValue("limitToCPU");
+        if (limitToCPU > 0)
+            setThreadAffinity((unsigned int)limitToCPU);
+
+        // Determine and set the location of the executable
+        setExecutablePath();
+
+        // Determine whether we have an installed or a binary dir run
+        // The latter occurs when simply running from the build directory
+        checkDevBuild();
+
+        // Make sure the directories we write in exist or else make them
+        createDirectories();
+
+        // create a signal handler (only active for linux)
+        // This call is placed as soon as possible, but after the directories are set
+        this->signalHandler_ = new SignalHandler();
+        this->signalHandler_->doCatch(executablePath_g.string(), Core::getLogPathString() + "orxonox_crash.log");
 
         // Set the correct log path. Before this call, /tmp (Unix) or %TEMP% was used
         OutputHandler::getOutStream().setLogPath(Core::getLogPathString());
 
+        // Manage ini files and set the default settings file (usually orxonox.ini)
+        this->configFileManager_ = new ConfigFileManager();
+        this->configFileManager_->setFilename(ConfigFileType::Settings,
+            CommandLine::getValue("settingsFile").getString());
+
+        this->languageInstance_ = new Language();
+
+        // Do this soon after the ConfigFileManager has been created to open up the
+        // possibility to configure everything below here
+        this->setConfigValues();
+
         // Possible media path override by the command line
         if (!CommandLine::getArgument("mediaPath")->hasDefaultValue())
@@ -102,4 +158,19 @@
             Core::tsetMediaPath(CommandLine::getValue("mediaPath"));
         }
+
+        // Create the lua interface
+        this->luaBind_ = new LuaBind();
+
+        // initialise Tcl
+        this->tclBind_ = new TclBind(Core::getMediaPathString());
+        this->tclThreadManager_ = new TclThreadManager(tclBind_->getTclInterpreter());
+
+        // create a shell
+        this->shell_ = new Shell();
+
+        // creates the class hierarchy for all classes with factories
+        Factory::createClassHierarchy();
+        
+        this->loaded_ = true;
     }
 
@@ -109,4 +180,19 @@
     Core::~Core()
     {
+        this->loaded_ = false;
+
+        delete this->shell_;
+        delete this->tclThreadManager_;
+        delete this->tclBind_;
+        delete this->luaBind_;
+        delete this->languageInstance_;
+        delete this->configFileManager_;
+        delete this->signalHandler_;
+
+        // Destroy command line arguments
+        CommandLine::destroyAllArguments();
+        // Also delete external console command that don't belong to an Identifier
+        CommandExecutor::destroyExternalCommands();
+
         assert(Core::singletonRef_s);
         Core::singletonRef_s = 0;
@@ -292,23 +378,48 @@
     }
 
-    /**
-    @brief
-        Performs the rather lower level operations just after
-        int main() has been called.
-    @remarks
-        This gets called AFTER pre-main stuff like AddFactory,
-        SetConsoleCommand, etc.
-    */
-    /*static*/ void Core::postMainInitialisation()
-    {
-        // set location of the executable
-        Core::setExecutablePath();
-
-        // Determine whether we have an installed or a binary dir run
-        // The latter occurs when simply running from the build directory
-        Core::checkDevBuild();
-
-        // Make sure the directories we write in exist or else make them
-        Core::createDirectories();
+
+    /**
+    @note
+        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
+            (Object-oriented Graphics Rendering Engine)
+        For the latest info, see http://www.ogre3d.org/
+
+        Copyright (c) 2000-2008 Torus Knot Software Ltd
+
+        OGRE is licensed under the LGPL. For more info, see OGRE license.
+    */
+    void Core::setThreadAffinity(int limitToCPU)
+    {
+        if (limitToCPU <= 0)
+            return;
+
+        unsigned int coreNr = limitToCPU - 1;
+#ifdef ORXONOX_PLATFORM_WINDOWS
+        // Get the current process core mask
+        DWORD procMask;
+        DWORD sysMask;
+#  if _MSC_VER >= 1400 && defined (_M_X64)
+        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
+#  else
+        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
+#  endif
+
+        // If procMask is 0, consider there is only one core available
+        // (using 0 as procMask will cause an infinite loop below)
+        if (procMask == 0)
+            procMask = 1;
+
+        // if the core specified with coreNr is not available, take the lowest one
+        if (!(procMask & (1 << coreNr)))
+            coreNr = 0;
+
+        // Find the lowest core that this process uses and coreNr suggests
+        DWORD threadMask = 1;
+        while ((threadMask & procMask) == 0 || (threadMask < (1u << coreNr)))
+            threadMask <<= 1;
+
+        // Set affinity to the first core
+        SetThreadAffinityMask(GetCurrentThread(), threadMask);
+#endif
     }
 
@@ -317,5 +428,5 @@
         Compares the executable path with the working directory
     */
-    /*static*/ void Core::setExecutablePath()
+    void Core::setExecutablePath()
     {
 #ifdef ORXONOX_PLATFORM_WINDOWS
@@ -369,10 +480,10 @@
         don't write the logs and config files to ~/.orxonox
     */
-    /*static*/ void Core::checkDevBuild()
+    void Core::checkDevBuild()
     {
         if (boost::filesystem::exists(executablePath_g / "orxonox_dev_build.keep_me"))
         {
             COUT(1) << "Running from the build tree." << std::endl;
-            Core::isDevBuild_s = true;
+            Core::isDevBuild_ = true;
             mediaPath_g  = ORXONOX_MEDIA_DEV_PATH;
             configPath_g = ORXONOX_CONFIG_DEV_PATH;
@@ -416,7 +527,7 @@
 
         // Option to put all the config and log files in a separate folder
-        if (!CommandLine::getArgument("directory")->hasDefaultValue())
-        {
-            std::string directory(CommandLine::getValue("directory").getString());
+        if (!CommandLine::getArgument("writingPathSuffix")->hasDefaultValue())
+        {
+            std::string directory(CommandLine::getValue("writingPathSuffix").getString());
             configPath_g = configPath_g / directory;
             logPath_g    = logPath_g    / directory;
@@ -429,5 +540,5 @@
         if necessary. Otherwise me might have problems opening those files.
     */
-    /*static*/ void Core::createDirectories()
+    void Core::createDirectories()
     {
         std::vector<std::pair<boost::filesystem::path, std::string> > directories;
@@ -451,3 +562,8 @@
         }
     }
+
+    void Core::tick(const Clock& time)
+    {
+        this->tclThreadManager_->tick(time.getDeltaTime());
+    }
 }
Index: code/branches/gui/src/core/Core.h
===================================================================
--- code/branches/gui/src/core/Core.h	(revision 2798)
+++ code/branches/gui/src/core/Core.h	(revision 2799)
@@ -22,6 +22,7 @@
  *   Author:
  *      Fabian 'x3n' Landau
+ *      Reto Grieder
  *   Co-authors:
- *      Reto Grieder
+ *      ...
  *
  */
@@ -59,10 +60,11 @@
     class _CoreExport Core : public OrxonoxClass
     {
-        friend int ::main(int, char**); // sets isDevBuild_s
-
         public:
-            Core();
+            Core(int argc, char** argv);
             ~Core();
             void setConfigValues();
+
+            bool isLoaded() { return this->loaded_; }
+            void tick(const Clock& time);
 
             static Core& getInstance() { assert(Core::singletonRef_s); return *Core::singletonRef_s; }
@@ -72,6 +74,4 @@
             static const std::string& getLanguage();
             static void  resetLanguage();
-
-            static bool isDevBuild() { return Core::isDevBuild_s; }
 
             static void tsetMediaPath(const std::string& path)
@@ -98,4 +98,10 @@
         private:
             Core(const Core&);
+
+            void checkDevBuild();
+            void setExecutablePath();
+            void createDirectories();
+            void setThreadAffinity(int limitToCPU);
+
             void resetLanguageIntern();
             void initializeRandomNumberGenerator();
@@ -105,8 +111,12 @@
             void _tsetMediaPath(const std::string& path);
 
-            static void postMainInitialisation();
-            static void checkDevBuild();
-            static void setExecutablePath();
-            static void createDirectories();
+            // Singletons
+            ConfigFileManager*    configFileManager_;
+            Language*             languageInstance_;
+            LuaBind*              luaBind_;
+            Shell*                shell_;
+            SignalHandler*        signalHandler_;
+            TclBind*              tclBind_;
+            TclThreadManager*     tclThreadManager_;
 
             int softDebugLevel_;                            //!< The debug level
@@ -117,4 +127,6 @@
             bool bInitializeRandomNumberGenerator_;         //!< If true, srand(time(0)) is called
             std::string mediaPathString_;                   //!< Path to the data/media file folder as string
+            bool isDevBuild_;                               //!< True for builds in the build directory (not installed)
+            bool loaded_;                                   //!< Only true if constructor was interrupted
 
             static bool bShowsGraphics_s;                   //!< global variable that tells whether to show graphics
@@ -124,6 +136,4 @@
             static bool bIsMaster_s;
 
-            static bool isDevBuild_s;                       //!< True for builds in the build directory (not installed)
-
             static Core* singletonRef_s;
     };
Index: code/branches/gui/src/orxonox/Main.cc
===================================================================
--- code/branches/gui/src/orxonox/Main.cc	(revision 2798)
+++ code/branches/gui/src/orxonox/Main.cc	(revision 2799)
@@ -34,17 +34,12 @@
 
 #include "OrxonoxStableHeaders.h"
+#include "OrxonoxConfig.h"
 
 #include <exception>
 #include <cassert>
 
-#include "OrxonoxConfig.h"
 #include "util/Debug.h"
-#include "util/SignalHandler.h"
-#include "core/ConfigFileManager.h"
-#include "core/CommandLine.h"
-#include "core/CommandExecutor.h"
+#include "core/Core.h"
 #include "core/Identifier.h"
-#include "core/Core.h"
-#include "core/Language.h"
 
 #include "gamestates/GSRoot.h"
@@ -85,39 +80,17 @@
 
 
-SetCommandLineArgument(settingsFile, "orxonox.ini");
-SetCommandLineArgument(configFileDirectory, "");
 
 int main(int argc, char** argv)
 {
-    using namespace orxonox;
-
-    // Parse command line arguments
-    try
+    orxonox::Core* core = new orxonox::Core(argc, argv);
+    if (!core->isLoaded())
     {
-        CommandLine::parseAll(argc, argv);
+        COUT(0) << "Core was not fully loaded, probably an exception occurred during consruction. Aborting" << std::endl;
+        abort();
     }
-    catch (ArgumentException& ex)
-    {
-        COUT(1) << ex.what() << std::endl;
-        COUT(0) << "Usage:" << std::endl << "orxonox " << CommandLine::getUsageInformation() << std::endl;
-    }
-
-    // Do this after parsing the command line to allow customisation
-    Core::postMainInitialisation();
-
-    // create a signal handler (only active for linux)
-    SignalHandler signalHandler;
-    signalHandler.doCatch(argv[0], Core::getLogPathString() + "orxonox_crash.log");
-
-    // Create the ConfigFileManager before creating the GameStates in order to have
-    // setConfigValues() in the constructor (required).
-    ConfigFileManager* configFileManager = new ConfigFileManager();
-    configFileManager->setFilename(ConfigFileType::Settings, CommandLine::getValue("settingsFile").getString());
-    // create the Core settings to configure the output level
-    Language* language = new Language();
-    Core*     core     = new Core();
 
     // put GameStates in its own scope so we can destroy the identifiers at the end of main().
     {
+        using namespace orxonox;
         // create the gamestates
         GSRoot root;
@@ -143,15 +116,10 @@
     }
 
-    // destroy singletons
+    // Destroy pretty much everyhting left
     delete core;
-    delete language;
-    delete configFileManager;
 
     // Clean up class hierarchy stuff (identifiers, xmlport, configvalue, consolecommand)
-    Identifier::destroyAllIdentifiers();
-    // destroy command line arguments
-    CommandLine::destroyAllArguments();
-    // Also delete external console command that don't belong to an Identifier
-    CommandExecutor::destroyExternalCommands();
+    // Needs to be done after 'delete core' because of ~OrxonoxClass
+    orxonox::Identifier::destroyAllIdentifiers();
 
     return 0;
Index: code/branches/gui/src/orxonox/gamestates/GSGraphics.h
===================================================================
--- code/branches/gui/src/orxonox/gamestates/GSGraphics.h	(revision 2798)
+++ code/branches/gui/src/orxonox/gamestates/GSGraphics.h	(revision 2799)
@@ -31,7 +31,7 @@
 
 #include "OrxonoxPrereqs.h"
-#include <OgrePrerequisites.h>
 #define NOMINMAX // required to stop windows.h screwing up std::min definition
 #include <OgreWindowEventUtilities.h>
+#include <OgreLog.h>
 #include "core/GameState.h"
 #include "core/OrxonoxClass.h"
Index: code/branches/gui/src/orxonox/gamestates/GSRoot.cc
===================================================================
--- code/branches/gui/src/orxonox/gamestates/GSRoot.cc	(revision 2798)
+++ code/branches/gui/src/orxonox/gamestates/GSRoot.cc	(revision 2799)
@@ -33,28 +33,12 @@
 #include "util/Debug.h"
 #include "core/Core.h"
-#include "core/Factory.h"
 #include "core/ConfigValueIncludes.h"
 #include "core/CoreIncludes.h"
 #include "core/ConsoleCommand.h"
-#include "core/CommandLine.h"
-#include "core/Shell.h"
-#include "core/TclBind.h"
-#include "core/TclThreadManager.h"
-#include "core/LuaBind.h"
 #include "tools/Timer.h"
 #include "objects/Tickable.h"
 
-#ifdef ORXONOX_PLATFORM_WINDOWS
-#  ifndef WIN32_LEAN_AND_MEAN
-#    define WIN32_LEAN_AND_MEAN
-#  endif
-#  define NOMINMAX // required to stop windows.h screwing up std::min definition
-#  include "windows.h"
-#endif
-
 namespace orxonox
 {
-    SetCommandLineArgument(limitToCPU, 1).information("0: off | #cpu");
-
     GSRoot::GSRoot()
         : RootGameState("root")
@@ -62,7 +46,4 @@
         , bPaused_(false)
         , timeFactorPauseBackup_(1.0f)
-        , tclBind_(0)
-        , tclThreadManager_(0)
-        , shell_(0)
     {
         RegisterRootObject(GSRoot);
@@ -87,7 +68,4 @@
     void GSRoot::enter()
     {
-        // creates the class hierarchy for all classes with factories
-        Factory::createClassHierarchy();
-
         // reset game speed to normal
         timeFactor_ = 1.0f;
@@ -100,21 +78,4 @@
         this->avgTickTime_ = 0.0f;
 
-        // Create the lua interface
-        this->luaBind_ = new LuaBind();
-
-        // initialise TCL
-        this->tclBind_ = new TclBind(Core::getMediaPathString());
-        this->tclThreadManager_ = new TclThreadManager(tclBind_->getTclInterpreter());
-
-        // create a shell
-        this->shell_ = new Shell();
-
-        // limit the main thread to the first core so that QueryPerformanceCounter doesn't jump
-        // do this after ogre has initialised. Somehow Ogre changes the settings again (not through
-        // the timer though).
-        int limitToCPU = CommandLine::getValue("limitToCPU");
-        if (limitToCPU > 0)
-            setThreadAffinity((unsigned int)(limitToCPU - 1));
-
         {
             // add console commands
@@ -156,10 +117,4 @@
         delete this->ccSelectGameState_;
 
-        delete this->shell_;
-        delete this->tclThreadManager_;
-        delete this->tclBind_;
-
-        delete this->luaBind_;
-
         if (this->ccSetTimeFactor_)
         {
@@ -179,5 +134,5 @@
         uint64_t timeBeforeTick = time.getRealMicroseconds();
 
-        TclThreadManager::getInstance().tick(time.getDeltaTime());
+        Core::getInstance().tick(time);
 
         for (ObjectList<TimerBase>::iterator it = ObjectList<TimerBase>::begin(); it; ++it)
@@ -235,45 +190,4 @@
 
     /**
-    @note
-        The code of this function has been copied and adjusted from OGRE, an open source graphics engine.
-            (Object-oriented Graphics Rendering Engine)
-        For the latest info, see http://www.ogre3d.org/
-
-        Copyright (c) 2000-2008 Torus Knot Software Ltd
-
-        OGRE is licensed under the LGPL. For more info, see OGRE license.
-    */
-    void GSRoot::setThreadAffinity(unsigned int limitToCPU)
-    {
-#ifdef ORXONOX_PLATFORM_WINDOWS
-        // Get the current process core mask
-        DWORD procMask;
-        DWORD sysMask;
-#  if _MSC_VER >= 1400 && defined (_M_X64)
-        GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&procMask, (PDWORD_PTR)&sysMask);
-#  else
-        GetProcessAffinityMask(GetCurrentProcess(), &procMask, &sysMask);
-#  endif
-
-        // If procMask is 0, consider there is only one core available
-        // (using 0 as procMask will cause an infinite loop below)
-        if (procMask == 0)
-            procMask = 1;
-
-        // if the core specified with limitToCPU is not available, take the lowest one
-        if (!(procMask & (1 << limitToCPU)))
-            limitToCPU = 0;
-
-        // Find the lowest core that this process uses and limitToCPU suggests
-        DWORD threadMask = 1;
-        while ((threadMask & procMask) == 0 || (threadMask < (1u << limitToCPU)))
-            threadMask <<= 1;
-
-        // Set affinity to the first core
-        SetThreadAffinityMask(GetCurrentThread(), threadMask);
-#endif
-    }
-
-    /**
     @brief
         Changes the speed of Orxonox
Index: code/branches/gui/src/orxonox/gamestates/GSRoot.h
===================================================================
--- code/branches/gui/src/orxonox/gamestates/GSRoot.h	(revision 2798)
+++ code/branches/gui/src/orxonox/gamestates/GSRoot.h	(revision 2799)
@@ -33,5 +33,4 @@
 
 #include <list>
-#include <OgreLog.h>
 #include "core/RootGameState.h"
 #include "core/OrxonoxClass.h"
@@ -76,13 +75,8 @@
 
         void setConfigValues();
-        void setThreadAffinity(unsigned int limitToCPU);
 
         float                 timeFactor_;       //!< A factor that sets the gamespeed. 1 is normal.
         bool                  bPaused_;
         float                 timeFactorPauseBackup_;
-        TclBind*              tclBind_;
-        TclThreadManager*     tclThreadManager_;
-        Shell*                shell_;
-        LuaBind*              luaBind_;
 
         // variables for time statistics
Index: code/branches/gui/src/orxonox/objects/worldentities/Model.cc
===================================================================
--- code/branches/gui/src/orxonox/objects/worldentities/Model.cc	(revision 2798)
+++ code/branches/gui/src/orxonox/objects/worldentities/Model.cc	(revision 2799)
@@ -31,4 +31,5 @@
 #include <OgreEntity.h>
 #include "Model.h"
+#include "core/Core.h"
 #include "core/CoreIncludes.h"
 #include "core/XMLPort.h"
Index: code/branches/gui/src/orxonox/objects/worldentities/ParticleEmitter.cc
===================================================================
--- code/branches/gui/src/orxonox/objects/worldentities/ParticleEmitter.cc	(revision 2798)
+++ code/branches/gui/src/orxonox/objects/worldentities/ParticleEmitter.cc	(revision 2799)
@@ -39,4 +39,5 @@
 #include "tools/ParticleInterface.h"
 #include "util/Exception.h"
+#include "core/Core.h"
 #include "core/CoreIncludes.h"
 #include "core/XMLPort.h"
